Junior — Middle
What is the difference between declaring variables using the keywords var and let, and what are their features?
sobes.tech AI
Answer from AI
In JavaScript (and Node.js), the keywords var and let are used for declaring variables, but they have important differences:
-
Scope:
varhas function scope. This means a variable declared withvarinside a function is visible throughout the entire function.lethas block scope. The variable is only visible within the nearest enclosing{}.
-
Hoisting:
- Variables declared with
varare hoisted to the top of their scope and initialized withundefined. - Variables with
letare also hoisted but not initialized, leading to a Temporal Dead Zone until the declaration is processed.
- Variables declared with
-
Re-declaration:
varallows re-declaring the same variable within the same scope.letdoes not allow re-declaring a variable within the same scope.
Example:
function example() {
console.log(a); // undefined
// console.log(b); // Error: cannot access before declaration
var a = 1;
let b = 2;
if (true) {
var a = 3; // reassigns the variable a in the function scope
let b = 4; // new variable b in the if block
console.log(b); // 4
}
console.log(a); // 3
console.log(b); // 2
}
example();
Using let is preferable for better scope control and to prevent errors related to re-declaration and unexpected var behavior.