JavaScript Assignment
Assignment operators store a value in a variable. Besides the plain =, JavaScript has compound operators that combine a calculation with the assignment, and logical assignment operators that only assign under certain conditions.
Basic and compound assignment
| Operator | Example | Same as |
|---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
**= |
x **= 5 |
x = x ** 5 |
let balance = 100;
balance += 50; // deposit
console.log(balance);
balance -= 30; // withdrawal
console.log(balance);
balance *= 1.1; // 10% interest
console.log(balance);
balance /= 2; // split with a friend
console.log(balance);
balance %= 10;
console.log(balance);150
120
132
66
6
Building strings with +=
+= also appends to strings, which is a simple way to build up text piece by piece:
let receipt = "Items:";
receipt += " coffee";
receipt += ", croissant";
receipt += ", juice";
console.log(receipt);Items: coffee, croissant, juice
Assignment is an expression
An assignment produces the assigned value, so you can chain them. It works, but use it sparingly:
let a, b, c;
a = b = c = 10; // evaluated right to left
console.log(a, b, c);10 10 10
Logical assignment
Three operators (added in ES2021) assign only when a condition about the current value holds:
| Operator | Assigns when the variable is… | Same as |
|---|---|---|
x ||= y |
falsy (0, "", null, undefined, false, NaN) |
x || (x = y) |
x &&= y |
truthy | x && (x = y) |
x ??= y |
null or undefined |
x ?? (x = y) |
They're great for filling in defaults on settings objects:
const settings = { volume: 0, theme: "", user: null };
settings.volume ??= 50; // 0 is a real value, keep it
settings.theme ||= "light"; // "" is falsy, replace it
settings.user ??= "guest";
settings.language ??= "en"; // missing property is undefined
console.log(settings);
let session = "abc123";
session &&= session.toUpperCase(); // only transform if present
console.log(session);{ volume: 0, theme: 'light', user: 'guest', language: 'en' }
ABC123
Destructuring assignment (preview)
You can also assign several variables from an array or object at once. A popular trick is swapping two variables without a temporary one:
let left = "L";
let right = "R";
[left, right] = [right, left];
console.log(left, right);R L
The Destructuring chapter covers this syntax in detail.
Note:
=assigns;===compares. Writingif (x = 5)instead ofif (x === 5)assigns 5 toxand is always true — a classic bug that linters warn about.
Test yourself
After let x = 10; x -= 3; x *= 2;, what is x?
- 14
- 17
- 4
- 13
Given let n = 0; n ??= 5;, what is n?
- 0
- 5
- null
- undefined
Given let s = ""; s ||= "none";, what is s?
- ""
- "none"
- undefined
- false