Variables (var, let, const)
EasyIn plain terms
Variables are like labeled boxes: you put a value in, give it a name, and use that name later to get the value back. In JavaScript, you create variables with let or const.
Use let when the value might change—for example, a counter that goes up, or user input. Use const when the value should stay the same—for example, the value of Pi, or a user object you create once. If you try to reassign a const, you will get an error.
Older code uses var, but it has confusing behavior (function scope, hoisting). Stick with let and const for clearer, safer code.
What you need to know
- •let: block-scoped, reassignable
- •const: block-scoped, not reassignable
- •var: function-scoped (avoid)
Try it yourself
Copy the code below and run it in your browser console or a code editor:
let count = 0; // Can be reassigned
count = count + 1;
const PI = 3.14; // Cannot be reassigned
// PI = 3.14; // Error!
var oldWay = 1; // Avoid - function-scoped, can cause bugsWhy this matters
let vs const vs var is a very common JS interview question. You may be asked about TDZ, hoisting, and block scope—these affect real bugs.
How it connects
Scope (block vs function) ties into closures and execution context. Preferring const supports immutability and avoids accidental reassignment; let is for mutable state. var is legacy and breaks block scope.
Interview focus
Be ready to explain these; they come up often in JS interviews.
- ▸let: block-scoped, reassignable; const: block-scoped, cannot reassign (object content can change).
- ▸var: function-scoped, hoisted; avoid in new code. Explain TDZ for let/const.
- ▸When to use which: default to const; use let when you need to reassign.
Learn more
Dive deeper with these trusted resources: