Closures are related and often confused with lambda functions.
The 2 concepts are wonderfully explained and distinguished
in this StackOverflow answer :
https://stackoverflow.com/a/36878651/13574304
function Counter() {
var counter = 0;
alert("XXXXX");
function increaseCounter()
{
return counter +=1;
}
return increaseCounter;
}
/***/
const counter = new Counter();
console.log(counter());
console.log(counter());
/*note that alert("XXXX") only executes once*/
/*think of counter() = new Counter() declaration as storing the value of ONE Counter function execution and
the remaining times you use counter(), you reexecute only the returned function*/
/*use counter() instead of Counter() if you want alert("XXXX") to execute only once AND for you to be able to return an actual value otherwise you only console.log a function and alert executes multiple times*/
// Closures
//Almost mystical like feature that many developers fail to fully understand.
//We cannot create closures manually like how we create arrays and functions.
//Rather closures happen in certain situations. We just need to recognize
//those situations.
//Example:
const secureBooking = function () {
let passengerCount = 0; //Variable of the secureBooking Function
//returns a function
return function () {
passengerCount++; //Adding to the passengerCount
console.log(passengerCount);
};
};
const book = secureBooking(); //capture that function
book();
//In the above example we have a function called secureBooking
//That function returns another function, which we stored in book variable
//We then call the book() function and it adds to the passengerCount.
//But you may be wondering? How can it add to the passengerCount
//if the secureBooking has finished executing, shouldn't it not exist?
//This works because all functions have access to the variable environment
// in which they were created in. Meaning since secureBooking created
// the function which we stored in book. The book function now has
// access to the variable environment of secureBooking function.
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
var returns_a_func = function () {
var word = 'I can see inside ' function sentence(){ var word2 = 'I can also see outside. ' console.log(word + 'and ' + word2) } return sentence;
}var finalSentence = returns_a_func()finalSentence()
function makeFunc() {
const name = 'Mozilla';
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();
const add = (function () {
let counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// the counter is now 3
Cannot GET /about-us.html