Introduction
Javascript has multiple ways of declaring variables in the code as given below. However each type of usage has its own context.
let x = 10;
const y =10;
var z = 10
Problem Statement
I recently came across a problem statement regarding the above type of variable declaration and usage
Snippet: 1
In the below snippet, the output will be 3,3,3. The reason for this behavior is that in javascript, the variable defined as var will be referring to the address of i since it has a function scope so, whenever the value of i is incremented, the change will be reflected inside the setTimeout method as well as they are pointing to the same address
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
Snippet2
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
In the above snippet, we have used a variable with let keyword which has a block scope, so there is a copy of i inside the setTimeout. Hence the above snippet always outputs 0,1,2 as the value is defined, initialized and used within the block rather than lookup to the function that uses the variable.
Solution
The right choice of the types of declaring variables should be thought through, in order to avoid runtime weird behavior and then figuring out the right ways to use.
Comments
Post a Comment