Consider the following code:
function test() {
let num = 1;
return function() {
console.log(num);
num++;
};
}
test()(); //shows 1
test()(); //shows 1
Why will the number 1
always be displayed?
In order to understand this, let's
rewrite our code differently:
function test() {
let num = 1;
return function() {
console.log(num);
num++;
};
};
let func1 = test(); // the first function
func1(); // shows 1
let func2 = test(); // the second function
func2(); // shows 1
That is, each function test
call
like this: test()()
creates its
own function with its own closure and
immediately calls this function.
Determine what will be output to the console without running the code:
function func() {
let num = 0;
return function() {
console.log(num);
num++;
};
};
func()();
func()();
func()();
Determine what will be output to the console without running the code:
function func() {
let num = 0;
return function() {
console.log(num);
num++;
};
}
let test = func;
test()();
test()();
test()();