Closure in Javascript

jasmine
2 min readAug 26, 2022

--

In JavaScript, closure provides access to the outer scope of a function from inside the inner function, even after the outer function has closed. For example,



function calculate(x) {
function multiply(y) {
return x * y;
}
return multiply;
}

const multiply3 = calculate(3);
const multiply4 = calculate(4);

console.log(multiply3); // returns calculate function definition
console.log(multiply3()); // NaN

console.log(multiply3(6)); // 18
console.log(multiply4(2)); // 8

In the above program, the calculate() function takes a single argument x and returns the function definition of the multiply() function. The multiply() function takes a single argument y and returns x * y.

Both multiply3 and multiply4 are closures.

Whenever a function is invoked, a new scope is created for that call. The local variable declared inside the function belong to that scope — they can only be accessed from that function

function buildName(name) {var greeting = "Hello, " + name + "!";var sayName = function() {var welcome = greeting + " Welcome!";console.log(greeting);};return sayName;}var sayMyName = buildName("John");sayMyName();  // Hello, John. Welcome!sayMyName();  // Hello, John. Welcome!

The function sayName() from this example is a closure.

A closure is a function which has access to the variable from another function’s scope. This is accomplished by creating a function inside a function. Of course, the outer function does not have access to the inner scope.

Another extremely important thing to understand is that a closure is created at every function call. Whenever I’m using the closure, it will reference the same outer scope. If any variable is change in the outer scope, than the change will be visible in the next call as well.

function buildContor(i) {var contor = i;var displayContor = function() {console.log(contor++);contor++;};return displayContor;}
var myContor = buildContor(1);myContor(); // 1myContor(); // 2myContor(); // 3// new closure - new outer scope - new contor variablevar myOtherContor = buildContor(10);myOtherContor(); // 10myOtherContor(); // 11

--

--