JavaScript Closures Made Simple

Learn about JavaScript lexical scoping and closures with simple examples anyone can understand.

Note - To understand closures, we first need to know what lexical scoping is.

What is Lexical Scoping?

  • Lexical scoping means that a variable’s visibility is determined by where it is written in the code.
  • It’s also called static scoping.
  • Let’s look at a simple example:
function outer() {
    const greeting = "Hello";
    function inner() {
        console.log(greeting);
    }
    inner();
}
outer(); // Output: Hello

console.log(greeting); // ReferenceError: greeting is not defined
  • In this example, the inner() function can access the greeting variable from outer() because it is written inside the outer() function.
  • This happens due to lexical scoping, where inner functions can use variables from their parent function.

What is a Closure?

  • A closure is a function that remembers and uses variables from the place where it was created, even after that outer function is done running.

Here’s an example:

function outer() {
    const greeting = "Hello";
    return function inner() {
        console.log(greeting);
    };
}
const closureFunction = outer(); // This returns the inner function
closureFunction(); // Output: Hello
  • Here, the inner() function is returned by outer() and saved in closureFunction.
  • When we call closureFunction(), it still remembers the greeting variable from outer(), even though outer() has already finished.