Chapters

FundamentalsChapter 13 of 21

Assignment

Storing values, and the shorthand forms worth knowing.

Plain assignment

= stores the value on the right in the name on the left. It is not a comparison, which is why comparison needs three characters.

JavaScript

JavaScript

let total = 10;
total = total + 5;

console.log(total);

Output

15

Compound forms

Every arithmetic operator has a shorthand that reads the variable, applies the operation and stores the result.

JavaScript

JavaScript

let n = 10;

n += 5;
n -= 3;
n *= 2;
n /= 4;
n %= 4;

console.log(n);

Output

2
ShorthandSame as
n += 5n = n + 5
n -= 5n = n - 5
n *= 5n = n * 5
n /= 5n = n / 5
n **= 2n = n ** 2

Strings too

+= works on strings, which is how text gets built up a piece at a time.

JavaScript

JavaScript

let message = 'Hello';

message += ', ';
message += 'world';

console.log(message);

Output

Hello, world

Logical assignment

Three newer forms assign only under a condition. They are worth knowing because they replace a very common three-line pattern.

JavaScript

JavaScript

let name = '';
name ||= 'Anonymous';

let count = 0;
count ??= 10;

let flag = true;
flag &&= 'replaced';

console.log(name, count, flag);

Output

Anonymous 0 replaced

||= assigns when the current value is falsy. ??= assigns only when it is null or undefined, which is why count stayed 0 and name did not stay empty. &&= assigns only when the current value is truthy.

Gotcha

Reach for ??= rather than ||= when zero or an empty string are legitimate values. Defaults applied with || silently overwrite both.

Assignment is an expression

An assignment produces the assigned value, which is why chains work. It is also why a mistyped = inside an if is valid code rather than an error.

JavaScript

JavaScript

let a;
let b;

a = b = 5;

console.log(a, b);

Output

5 5

Test yourself

2 questions

What is the difference between ||= and ??=

Show the answer

||= assigns on any falsy value, ??= only on null or undefined Which matters whenever 0 or an empty string is a real value you meant to keep.

Why is if (x = 5) valid JavaScript?

Show the answer

Assignment is an expression, so it produces a value the if can test It assigns 5, which is truthy, so the branch always runs. Linters flag it for exactly this reason.

Next chapter

Comparison

Testing values against each other, and the traps in ordering them.