LESSON 03 / 16·2 min readFoundation

Variables: var, let & const

Try code in the playground
01 Understand02 Recall03 Prepare

Understand 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 gives undefined.

  • let: block scope; can be reassigned.

  • const: block scope; cannot be reassigned, but object contents can change.

  • Use const by default when the binding will not change, and let when reassignment is needed.

  • Redeclaring a let or const in the same scope is an error; var allows many redeclarations and can hide mistakes.

Comparison:

Pointvarletconst
Scope inside functionsFunctionBlockBlock
ReassignYesYesNo
Redeclare in the same scopeUsually allowedNoNo
Read before initializationundefinedReferenceErrorReferenceError

Work through the example

JavaScript
const user = { name: 'Asha' };
user.name = 'Neha'; // Allowed: changes the object.
// user = {};      // Not allowed: reassigns the binding.
PAUSE & RECALL

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Always distinguish changing an object's properties from assigning a different object to the variable.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: Hoisting & the temporal dead zone

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.