What is the difference between var, let and const?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Variables: var, let & const
Definition:
var, let and const declare variables, but they have different scope and initialization rules. let and const are block-scoped, making it easier to keep a variable inside the code that needs it. const prevents reassignment of the binding; it does not make an object immutable.
Key points:
-
var: function scope; reading before its declaration givesundefined. -
let: block scope; can be reassigned. -
const: block scope; cannot be reassigned, but object contents can change. -
Use
constby default when the binding will not change, andletwhen reassignment is needed. -
Redeclaring a
letorconstin the same scope is an error;varallows many redeclarations and can hide mistakes.
Comparison:
| Point | var | let | const |
|---|---|---|---|
| Scope inside functions | Function | Block | Block |
| Reassign | Yes | Yes | No |
| Redeclare in the same scope | Usually allowed | No | No |
| Read before initialization | undefined | ReferenceError | ReferenceError |
Example:
const user = { name: 'Asha' };
user.name = 'Neha'; // Allowed: changes the object.
// user = {}; // Not allowed: reassigns the binding.Interview point:
- Always distinguish changing an object's properties from assigning a different object to the variable.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What is the difference between var, let and const?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.