Articles
Back to TopMenu...
 

JavaScript Closure

One of the advanced concepts in JavaScript is closure. In this article, we will try to explain what closure is in JavaScript with practical examples.

What is a Closure in JavaScript?

Let's see what JavaScript closure is based on this definition from w3Schools.com:

A closure is a function having access to the parent scope, even after the parent function has closed.

Based on the definition above, we'll break down an example of JavaScript closure code.

This is the code to analyzed:

const outerFunction = (outParam) => {
    let outerVar = 21;

    const innerFunction = () => {
        console.log(outParam + outerVar );
    }
    return innerFunction;
}

In this code we have two functions:

  1. outerFunction is the parent function and in its scope we have outParam and externalVar (of course, plus the global scope).
  2. innerFunction is the child function and by the structure of the code it can access outParam and outerVar (of course, plus the global scope), in other word outerFunction scope.

Conclusion innerFunction is a function having access to the parent outerFunction scope. The last condition in the defintion is innerFunction should have access to outerFunction event after outerFunction has closed. So let put the return of outerFunction in a variable result in the following code:

const result = outerFunction(6);

With console.log of result, you notice that it is the same function as innerFunction

console.log(result)
() => {
        console.log(outParam + outerVar );
    }

At this point outerFunction has closed but when we execute result we have 27. So where it find the 27 result? To discover this let run console.dir on result.

console.log(result()); //27

console.dir(result);

result dir

You can see under scopes session that result ie innerFunction can access his itseft, outerFunction and global scope. More you can see under Scopes/Closure that only the variables outParam and outerVar are availables but those variables also hold the values they had during the execution of the outerFunction.

Explanation of closure with execution context

In the session above, we give a definition of closure and use an example to illustrate the definition. Here we will try to give a more detailed explanation using another advanced concept of JavaScript, the execution context.

In this article, we are not going to explain or detail execution context and in cas you don't know the concept I will encourage you to learn because it will help you understand more some other concept in JavaScript like Hoisting, Scope etc.

So let

Practical example

Closure in Loops

Emulating private methods with closures