JS let vs var
Let’s dive into the fundamental difference between JavaScript’s let and var. Both are used to declare variables in JavaScript, but they have distinct characteristics that impact how your code behaves.
Understanding these differences is crucial for writing clean, maintainable, and error-free JavaScript.
Introduction
In JavaScript, variables are used to store data.
Think of them as labeled containers that hold values.
varis older syntax and generally discouraged in modern JavaScript.letandconstare modern alternatives that provide safer scoping.
var — The Legacy Syntax
The var keyword is function-scoped, meaning it is only accessible within the function where it's declared.
function myFunction() {
var x = 10;
console.log(x); // Output: 10
}
myFunction();
console.log(x); // Error: x is not defined
In this example:
xexists only insidemyFunction- Accessing it outside causes an error
var is NOT block-scoped
if (true) {
var a = 5;
}
console.log(a); // 5
Even though a was declared inside an if block, it's still accessible outside.
let — Modern and Block-Scoped
The let keyword is block-scoped, meaning a variable only exists inside the block {} where it's declared.
function myFunction() {
let y = 20;
console.log(y); // 20
if (true) {
let z = 30;
console.log(z); // 30
}
// console.log(z);
// Error: z is not defined
}
myFunction();
Block Scope Example
if (true) {
let b = 10;
}
console.log(b); // Error: b is not defined
Unlike var, let stays inside its block.
const — Constant Variables
Use const when a variable should not be reassigned.
const is also block-scoped.
function myFunction() {
const message = "Hello, world!";
console.log(message);
// message = "Goodbye";
// Error: Assignment to constant variable
}
myFunction();
Note
With objects/arrays, the reference is constant—but contents can still change.
const user = {
name: "John"
};
user.name = "Mike"; // Allowed
console.log(user.name); // Mike
var vs let
| Feature | var | let |
|---|---|---|
| Scope | Function | Block |
| Redeclare | ✅ Yes | ❌ No |
| Reassign | ✅ Yes | ✅ Yes |
| Hoisted | ✅ Yes | ✅ (Temporal Dead Zone) |
| Modern Usage | ❌ Avoid | ✅ Preferred |
Summary
var→ old syntax, function-scoped, avoid in modern code.let→ block-scoped, use when value changes.const→ block-scoped, use when value shouldn't be reassigned.
Best Practice
const name = "Rahul"; // default choice
let age = 25; // use when value changes
💡 Tip: Prefer const by default, use let only when reassignment is needed, and avoid var.

