Yozex
Yozex

Reputation: 73

javascript closures and local variable 'remembering'

Question is about JS closures. I have red the definitions and examples of it, and I believe I fairly understand the mechanism. So, the question is about specific thing I do not understand. Please consider following two codes. Code 1:

function a(){
let x = 5;
return function b(y){
    x=x+y;
    return x;
};
}

let c = a();
let d = c(3);
let e = c(4);
console.log(d);  // logs 8
console.log(e);  // logs 12

Code 2:

function a(){
let x = 5;
return function b(y){
    x=x+y;
    return x;
};
}

let d = a()(3);
let e = a()(4);
console.log(d);  //logs 8
console.log(e);  //logs 9

Question: In code 1 x changes its value and the new value is saved in a closure. In code 2 x changes its value and the new value is not saved. Why is that?

Upvotes: 1

Views: 420

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

It's because in the second example, you're calling a a second time, while in the first one a is only called once. Each time you call a, the value of x is initialised as 5. It is the inner function which is returned which creates the closure, and the value of x is remembered between invocations of that function. But each time you return a new function from a, it initially has access to an x which holds the value 5.

Upvotes: 2

Related Questions