JavaScript Closure Tutorial

In this section, we will learn what the Closure is and how does it works in JavaScript.

What is Closure in JavaScript?

Closure is when a function “remembers” its scope, even when the function is executed outside that scope.

We know that a function can return a value via the `return` keyword. This return value can also be another function!

Now let’s see how returning another function as a result of calling a function relates to the topic of Closure.

Closure in JavaScript Example:

function foo(){
  let fullName = "John Doe";
  return function boo(){
    console.log(fullName);
  }
}
let ext = foo();
ext();

Output:

John Doe

How Does JavaScript Closure work?

Here there’s a function named `foo` that returns another function named `boo` when we call it.

So the output of this function is another function that can be invoked as well.

Also, in the body of the `foo` function, there’s a variable named `fullName`.

In the example above, we invoked the `foo()` function and assigned the result to the variable `ext`. So after the execution of the `foo()` function, the `ext` stored the memory address in which the `boo()` function’s body is. This means the `ext` represents the `boo()` function and so can be invoked as well. This is what we’ve done in the last statement.

Now if we look at the browser’s console, we can see that the value of the variable `fullName` is on the console. (“John Doe”).

This is because when the `boo` function is invoked via the `ext` variable, the execution engine will invoke the body of the function and its scope as well.

This means in the body of the `boo` function when the call to the `console.log(fullName);` statement occurred, first the scope of the `boo` function will be checked to see if the `fullName` is declared there. If the variable is not registered in this scope, the linked scope (the one that the `boo` function is defined in) will be checked next.

So because the enclosing function (the `foo` function) has such a variable, the execution engine will use that variable’s value and update the target statement.

So the statement will be updated like this: `console.log(“John Doe”);`.

Finally, the message `John Doe` will appear on the console.

This is closure. As you can see, we’ve invoked the `boo()` function outside of the body of the `foo()` function, which is the enclosing scope of the `boo`. But yet the `boo` function stayed connect with its scope even though it is being invoked outside of its scope.

So in short, a function won’t lose its scope (its own scope and the other scopes that are linked to) no-matter where we invoke it. Basically, it will always return to the place in which its body is declared.

Note: If you read the hoisting section, you’ll realize that you’ve been working with closure all along but just didn’t use the term `closure`!

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies