Why in Example 1 and Example 2 return different results? A conter variable(example 1) instance still has access from the global scope.
Example 1:
const increment = (()=> {
let counter = 0;
//console.log(counter);
const credits = (num) => console.log(`I have ${num} credit(s).`);
return () => { counter ; credits(counter); }
})();
increment();//I have 1 credit(s).
increment();//I have 2 credit(s).
Example 2:
function a() {
let counter = 0;
const credits = (num) => console.log(`I have ${num} credit(s).`);
return () => { counter ; credits(counter); }
}
a()();//I have 1 credit(s).
a()();//I have 1 credit(s).
Thanks.
CodePudding user response:
The let counter
line initializes a counter
variable. This will occur whenever that line runs.
In the first example, you run that line once when you invoke the IIFE with })()
at the end, and the function returned by the IIFE references that one counter
variable you initialized.
In the second example, you run that line every time the a
function runs - a new counter
variable is created every time you do a()
. So if you do a()()
, you create one counter variable, increment it in the returned function, log it, and then discard it (since the counter
can't be referenced by anything anymore). Calling a()()
and then a()()
results in two separate counter
variables, both of which you increment by 1 and log.
If you wanted to log 2 by tweaking the second example, assign the returned function to a variable before calling it, then call that returned function twice (instead of calling a
twice).
function a() {
let counter = 0;
const credits = (num) => console.log(`I have ${num} credit(s).`);
return () => { counter ; credits(counter); }
}
const fn = a();
fn();//I have 1 credit(s).
fn();//I have 2 credit(s).
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>