Assignment Operators
Assign and update values with =, += and friends.
Syntax
x += value;The = operator assigns a value to a variable. Shorthand operators combine an operation with assignment.
| Operator | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
Example
Loading editor…
Press Run to execute the code.
When to use it
- Accumulate a running total in a variable as a user adds items to a shopping cart.
- Append new messages to a string log variable using the += operator.
- Decrement a stock count with -= each time an order is placed.
More examples
Basic and compound assignment
Demonstrates +=, -=, and *= compound assignment operators updating a running total.
let total = 100;
total += 25; // 125
total -= 10; // 115
total *= 1.1; // 126.5
console.log(total);String append with +=
Uses += to progressively build up a log string by appending new events.
let log = "Session started. ";
log += "User logged in. ";
log += "Item added to cart.";
console.log(log);Logical assignment operators
Uses ??= and ||= logical assignment operators to set default values on an object.
let config = {};
config.timeout ??= 3000; // assign only if null or undefined
config.retries ||= 3; // assign if falsy
console.log(config); // { timeout: 3000, retries: 3 }
Discussion