Tell us what’s happening:
I am working on the lesson titled “ES6: Compare Scopes of the var and let Keywords.” I am comparing various blocks of code in the explanation section and tinkering with them using the “Inspect > console” feature of my browser (the latest version of Google Chrome) to try to fully understand them.
Problem is, my results in the browser don’t match what is given in the lesson.
Lesson code reads:
'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"
However, when I copy and paste that same code into the console, I don’t get the return vales of 2 and undefined. What I get is this:
VM184:1 Uncaught SyntaxError: Identifier 'printNumTwo' has already been declared
at <anonymous>:1:1
I don’t understand the problem.
Perhaps I should add that when I try deleting the line that declares the variable and instead just declare and define the variable on the same line of code like this…
'use strict';
for (let i = 0; i < 3; i++) {
if (i === 2) {
let printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
console.log(i);
… I get very different results: 3 and 3.
I am very confused.
Thanks in advance for your help.
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords