DEV Community

Cover image for A quick explanation/example of closure in JS
Daniel Joo
Daniel Joo

Posted on

A quick explanation/example of closure in JS

Hope everyone is staying safe and healthy during these crazy times! Just wanted to briefly explain the main concepts of closure, along with providing an example that highlights these concepts. So let's dive right in.

What is closure?

Simply put, closure occurs when a function accesses a variable that is outside its scope. This function is also invoked in a different scope from that of the variable. We can say that a function 'closes' over that variable. In easier terms, a function has access to a variable that is outside the function. Closure can only happen through an invoked function that references a variable(s) that is outside the function and outside the function's scope.

Enough words and abstract ideas, let's see this in a concrete example:

var day = "Friday";

var hello = function dayOfTheWeek() {
    // we are closing over `day`,
    console.log(
        `Today is ${ day }.`
    );
}

day = "Saturday";

hello();
// Today is Saturday.

In this example, the function dayOfTheWeek is called and closes over the variable day. day is declared and is assigned the value 'Friday,' but is later reassigned the value of 'Saturday'. This concept might seem very similar to scope, but the key difference is this: closure applies specifically to functions. Each time a function like dayOfTheWeek is called, there is a new closure. In Javascript, closure ensures that outside variables, which may be in an outer, enclosing function, are not garbage-collected (or GC'ed) once that outer function is done running. Closure allows the inner-scope function to have live access to those variables.

Here is another example, which might be very confusing at first.

var keeps = [];

for (var i = 0; i < 3; i++) {
    keeps[i] = function keepI(){
        // closure over `i`
        return i;
    };
}

keeps[0]();   // 3 
keeps[1]();   // 3
keeps[2]();   // 3

You might expect the function calls at the end to produce the outputs 0,1, and 2. However, 3 is returned for all three. Why? It's because of closure. The function keepI is called inside the for loop, and closes over the global var i during each instance of the loop. Although each function instance has its own closure, it closes over the same variable i, which takes on the value of 3 at the end of the loop.

Top comments (0)