Explain it simply
Explain it simply
A variable is a name tag attached to a value. Tag the value "Alice" with the name name, and from then on writing name gives you that value back.
JavaScript has three kinds of tag. const is glued in place: it can never move to another value. let can be peeled off and stuck onto a new value. var is the old-style tag that leaks into places you did not expect, so new code no longer uses it.
Problem → Why → Solution
The problem: var silently overwrites an old value
In a long file, total is set to 100 near the top. Two hundred lines later, someone else declares var total again for a different job. JavaScript accepts it without a word, the original total is gone, and the order calculations go wrong without anybody noticing.
var total = 100;
// ... 200 lines later, the same name is reused
var total = 0; // no error: var allows declaring it again
console.log(total); // 0 - the original 100 is silently gone
let price = 100;
let price = 0; // SyntaxError: Identifier 'price' has already been declaredWhy do let and const help?
var lets you declare the same name again in one scope, and it escapes if and for blocks. let and const, added in ES2015, report a repeated declaration as a SyntaxError before any code runs, and they stay inside their block. const adds one more guard: accidentally reassigning a value that was never meant to change throws a TypeError.
Core concept: bindings, scope and reassignment
Declaring a variable creates a binding: a link between a name and a value. let name = "Alice"; creates the binding, and name = "Bob"; moves the tag to a new value, which is called reassignment. A const binding can never move, so it needs its value at declaration time; const x; on its own is a SyntaxError.
With let, declaring and assigning can be separate steps. let message; creates the binding with the value undefined, and you assign it later, which is handy when the value depends on a later decision such as an if/else. One statement can declare several variables, as in let a = 1, b = 2;, but one per line is easier to read and to change in code review.
| Keyword | Can reassign? | Scope |
|---|---|---|
| const | No (TypeError) | Block { } |
| let | Yes | Block { } |
| var | Yes, even redeclare | Whole function |
const protects the binding, not the value. With const cart = ["apple"];, cart.push("banana") adds an item to the same array, which is allowed (this is mutation). cart = [] tries to move the tag to a new array and throws a TypeError. Primitive values such as numbers and strings cannot be changed at all, so a const number really is fixed.
let and const live only inside the { } block that declares them. The name exists from the start of the block, but reading it before the declaration line throws ReferenceError: Cannot access 'x' before initialization; that gap is called the temporal dead zone (TDZ). var is hoisted to the top of its function and starts as undefined, so reading it early quietly gives undefined instead of an error, which hides bugs. The rule: const by default, let when you must reassign, and never var in new code.
Reassignment moves the tag; mutation changes the value
------------------------------------------------------
let name = "Alice" name --> "Alice"
name = "Bob" name --> "Bob" (tag moved: allowed for let)
const cart = ["apple"] cart --> [ "apple" ]
cart.push("banana") cart --> [ "apple", "banana" ] (same array: OK)
cart = [] TypeError: Assignment to constant variable.- Start every variable with const
- Switch to let only if you reassign
- Expect the name to vanish outside { }
- Leave var to old code
const means the tag cannot move; the object or array it points to can still change.
General pattern
const fixedName = initialValue; // must be initialised, never reassigned
let changingName = initialValue; // may be reassigned later
changingName = newValue;
{
const insideOnly = value; // exists only inside this block
}
var legacyName = value; // old style: function-scopedThe shape is always keyword, name, = and a value. What differs is whether the binding can move (let) or not (const), and how far the name is visible (the block, or the whole function for var).
Example: the three keywords in action
Reassigning a const throws a TypeError, which would normally stop the script. Here try/catch catches that error and prints its message so the program keeps going; try/catch gets its own lesson in the Intermediate chapter. Notice also that pushing into a const array works.
let name = "Alice"; // let: this value will change
name = "Bob";
console.log(name);
const birthYear = 2000; // const: never reassigned
try {
birthYear = 2001;
} catch (error) {
console.log(error.name + ": " + error.message);
}
const cart = ["apple"]; // const blocks reassignment, not changes inside
cart.push("banana");
console.log(cart);
var city = "Yangon"; // var: the old, function-scoped way
console.log(city);Code breakdown
- Lines 1-3
name = "Bob";name was declared with let, so it can be moved to the new value "Bob". Reassignment does not repeat let; writing let again would be a SyntaxError.
- Line 7
birthYear = 2001;Trying to move a const binding throws a TypeError at runtime. The catch block prints error.name (TypeError) and error.message.
- Line 13
cart.push("banana");This adds an item to the existing array (mutation) instead of creating a new one, so const allows it. Node.js displays the array as [ 'apple', 'banana' ].
- Line 16
var city = "Yangon";Here var behaves like let, but declared inside a block it would leak out of it, and it allows redeclaration. Know it so you can read older code.
Bob
TypeError: Assignment to constant variable.
[ 'apple', 'banana' ]
YangonSeeing block scope and hoisting
The code below declares one var and one let inside an if block. The var is visible outside the block; the let is not. Reading a var before its declaration gives undefined, while reading a let early throws the TDZ error.
if (true) {
var oldStyle = "visible outside";
let newStyle = "only inside";
}
console.log(oldStyle); // visible outside
console.log(typeof newStyle); // undefined: no such name out here
console.log(early); // undefined: var is hoisted
var early = 1;
try {
console.log(later); // TDZ
let later = 2;
} catch (error) {
console.log(error.message); // Cannot access 'later' before initialization
}Notice that typeof newStyle does not throw: typeof on a name that does not exist at all returns "undefined". The TDZ is different, because there the name already exists but is not ready yet. Older code relied on var's leaky scope, for example reading a loop counter after the loop ended; with let, declare such a value above the loop instead.
In real projects
Where this shows up in real projects
In modern codebases most variables are const: functions, imported modules, data from an API, configuration values. let appears only in the few places where a value really changes, such as a counter, a running total or a value updated in a loop. That makes let a signal to the reader: this value will change later. It also speeds up code review: when a value is const, the reviewer knows it holds the same thing from its declaration to the end of the block and never has to hunt for later assignments.
ESLint's prefer-const rule flags a let that is never reassigned, and its no-var rule bans var completely. Values that are fixed for the whole program, such as API_URL or MAX_UPLOAD_MB, are usually collected at the top of a file as const with UPPER_SNAKE_CASE names.
Common mistakes
Common mistakes
1. Believing const freezes an object
After const user = { name: "Mya" };, user.name = "Hla"; works without any error. If an object must really stay unchanged, use Object.freeze(user), and remember it only freezes the top level.
2. Using a let variable before its declaration
console.log(total); let total = 5; throws ReferenceError: Cannot access 'total' before initialization. With var you would silently get undefined, so this error is actually a favour: move the declaration above the line that uses it.
3. Assigning without any keyword
Writing score = 10; with no declaration silently creates a global variable in non-strict scripts, and throws a ReferenceError in modules and strict mode. Always write const or let where a name is first introduced.
4. Using var for a loop counter
After for (var i = 0; i < 3; i++) finishes, i is still around outside the loop with the value 3. Put setTimeout callbacks inside that loop and they all share the one i, printing 3 3 3. With let i, each iteration gets its own i and they print 0 1 2.
Best practices
Best practices
- Declare each variable in the smallest block that needs it, as close as possible to where it is used.
- Choose names that say what the value means, such as isLoggedIn or cartTotal, and avoid data, temp or x.
- Turn on ESLint's prefer-const and no-var rules in your editor so a tool checks your keyword choices.
Mini challenge
Mini challenge: a game player's state
Keep a game player's state in variables, choosing the right keyword for each one.
- playerName ("Mya") and maxLives (3) never change, so use const
- score (0) and lives (starting at maxLives) will change, so use let
- Declare inventory as an empty const array and add "key" to it
- Add 10 points twice, lose one life, then print two status lines
// TODO: playerName and maxLives - values that never change
// TODO: score and lives - values that will be reassigned
// TODO: inventory - one array whose contents will grow
// TODO: score 10 points twice, lose one life, pick up a "key"
// TODO: print "Mya: 20 points, 2/3 lives" and "Inventory: key"Expected: Two lines are printed: Mya: 20 points, 2/3 lives Inventory: key
Show hint
Reassigning, as in score = score + 10;, needs let, but inventory.push("key") is a mutation and works with const. Show the array as text with inventory.join(", ").
Show solution
const playerName = "Mya";
const maxLives = 3;
let score = 0;
let lives = maxLives;
const inventory = [];
score = score + 10;
score = score + 10;
lives = lives - 1;
inventory.push("key");
console.log(`${playerName}: ${score} points, ${lives}/${maxLives} lives`);
console.log("Inventory: " + inventory.join(", "));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A variable is a binding: a name linked to a value.
- Use const by default, let when you must reassign, and no var in new code.
- const blocks reassignment, but objects and arrays it points to can still change.
- let and const are block-scoped, and reading them before their declaration throws a TDZ ReferenceError.
MDN — JavaScript Guide — MDN Web Docs