a)
for (var i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1);
}
b)
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1);
}
a) a) 0 1 2 3 4; b) 5 5 5 5 5
b) a) 5 5 5 5 5; b) 0 1 2 3 4
c) a) 5 5 5 5 5; b) 5 5 5 5 5
Expand the correct answer with an explanation
First we need to understand what is the difference between var
and let
. The scope of a variable declared with var
is its current execution context. Which can be limited to the function or be global to variables declared outside the function. However, var
has one weakness. Let's take a look at the example below.
var greeting = 'say hi';
var times = 4;
if (times > 3) {
var greeting = 'say Hello instead';
}
console.log(greeting); // "say Hello instead"
As you can see, since the times > 3
condition returns true
, the value of the greeter
variable is redefined as say Hello instead
. If you unconsciously use greeting
elsewhere in your code, you will get unpredictable results. This can cause a lot of bugs in your code. This is why there is a need for let
and const
.
let
has block scope. A block is a piece of code delimited by curly braces {}
. Everything inside the curly braces belongs to the block. Thus, a variable declared in a block with let
will only be available within that block. Let's now look at another example.
let times = 4;
if (times > 3) {
let greeting = 'say Hello';
console.log(greeting); // "say Hello"
}
console.log(greeting); // ReferenceError: greeting is not defined
From this example, we can see that trying to use greeting
outside of a block (the curly braces within which the variable was defined) will return an error, since let
is block scoped.
So, back to the task. Since setTimeout
is executed asynchronously, and one millisecond is a very long time for a computer, the passed callback will be called after the loop has completed.
In the case of a, the variable i
is declared with the var
keyword, so it is global. It will be overwritten every iteration, and when setTimeout
is called, it will have its last value of 5
, so 5 5 5 5 5
will be sequently printed to the console .
In the case of b, the variable i
is already declared via let
and has block scope. It means that it’s only available in the scope of the for
loop. During each iteration, the variable will have a new value, and after the code executing, 0 1 2 3 4
will be displayed in the console.
Therefore, the correct answer is a) 5 5 5 5 5; b) 0 1 2 3 4