This article explains the difference between “var” and “let” in JavaScript.
Let’s learn the differences between “var” and “let”, such as scope, reassignability, variable declaration timing, and traps.
What is the difference between “var” and “let”?
Differences between “var” and “let” include scope, reassignability, variable declaration timing, and traps.
Differences regarding scope
“var” and “let” have different scopes .
“var” creates a variable that is valid within function scope, whereas “let” creates a variable that is valid within block scope.
As shown in the sample below, let has a more limited scope.
function varFunction() {
if (true) {
var x = 10;
}
console.log(x); // 10
}
function letFunction() {
if (true) {
let y = 10;
}
console.log(y); // Uncaught ReferenceError: y is not defined
}
Differences in whether reassignment is possible or not
“var” is reassignable , “let” is not reassignable .
Variables declared with “var” can be reassigned at any time. On the other hand, variables declared with “let” cannot be reassigned, so once a value is assigned to a variable, it cannot be reassigned.
This behavior is tied to the scope control feature of “let”, and by using “let” which is not reassignable, you can prevent bugs in your program.
Differences in accessing variables
Regarding the difference between “var” and “let”, there are also differences when declaring variables and accessing variable values.
Variables declared with “var” can be accessed at the time of variable declaration and variable value . On the other hand , variables declared with “let” cannot be accessed before the variable is declared .
If “let” is accessed before it is declared, a “ReferenceError” error will occur.
Article summary
I explained the difference between “var” and “let”.
- Variables declared with “var” can be accessed outside the block scope
- Variables declared with “let” can only be accessed within block scope
- Variables declared with “var” can be reassigned
- Variables declared with “let” can be reassigned
- “var” allows you to declare a variable and access the variable value.
- Variables declared with ‘let’ cannot be accessed before the variable is declared.
I now understand the difference between “var” and “let”.
I hope this will be useful for your future JavaScript coding!
By using “var” and “let” appropriately, you can avoid program bugs and perform more accurate processing.
Also, since “let” is a newer concept than “var”, we recommend using “let” for variable declarations in modern JavaScript.
Comments