One issue arises when a variable exits its scope and gets destroyed. Upon the next value call, it will be recreated with its initial value. In this case, the variable i
is scoped within the increment
function, which in turn is within the scope of myFunc
. This means that each time myFunc
is executed, the closure is destroyed and then created again.
An illustrative example showcases how i
is hoisted to the scope of
myFunc</code, with the <code>increment
function being called multiple times:
function myFunc() {
console.log('running myFunc');
var i = 0;
console.log('assigning i to ' + i);
function increment() {
console.log('incrementing');
i++;
};
increment();
increment();
console.log(`calling myFunc ${i} times`);
}
myFunc();
It can be observed that i
retains its state across invocations of the increment
function. Whenever we call myFunc
repeatedly, we witness the destruction and recreation of i
each time myFunc
is invoked.
function myFunc() {
console.log('running myFunc');
var i = 0;
console.log('assigning i to ' + i);
function increment() {
console.log('incrementing');
i++;
}
increment();
increment();
console.log(`calling myFunc ${i} times`);
}
myFunc();
myFunc();
If we lift i
outside the scope of myFunc
, we notice that its value persists across calls to myFunc
.
var i = 0;
console.log('assigning i to ' + i);
function myFunc() {
console.log('running myFunc');
function increment() {
console.log('incrementing');
i++;
}
increment();
console.log(`calling myFunc ${i} times`);
}
myFunc();
myFunc();