Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
What is the difference between var, let, and const in JavaScript?
Asked on Mar 07, 2026
Answer
In JavaScript, "var", "let", and "const" are used to declare variables, but they differ in terms of scope, hoisting, and mutability. Here's a concise example to illustrate these differences:
// var: function-scoped or globally-scoped
var x = 1;
if (true) {
var x = 2; // same variable, reassigns x
console.log(x); // 2
}
console.log(x); // 2
// let: block-scoped
let y = 1;
if (true) {
let y = 2; // different variable, block-scoped
console.log(y); // 2
}
console.log(y); // 1
// const: block-scoped, cannot be reassigned
const z = 1;
if (true) {
const z = 2; // different variable, block-scoped
console.log(z); // 2
}
console.log(z); // 1Additional Comment:
✅ Answered with JavaScript best practices.- "var" is function-scoped or globally-scoped and can be redeclared and updated.
- "let" is block-scoped, can be updated but not redeclared in the same scope.
- "const" is block-scoped, cannot be updated or redeclared, but objects and arrays declared with "const" can be mutated.
- "var" is hoisted to the top of its scope and initialized with "undefined", while "let" and "const" are hoisted but not initialized.
Recommended Links:
