Junior — Middle
What is the difference between variable declarations using var and let in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, the keywords var and let are used for declaring variables, but there are important differences between them:
-
Scope:
varhas function scope. If declared inside a function, the variable is visible throughout the entire function.lethas block scope. The variable is only visible within the nearest enclosing{}.
-
Hoisting:
- Variables declared with
varare hoisted and initialized withundefinedat the beginning of the function. - Variables with
letare also hoisted but not initialized, accessing them before declaration results in a ReferenceError (Temporal Dead Zone).
- Variables declared with
-
Re-declaration:
varallows re-declaring the same variable within the same scope.letdoes not allow re-declaration within the same scope.
Example:
function test() {
if (true) {
var x = 1;
let y = 2;
}
console.log(x); // 1
console.log(y); // Error: y is not defined
}
test();
In modern JavaScript standards, it is recommended to use let (or const for constants) due to more predictable behavior and scope limitation.