Assignment Operators
Assignment stores a value in a variable, and a family of shorthands combine a calculation with the store in one step.
Plus-equals, minus-equals and the rest read and write in one step. Logical assignment operators do the same for defaults. Assignment is an expression, which is why a stray single equals inside an if is such a dangerous typo.
EXERCISE
1The Compound Assignment Shorthands
Reading a variable, changing it and storing it back is so common that each operator has a two-character form.
count = count + 1 works. count += 1 does the same thing and says it once instead of twice.
One for each arithmetic operator:
let n = 10;
n += 5; console.log(n); // 15 same as n = n + 5
n -= 3; console.log(n); // 12
n *= 2; console.log(n); // 24
n /= 4; console.log(n); // 6
n %= 4; console.log(n); // 2
n **= 3; console.log(n); // 8
It works on strings too, which is genuinely useful:
let message = "Hello";
message += ", world";
message += "!";
console.log(message); // Hello, world!
// Building up text in a loop:
let list = "";
for (const item of ["a", "b", "c"]) {
list += item + " ";
}
console.log(list); // "a b c "
Why it is more than a typing saving:
// With a long name, the repetition is a real place for a bug:
basket.items[selectedIndex].quantity =
basket.items[selectedIndex].quantity + 1;
// The shorthand names it once, so it cannot disagree with itself:
basket.items[selectedIndex].quantity += 1;
Pro Tip: The value of
+=is that the thing being changed appears once. When the left side is a long path into a nested object, writing it twice is an invitation to update one copy and not the other, and that bug reads as correct at a glance. Say it once.
EXERCISE
2Logical Assignment, for Defaults in One Line
Three newer operators apply a value only when the existing one fails a test, which makes setting defaults very short.
These combine a logical operator with an assignment, and each one only writes when it needs to.
Fill in a missing value:
const config = { retries: 0 };
config.timeout ??= 3000; // timeout is undefined, so set it
config.retries ??= 5; // retries is 0, which is NOT nullish, so leave it
console.log(config); // { retries: 0, timeout: 3000 }
The falsy version, with the usual zero problem:
const settings = { volume: 0 };
settings.volume ||= 50; // 0 is falsy, so it gets overwritten
console.log(settings.volume); // 50 <- probably not what you wanted
// Which is exactly why ??= usually deserves the job instead.
And the one that only overwrites an existing value:
const user = { name: "Ada", nickname: "" };
user.name &&= user.name.trim(); // name is truthy, so trim it
user.nickname &&= user.nickname.trim(); // "" is falsy, left alone
console.log(user); // { name: 'Ada', nickname: '' }
Written out longhand, so the shape is clear:
// a ??= b is if (a === null || a === undefined) a = b;
// a ||= b is if (!a) a = b;
// a &&= b is if (a) a = b;
Pro Tip:
??=is the one you will reach for most, because filling in options that were not supplied is an everyday job and it is the only one of the three that treats0,""andfalseas real values. Learn that one properly and let the other two be things you recognise when reading someone else's code.
EXERCISE
3Assignment Is an Expression, and Why That Bites
An assignment produces a value as well as storing one, which is the reason a single missing equals sign can break a condition silently.
x = 5 does two things: it stores 5 in x, and the whole thing evaluates to 5.
Proof that it produces a value:
let x;
console.log(x = 5); // 5 the assignment itself evaluated to 5
// Which is why chaining works:
let a, b, c;
a = b = c = 0;
console.log(a, b, c); // 0 0 0
// c = 0 evaluates to 0, then b = 0, then a = 0.
And why this typo is so dangerous:
const status = "pending";
// Intended: compare
if (status === "active") {
console.log("Active");
}
// Nothing prints. Correct.
let state = "pending";
// Typo: one equals instead of three
if (state = "active") {
console.log("Active"); // THIS RUNS
}
console.log(state); // "active" <- and the variable was changed
// The if got the string "active", which is truthy.
// No error. The condition is always true and the data is corrupted.
How the language protects you, a little:
const role = "guest";
// if (role = "admin") { }
// TypeError: Assignment to constant variable.
// Another reason to default to const: a typo that would be
// silent on a let becomes an immediate, obvious error.
This is a concrete, everyday argument for two habits you have already been given. Use const unless you need let, so that an accidental assignment throws instead of quietly succeeding. And read every condition twice for the number of equals signs, because this particular bug produces no error message at all.
