The basic assignment operator is =. It stores the value on the right in the variable on the left.
let total = 10;
total = total + 5;
console.log(total); // → 15
Updating a variable based on its own value is so common that JavaScript has shortcuts.
| Shortcut | Same as |
|---|---|
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 **= 2 | x = x ** 2 |
let score = 10;
score += 5; // 15
score *= 2; // 30
score -= 8; // 22
console.log(score); // → 22
+= works on strings too, which is handy for building text.
let message = "Hello";
message += ", ";
message += "world";
console.log(message); // → Hello, world
Logical assignment
Modern JavaScript adds three more: ||=, &&= and ??=. They assign only when a condition is met. You will meet them in Logical Assignment and Other Modern Operators.
let name = null;
name ??= "Guest"; // assign only if name is null or undefined
console.log(name); // → Guest
Assignment is an expression
a = b = 5 assigns 5 to both. It works, but code that does too much on one line is harder to read, so use it sparingly.
= is not ==
if (x = 5) assigns 5 to x and is always truthy. You almost certainly meant ===. See Strict vs Loose Equality.