Variables

A named container for storing a value your program can reuse.

What is it?

Programs need to remember things: a username, a score, a price. A variable is a name for a piece of information, so you can reuse it without retyping the value.

In JavaScript, you create a variable with let or const:

  • Use let when the value might change later.
  • Use const when the value should stay the same after it's set.

There's also an older keyword, var. Modern code mostly avoids it, because let and const behave more predictably.

Explain like I'm 10

A variable is like a labeled jar. You write a label on it (the variable name) and put something inside (the value). Later, you just read the label to find what's inside.

Examples

Declaring variables

let score = 0;
score = score + 10; // score is now 10

const username = "amara";
// username = "someone-else"; // ❌ this would cause an error

score can change because it's declared with let. username cannot be reassigned because it's declared with const.

Using a variable to avoid repeating a value

const taxRate = 0.08;

const price1 = 20;
const total1 = price1 + price1 * taxRate;

const price2 = 45;
const total2 = price2 + price2 * taxRate;

taxRate is defined once and used in both calculations. If the rate changes, you update it in one place.

How it works

When JavaScript sees let score = 0, it sets aside a space in memory, labels it "score" and stores 0 there. Whenever your code later uses score, JavaScript looks up that space and uses its current value.

Why does it exist?

Without variables, you'd repeat the same values everywhere, and you couldn't store anything that changes while the program runs, like a running total or the current user's name.

When to use it

Use a variable whenever you need to store a value to use again: a running total, user input, a flag that tracks whether something happened. Use const by default, and switch to let only when the value really needs to change.

When not to use it

A value you use exactly once may be clearer written directly where it's needed. And avoid var in new code: it's never better than let/const in modern JavaScript.

Common mistakes

  • Trying to reassign a const variable — it will throw an error.

  • Using a variable before declaring it.

  • Picking unclear names like x or data1 instead of descriptive ones like cartTotal.

Practice exercises

  1. Easy:

    Declare a const variable called age and log it to the console.

  2. Medium:

    Declare a let variable called count, then write code that increases it by 1 three times.

  3. Hard:

    Write a small script that stores a product's price and quantity in variables and logs the total cost.

Interview questions

What's the difference between `var`, `let`, and `const`?

var is function-scoped (or global) and can be redeclared and reassigned. let is block-scoped and can be reassigned but not redeclared in the same scope. const is block-scoped and can't be reassigned after it's set. They differ in scope and in what reassignment/redeclaration they allow, not in what values they can hold.

Can you declare the same variable name twice in the same scope with `let`?

No. Redeclaring a let (or const) in the same scope throws a SyntaxError ("Identifier has already been declared"). var allows it with no error.

What happens if you try to reassign a `const` variable?

JavaScript throws TypeError: Assignment to constant variable. when the reassignment runs. const locks the binding itself.

What's the difference between declaring a variable and initializing it?

Declaring tells the engine a name exists in a scope (let x). Initializing gives it its first value (x = 5, or both at once: let x = 5). For var and let these can be on separate lines. A var is undefined until then, while a let/const is inaccessible (in the TDZ) until its declaration line runs.

What is variable scope, in plain terms?

Scope is the region of code where a variable name is visible. Code outside it either can't see the variable, or sees a different variable with the same name.

What is function scope, and which keyword creates it?

A function-scoped variable is visible anywhere in the function it was declared in, through any nested blocks (if, for, etc.). var is function-scoped, so a var declared inside an if is visible in the rest of the function.

What is block scope, and which keywords create it?

A block-scoped variable is only visible inside the nearest { } it was declared in: an if block, a for loop body or a standalone { }. let and const are block-scoped.

What is global scope?

The outermost scope, outside any function or block. A variable declared there is visible everywhere in the file. In non-module scripts, a var or implicit global also becomes a property of the global object.

What happens if you try to use a variable that was never declared anywhere?

JavaScript throws ReferenceError: x is not defined when that line runs. There's no fallback, unlike a declared-but-unassigned variable, which is just undefined.

What does a `ReferenceError` actually indicate?

The code used a name that doesn't exist in any visible scope. Either it was never declared, or it's a let/const accessed before its declaration ran (the TDZ case), which throws the same error type.

Are `let` and `const` hoisted the same way `var` is?

Partly. The engine registers the name at the top of the scope, but unlike var it isn't set to undefined. It stays uninitialized in the Temporal Dead Zone until the declaration line runs, so earlier access throws instead of returning undefined.

What is the Temporal Dead Zone (TDZ)?

The stretch between the start of a scope and the line that declares a let/const. The variable exists (it's hoisted) but can't be read or written there; any access throws a ReferenceError.

If `var`, `let`, and `const` are all hoisted, why does only `var` let you access the variable before its declaration line?

A hoisted var is set to undefined right away, so an early read gets undefined. A hoisted let/const only reserves the name and stays uninitialized until its declaration runs, so an early read hits the TDZ and throws.

What's the difference between reassignment and mutation?

Reassignment points the variable at a new value (x = newValue). Mutation changes the contents of the value it already points to (arr.push(1), obj.key = 2). const blocks reassignment but not mutation.

Can you change a property on an object declared with `const`? Can you reassign the variable to a different object?

You can change, add or delete its properties (obj.name = "new"), because that's mutation. You can't do obj = { other: "object" }: that reassigns the binding, which const forbids.

Can you `.push()` to a `const` array? Can you reassign it to a new array?

Yes to pushing (and .pop(), .splice(), index assignment, etc.), which change the array in place. No to reassigning it (arr = [1, 2]). const locks the binding, not the array's contents.

What is variable shadowing?

When an inner-scope variable has the same name as an outer one, the inner one hides (shadows) the outer one inside that scope. The outer variable is unaffected and is visible again once the inner scope ends.

What happens when you declare a `var` inside an `if` block?

It isn't scoped to the block. var is function-scoped, so it's hoisted to the top of the enclosing function (or global scope) and is usable outside and after the if. This often surprises people who expect block scoping.

What is lexical scope?

Scope set by where code is written, not where it's called from. A function can use variables from the scopes it was nested in when defined, wherever it's later called.

What does it mean for scopes to be nested?

An inner scope (a function or block) sits inside an outer one and can read variables from every surrounding scope, out to global. The reverse isn't true: an outer scope can't see an inner scope's variables.

If you declare a variable with `let` inside a function, can code outside that function access it?

No. Outside the function (or block), the variable is out of scope. The only way to reach its value is for the function to return or expose it.

What happens if you assign to a name with no `let`, `const`, or `var` at all, like `total = 5;`?

In non-strict mode, JavaScript silently creates a global variable. No error, but it pollutes the global scope. In strict mode ("use strict", or inside any ES module or class), the same line throws a ReferenceError.

Why is relying on implicit globals (assigning without a declaration keyword) considered risky?

It creates a variable outside any controlled scope, easy to miss when reading the function, and it can silently collide with a same-named variable elsewhere in a large codebase. Strict mode throws a ReferenceError on undeclared assignment to catch exactly these bugs early.

Explain the TDZ in terms of lexical environments.

On entering a scope, the engine creates a lexical environment and registers every let/const name in it, marked uninitialized. Only when execution reaches the declaration does the binding become initialized and get its value. A lookup before that finds an uninitialized binding and throws. That's the TDZ.

Why does JavaScript bother having a TDZ instead of just initializing `let`/`const` to `undefined` like `var`?

It turns reading a variable before its setup line into an immediate error, instead of a silent undefined that causes problems later. It also keeps const consistent: a const that started as undefined and later got its real value would effectively be reassigned, which const doesn't allow.

What's the key hoisting difference between a function declaration and a `let`/`var` declaration?

A function declaration is hoisted with its whole body, so you can call it before the line it's on. A var is hoisted as undefined, and a let/const is hoisted but uninitialized (TDZ). Only the function works early; the others just reserve the name.

Why does using `let` instead of `var` fix the classic loop-and-`setTimeout` bug?

With var, the whole loop shares one binding, so when the callbacks run they all see its final value. With let, each iteration gets a new binding, so each callback closes over its own copy with that iteration's value.

Can two variables with the same name coexist in nested scopes at the same moment?

Yes. Each scope has its own binding, so an inner let x and an outer let x are two separate variables with the same name. The engine looks up a name from the current scope outward and stops at the first match, so the innermost one wins.

Output-prediction: what does `console.log(x); var x = 5;` print, and why not a `ReferenceError`?

It logs undefined. var x is hoisted and set to undefined right away, and the assignment x = 5 hasn't run yet when console.log reads it.

Output-prediction: what does `console.log(y); let y = 5;` do?

It throws ReferenceError: Cannot access 'y' before initialization. y is hoisted but stays in the Temporal Dead Zone until its declaration runs, so reading it earlier throws.

Output-prediction: what does `let count = 1; { let count = 2; console.log(count); } console.log(count);` log?

It logs 2, then 1. The { } block is a new scope where let count = 2 shadows the outer count. After the block, the last console.log sees the untouched outer count, still 1.

Output-prediction: what does `for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }` log?

It logs 3, 3, 3. All three callbacks share the one function-scoped var i, and by the time they run (after the loop ends), i is already 3.

Output-prediction: if you replace `var i` with `let i` in the same loop, `for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }`, what does it log now, and why?

It logs 0, 1, 2. let in a for header creates a new binding per iteration, so each arrow function captures its own i with that iteration's value.

Output-prediction: why does `const point = { x: 1 }; point = { x: 2 };` throw, and what's the exact error?

It throws TypeError: Assignment to constant variable. point = reassigns the binding, which const forbids, even though the new object looks the same. point.x = 2 would work, since it mutates the existing object.

Trap: a teammate declares a loop counter with `const i` in a classic `for` loop and it immediately throws. Why?

for (const i = 0; i < 3; i++) throws a TypeError after the first iteration, when i++ tries to reassign i. const only works as a loop variable in for...of/for...in, where each iteration gets a fresh binding instead of reassigning one.