Closure Explained!

Let's Define Closure

A closure is a function that makes use of variable defined in outer functions that have previously returned. What does this mean, Let's quickly look at an example.

function outer(a){
    return function inner(b){
        return a + b;
    }
}
outer(5)(5); // 10

In the above code snippet, the function inner uses the variable "a" declared in a function named "outer," and when the function inner is called, the function outer returns the function called "inner," and this is called as a closure!

A few things to note:

  • We have to 'return' the inner function for the above example to work.
  • We can call the inner function right away by using an extra ().
  • We don't have to name the inner function (we just called it "inner" for learning purposes)

How Closures Work

Only variables used in the inner function are stored!
Closures don't remember everything from an outer function - just the variables they require!

Why do I need to know this?

Private Variables

Variables that cannot be updated externally are supported in other languages. These are referred to as private variables, although they are not included in JavaScript. No need to be concerned - closures can assist!

function counter(){
    let count = 0;
    return function(){
        count++;
        return count;
    }
}
const counter1 = counter();
counter1(); // 1
counter1(); // 2

const counter2 = counter();
counter2(); // 1
counter2(); // 2

counter1(); // 3 this is unaffected by counter2.

console.log(count); 
// Uncaught ReferenceError: count is not defined - because it is private!

TL;DR

  • Closure is when an inner function makes use of variables declared in an outer function that has previously returned.
  • JavaScript will only remember values that are being used inside of the inner function, not all variables defined in the outer function.
  • Closures allow us to define private variables and write cleaner code that separates our logic from our application.

Thank you for making it till the end!

20