Variables: var, let & const
Try code in the playgroundUnderstand the concept
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.
Important ideas
-
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 |
Work through the example
const user = { name: 'Asha' };
user.name = 'Neha'; // Allowed: changes the object.
// user = {}; // Not allowed: reassigns the binding.Can you explain it without the notes?
What is the difference between var, let and const?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
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.
Turn this concept into a clear answer.
- 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?”. Examples are study fragments; framework behavior can depend on your version.