Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
What is the difference between `let` and `var` in JavaScript? Pending Review
Asked on Apr 21, 2026
Answer
In JavaScript, "let" and "var" are both used to declare variables, but they have important differences in terms of scope and hoisting behavior.
// Example of 'let'
function letExample() {
let x = 10;
if (true) {
let x = 20; // Different scope
console.log(x); // 20
}
console.log(x); // 10
}
// Example of 'var'
function varExample() {
var y = 10;
if (true) {
var y = 20; // Same scope
console.log(y); // 20
}
console.log(y); // 20
}
letExample();
varExample();Additional Comment:
✅ Answered with JavaScript best practices.- "let" is block-scoped, meaning it is limited to the block in which it is defined (e.g., inside an "if" or "for" block).
- "var" is function-scoped or globally-scoped, which means it is accessible throughout the function or globally if declared outside a function.
- "let" does not allow re-declaration in the same scope, while "var" does.
- Both "let" and "var" are hoisted, but "let" is not initialized until the variable is defined, leading to a "temporal dead zone" if accessed before declaration.
Recommended Links:
