[JavaScript] Closure
![[JavaScript] Closure](https://cdn.hashnode.com/res/hashnode/image/unsplash/g5jpH62pwes/upload/v1655864663230/KkXNUaO4X.jpeg)
const secureBooking = function () {
let passengerCount = 0;
return function () {
passengerCount++;
console.log(`${passengerCount} passengers`);
};
};
const booker = secureBooking();
booker();
booker();
booker();
console.dir(booker);
Closure?
👉 A closure is the closed-over variable environment of the execution context in which a function was created, even after that execution context is gone.
👉 A closure gives function access to all the variables of its parent function, even after that parent function has returned. The function keeps a reference to its outer scope, which preserves the scope chain throughout time.
👉 A closure makes sure that a function doesn’t loose connection to variables that existed at the function’s birthplace ('hometown').
👉 A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were present in the environment where the function was created.
☝ We do NOT have to manually create closures, this is a JavaScript feature that happens automatically. We can’t even access closed-over variables explicitly. A closure is NOT a tangible JavaScript object.