← thecodex.expert · The Codex Family of Knowledge
JavaScript Course Lesson 4 of 16
The Codex / JavaScript / Variables — let, const, var

Variables — let, const, var

How to store information in JavaScript — and why const is the right default, let is for things that change, and var is legacy.

What it is, in plain English: A variable is a named container for a value. In modern JavaScript you declare variables with const (when the value won't change) or let (when it will). const is the right default — it makes your code easier to reason about. var is the old way; it has surprising scoping rules and is avoided in new code.
Where this bites you

Writing let again inside a block doesn't update the variable outside it. It creates a brand-new variable with the same name that exists only inside those braces (called shadowing). The outer variable is untouched, and when the block ends the inner one disappears with your result. JavaScript reports no error, because two variables in different scopes are perfectly legal.

const cart = [{ price: 120, member: true }, { price: 80, member: false }];
let discount = 0;

for (const item of cart) {
    if (item.member) {
        let discount = item.price * 0.1;   // meant to update the outer discount
        console.log("member discount:", discount);
    }
}

console.log("total discount:", discount);
// member discount: 12
// total discount: 0

Storing information in variables

Programs need to remember things. A variable is how you give a piece of information a name so you can use it later. Think of it like a labelled box — you put something in, you can take it out or look at it later by using the label.

Declaring a variable

The word "declare" just means "create." You declare a variable using const, let, or var, followed by the name you're giving it.

// const — for values that will NOT change
const greeting = "Hello, world!";
const maxScore = 100;
const pi = 3.14159;

// let — for values that WILL change
let currentScore = 0;
let playerName = "Alice";
let isGameOver = false;

The rule: use const by default

Here's the simple rule: start with const. Switch to let only if you need to reassign.

Why? Because if something can't change, it shouldn't change. const makes that explicit — if you or a colleague accidentally try to reassign it, JavaScript will throw an error immediately, before the bug causes mysterious problems further along.

const userName = "Alice";
userName = "Bob";   // ✗ TypeError: Assignment to constant variable
                    // JavaScript catches this immediately
let score = 0;
score = score + 10;   // ✓ let allows reassignment
score += 5;           // ✓ shorthand: score = score + 5
score++;              // ✓ shorthand: score = score + 1
console.log(score);   // 16

What const actually means — a common misconception

const means the variable binding is constant — you can't point the variable to a different value. But if the value is an object or array, the contents of that object or array can still change:

const person = { name: "Alice", age: 30 };

// ✓ Changing a property is fine — we're not reassigning person itself
person.age = 31;
person.city = "Mumbai";
console.log(person);   // { name: 'Alice', age: 31, city: 'Mumbai' }

// ✗ Reassigning person is not fine
person = { name: "Bob" };   // TypeError: Assignment to constant variable

Think of const as "the label is stuck on this box" — you can change what's inside the box, but you can't point the label at a different box.

Naming variables well

Choose names that describe what the variable holds. This is one of the most important habits in programming.

// ✗ Bad: what does x mean? What is d?
let x = 9.99;
let d = 0.1;
let t = x + (x * d);

// ✓ Good: instantly readable
const itemPrice = 9.99;
const taxRate = 0.1;
const totalPrice = itemPrice + (itemPrice * taxRate);
console.log("Total:", totalPrice);   // Total: 10.989

JavaScript convention: camelCase — first word lowercase, each new word capitalised. firstName, totalScore, isUserLoggedIn. Constants that are genuinely fixed configuration values sometimes use UPPER_SNAKE_CASE: MAX_RETRIES, API_BASE_URL.

What happens if you use a variable before declaring it?

console.log(age);   // ✗ ReferenceError: Cannot access 'age' before initialisation
const age = 25;

With const and let, you get a clear error. Always declare before use. (With var it would print undefined instead of erroring — one of the reasons var is avoided.)

Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.