Variable
Example
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}var is function-scoped, so it logs 3, 3, 3; let creates a new binding per pass and logs 0, 1, 2.
Common mistakes
- A
varinside a loop is shared by every callback, so all of them see the last value.
Key points
- New JavaScript code declares variables with
constorlet, notvar. - Variables have descriptive names, not
x,data2ortemp. - Each variable is declared in the smallest scope that needs it.
Interview questions
What is the difference between a variable and a constant?
A variable can be reassigned while the program runs. A constant keeps the value it got first.
Should I use let or const in JavaScript?
Use const by default and let only when the value must be reassigned.