Skip to main content

Command Palette

Search for a command to run...

[JavaScript] Closure

Published
•View as Markdown
[JavaScript] Closure
const secureBooking = function () {
  let passengerCount = 0;

  return function () {
    passengerCount++;
    console.log(`${passengerCount} passengers`);
  };
};

const booker = secureBooking();

booker();
booker();
booker();

console.dir(booker);

closure 1.PNG


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.

JavaScript

Part 1 of 50

More from this blog

Jayden's Blog

166 posts