← Fundamentals
Guided lesson 5 questions · 6 languages

Assignment and reassignment

What a new assignment changes, what it leaves alone, and how to swap two values without losing one.

Assigning to a variable first computes the value on the right, using the values variables hold at that moment. Then the variable on the left holds the result. No other variable changes.

Before you begin

Why this matters

Most mistakes with assignment come from losing track of which value a variable holds at a given line. Once you read every assignment as “compute the right side now, then replace”, you can predict the result of a sequence of updates and spot the line that loses a value.

What this helps you reason about

  • Predict what a variable holds after several assignments, including x = x + 1 and x += 1.
  • Keep a running total in a loop.
  • Swap two variables without losing one of the values.

A let variable can be given a new value as often as you like. This lesson follows what each new assignment changes, what it leaves alone, and the order in which it reads and writes.

Already know this? The short version
  • An assignment computes the right side with the current values, then the variable holds the result. The old value itself is not changed, and no other variable changes. Only let variables can be assigned again.
  • A value computed from other variables does not follow their later changes. Assigning an object copies a reference, so both names reach one object.
  • x += y means x = x + y, and x++ adds 1; an accumulator starts before the loop and is updated with += inside it.
  • a = b; b = a loses a value. Swap with a temporary variable or [a, b] = [b, a]; a, b = b, a is a compile error in TypeScript.

Go to the final check· Go to the practice tickets

Words in this lesson (6)
variable
A name that holds a value. let and const declare variables; a let variable can be given a new value later, and a const variable cannot.
assignment
Code such as marks = 9 that gives a variable a new value. The right side is computed first, with the values variables hold at that moment; then the variable on the left holds the result.
reference
A value that leads to an object. A variable whose value is an object holds a reference, not a copy of the object, so copying the variable gives a second way to reach the same object.
compound assignment
An operator such as += that updates a variable from its own value: marks += 3 means marks = marks + 3.
accumulator
A variable that collects a result step by step, such as a running total that a loop adds each item to.
destructuring assignment
An assignment such as [a, b] = [b, a], with names in brackets on the left. The right side is computed first; then its elements are assigned to the names, in order.

Examples are focused snippets; imports, enclosing functions, or classes may be omitted. C examples use C11; Haskell examples use Haskell 2010. Expand the notes for language-specific depth.

01 / Assign

What does an assignment do?

An assignment gives a variable a new value. marks = marks + 3 works in two steps. First the right side is computed, with the value marks holds now: 6 + 3 is 9. Then marks holds 9.

The old value is not changed. The number 6 is still 6; marks simply refers to 9 now. Only let variables can be assigned again; assigning to a const is a compile error.

Because the right side is always computed first, the order of assignments matters. Each line reads the values that the lines above it left behind.

main.ts
let marks = 6;
marks = marks + 3; // reads 6, then marks is 9
marks = marks * 2; // reads 9, then marks is 18
console.log(marks); // 18

Follow one variable through three assignments. The boxes are a picture of the values, not memory addresses.

A conceptual model, not a physical memory layout or live code execution.

1 / 3

Give marks its first value

marks
6

marks holds 6.

An assignment computes the right side first, then gives the variable the result.

Experiment

Follow one variable through three assignments

Each assignment first computes the right side with the value marks holds at that moment, then stores the result in marks. marks + 3 reads 6 and gives 9; marks * 2 reads 9 and gives 18. The order of the lines decides which value each line reads.

Why it matters To predict a variable, follow its assignments in order and use the value it holds just before each one.

Predict what marks holds after each line. Then swap the two lines that assign to marks, so the doubling comes first, and predict the printed number again.

let marks = 6;
marks = marks + 3;
marks = marks * 2;
console.log(marks);
What to look for

The panel shows the values from before the highlighted line runs. At the stop on line 2, marks shows 6; on line 3 it shows 9; on line 4 it shows 18, and the run prints 18. The stepper stops on the last line twice; that is normal for this debugger. After the edit, marks shows 6, then 12, then 15, and the run prints 15.

Expected output

18

02 / Copies

Does a variable follow the values it came from?

A variable holds a value, not the calculation that produced it. total = homework + test adds the two numbers when that line runs. Changing test later does not change total.

As Variables showed, assigning one variable to another copies the value at that moment, and the two are not linked afterwards. An assignment to one variable never changes another.

For an object or an array, the value that is copied is a reference: a value that leads to the object. Both names then reach the same object. A later lesson, Copying, identity, and aliasing, follows that case.

main.ts
let homework = 8;
let test = 15;
let total = homework + test; // 23
test = 20;
console.log(total); // still 23

A variable holds the value computed when its line ran, not a formula.

Coming from Spreadsheet formulas: A cell such as =A1+B1 updates when A1 changes. A variable does not: it holds the number that was computed when its line ran.

03 / +=

What do += and similar operators do?

Updating a variable from its own value is so common that it has a short form. marks += 3 means marks = marks + 3. -=, *=, and /= work the same way. marks++ adds 1, and marks-- subtracts 1.

A variable that collects a result step by step is called an accumulator. A running total is the usual example. It gets its starting value, 0, before the loop. Inside the loop, += adds each item to the total.

The loop below runs its block once for each element of tests. for (const mark of tests) means: in each round, mark holds the next element.

main.ts
const tests = [7, 9, 6];
let total = 0;
for (const mark of tests) {
  total += mark;
}
console.log(total); // 22

x += y reads x, adds y, and stores the result in x.

Coming from Python: Python has no ++; marks++ in TypeScript is marks += 1.

Precisely: x++ as a value

x++ and ++x both add 1 to x. Used inside a larger expression they differ: x++ gives the old value, and ++x the new one. So with count holding 3, next = count++ sets next to 3 and count to 4. Keep ++ on a line of its own and the difference never matters.

Experiment

Add each mark to a running total

total += mark reads total, adds mark, and stores the sum back in total. total gets its 0 once, before the loop, so each round adds to what the rounds before it left there.

Why it matters A running total needs both parts: a starting value before the loop, and an update that reads the old total.

Predict total after each round of the loop. Then change total += mark to total = mark and predict the printed number again.

const tests = [7, 9, 6];
let total = 0;
for (const mark of tests) {
  total += mark;
}
console.log(total);
What to look for

Step through the loop and watch total. The stepper stops on the for line before each round and on total += mark inside it, where mark shows 7, then 9, then 6, and total shows 0, then 7, then 16. At the console.log line, total shows 22, and the run prints 22. After the edit, total shows 0, 7, and 9 at the stops inside the loop and ends at 6, and the run prints 6: each round replaces the total with that round’s mark.

Expected output

22

04 / Swap

How do you swap two values?

Swapping two variables means each one ends up with the other’s value. The obvious two lines do not do that. roomA = roomB stores 30 over the 12, so roomB = roomA then copies 30 back. The value 12 is lost.

One fix keeps the old value first, in a temporary variable: an extra variable that holds a value for a short time. The other fix is a destructuring assignment. [roomA, roomB] = [roomB, roomA] first builds the array [30, 12] from the current values, then assigns its elements to roomA and roomB, in order.

The same rule applies whenever two updates depend on each other. If one running total must be computed from another one’s old value, update it first, or keep the old value in a temporary variable.

main.ts
let roomA = 12;
let roomB = 30;
const oldA = roomA; // keep 12
roomA = roomB;
roomB = oldA;
// or, in one line:
[roomA, roomB] = [roomB, roomA];

Read every value you still need before you overwrite it.

Coming from Python: a, b = b, a does not swap in TypeScript. The compiler rejects it: Left side of comma operator is unused and has no side effects. Write [a, b] = [b, a].

Precisely: the semicolon before [

A line that starts with [ can join the line before it when that line has no semicolon. A line let b = a with no semicolon, followed by a line [a, b] = [b, a], is read as one expression, let b = a[a, b] = [b, a]. End the previous line with a semicolon, as this lesson does everywhere.

Experiment

Swap two rooms and watch one number disappear

The first assignment stores 30 over the 12. When the second assignment reads the first room, it gets 30, so it copies 30 back. Nothing still holds 12. [roomB, roomA] on the right builds an array from the current values, [30, 12], before anything is assigned. Then the two elements are assigned to roomA and roomB in order.

Why it matters To swap, read both values before you assign either one: destructuring does that in one line.

Predict both printed numbers. Then replace the two assignment lines with one line, [roomA, roomB] = [roomB, roomA];, and predict again.

let roomA = 12;
let roomB = 30;
roomA = roomB;
roomB = roomA;
console.log(roomA, roomB);
What to look for

At the stop on line 3, roomA shows 12 and roomB 30. The debugger did not stop on line 4 in this run. The line still ran, as the output shows. At the next stop, on the console.log line, both show 30, and the run prints 30 30. After the edit, the stop on console.log shows roomA 30 and roomB 12, and the run prints 30 12.

Expected output

30 30

05 / Try it

Can you explain a fresh example?

Follow both variables line by line, and write down what each one holds after every line.

main.ts
let first = 2;
let second = 5;
first = first + second;
second = first - second;
first = first - second;
console.log(first, second);

What is printed?

Reveal the reasoning

5 2. After the first assignment, first holds 7. The second reads that 7 and stores 7 - 5 = 2 in second. The third reads 7 and 2 and stores 5 in first. Each line used the values from just before it, so the two numbers end up swapped without a temporary variable.

Practice tickets

  1. ASSIGN-101 · Reversed room bookings show one class hour twice → Free
  2. ASSIGN-102 · Every predicted grade 3 is as large as the group of new pupils → Sign in · Pro
  3. ASSIGN-103 · The best week of class points is never more than one day’s points → Sign in · Pro

Keep exploring

Mutability and constants →

Primary references