Difference between var, let, and const in JavaScript
Table of Contents
Before ES6 (2015), JavaScript only had var to declare variables. This caused many bugs due to scoping issues. ES6 introduced let and const to fix these problems. Let's see the differences.
1. var (Function Scoped)
var is function scoped, meaning if you declare it inside a function, it is available throughout that function. However, it ignores block scopes like if or for loops.
if (true) {
var x = 10;
}
console.log(x); // Output: 10 (Wait, what? 😱)
// Since var ignores the 'if' block, 'x' leaked out to the global scope.
Problem: This behavior can accidentally overwrite variables in other parts of your code.
2. let (Block Scoped)
let is block scoped. It only exists inside the curly braces { } where it was declared.
if (true) {
let y = 20;
}
console.log(y); // ❌ Error: y is not defined
// Ideally, variables should not leak outside their block.
3. const (Constant)
const is also block-scoped like let, but it **cannot be reassigned**. Use this for values that should not change.
const PI = 3.14;
PI = 3.15; // ❌ Error: Assignment to constant variable.
Note: If you use const with an Object or Array, you CAN change its properties.
const user = { name: "Vish" };
user.name = "Vishwas"; // ✅ This is allowed!
Verdict: When to use what?
- Always prefer
constby default. - Use
letonly if you need to update the value later (like in loops). - Avoid
varcompletely in modern JavaScript.
Preparing for interviews? Check out React questions in the sidebar.