Tell us what’s happening:
printNumTwo()
returned the correct value because three different i
variables with unique values (0, 1, and 2) were created by the let
keyword within the loop statement.
I don’t understand the above explanation, can someone please explain?
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"
printNumTwo is declared outside the for loop, console.log(i) returns not define because i declared in only the for loop, we can’t access outside that loop.
1 Like
I don’t understand why the explanation says that 3 different ‘i’ with unique values (0,1 and 2) were created.
Loop runs once, i is 0
Loop runs again, i is 1
Loop runs again, i is 2
@DanCouper But i gets updated right? it doesn’t store 0 and 1?