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 May 13, 2026
Answer
In JavaScript, "var", "let", and "const" are used for variable declarations, but they differ in scope, hoisting, and mutability. Here's a concise example to illustrate these differences:
// var is function-scoped and can be redeclared
function varExample() {
var x = 1;
if (true) {
var x = 2; // same variable
console.log(x); // 2
}
console.log(x); // 2
}
// let is block-scoped and cannot be redeclared in the same scope
function letExample() {
let y = 1;
if (true) {
let y = 2; // different variable
console.log(y); // 2
}
console.log(y); // 1
}
// const is block-scoped and cannot be reassigned
function constExample() {
const z = 1;
if (true) {
const z = 2; // different variable
console.log(z); // 2
}
console.log(z); // 1
}
varExample();
letExample();
constExample();Additional Comment:
✅ Answered with JavaScript best practices.- "var" is function-scoped, meaning it is accessible throughout the function in which it is declared, and it can be redeclared.
- "let" is block-scoped, meaning it is only accessible within the block it is declared in, and it cannot be redeclared in the same scope.
- "const" is also block-scoped like "let", but it cannot be reassigned after its initial assignment.
- Use "let" and "const" for better code clarity and to avoid issues with variable redeclaration and scope.
Recommended Links:
