Assignment Operators

Assign and update values with =, += and friends.

Syntaxx += value;

The = operator assigns a value to a variable. Shorthand operators combine an operation with assignment.

OperatorSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5

Example

Try it yourself
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.

Example · js
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.

Example · js
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.

Example · js
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

  • Be the first to comment on this lesson.