Technically what is a closure in Javascript?

Hi, in my Javascript career I have come across 2 very interesting questions one is – What is a callback in JS? and the other one is – What is a closure in Javascript? and at the beginning was a very confused to try to understand the answers for this 2 questions. For the first question you can read my post about callbacks 🙂 and for closures stay in this page to learn more about it.

A closure is nothing more that a function that a reference to a private variable.

Let see this code:

We have a simple function that give us the name that we are passing as a parameter (that is!), then we are creating the “me” object starting from Person (see …new Person line)

// Function to obtain name
function Person(name) {
    this.name = name;
}

// Instantiating Person to create "me" object 
let me = new Person('Cristina');

// Printing "me" object
console.log(me.name);

Result: Nice, we will have the result as we expected.

Now if we change the code – removing “this.name” that is inside the function and instead we declare a variable “var name = name” this variable only will exist in the scope of the Person function.

// Function to obtain name
function Person(name) {
    // This variable only exist in the scope of this function
    var name = name; 
}

// Instantiating Person to create "me" object 
let me = new Person('Cristina');

// Printing "me" object
console.log(me);

Result: this will return us an empty object and this is because the variable var name = name; is out of the scope in this point -> let me = new Person(‘Cristina’); so we don’t have a way to access to that variable.

So, a closure what it is:

If in this Person function somehow we still have a way to access to the variable “name” and what we can do for this is create a function called getName() inside of Person function and the getName() function will return the variable “name” that is outside its scope, so getName() will keep the reference to “name” even if the Person function was already executed.

Note: Remember that whenever a function is executed (or called/invoked), a new execution context gets created.

// Function to get name
function Person(paramName) {
    // This variable only exist in the scope of this function
    var name = paramName; 

    this.getName = function() {
        return name;
    };
}

// Instantiating Person to create "me" object 
let me = new Person('Cristina');

// Printing "me" object
console.log(me.getName());

Result:

So, in simple terms a closure “A closure in JavaScript where an inner function has access to the outer (enclosing) function’s variables”

This closure will keep/hold the reference to that variables and that’s why we can have expected results.

The closure has three scope chains:

  • it has access to its own scope — variables defined between its curly brackets
  • it has access to the outer function’s variables
  • it has access to the global variables

By Cristina Rojas.