Codectionary / Developer documentation / JavaScript

Assignment Operators

Assignment operators assign values to variables. Beyond the basic = operator, compound assignment operators combine an operation with assignment in one step, like += to add and assign. Logical assignment operators (&&=, ||=, ??=), introduced more recently, combine a logical check with assignment.

Syntax

x = y, x += y, x -= y, x *= y, x /= y, x ??= y

Examples

Compound Arithmetic Assignment

Combining an operation and assignment in one step.

let total = 10;
total += 5;  // total = total + 5 -> 15
total -= 3;  // total = total - 3 -> 12
total *= 2;  // total = total * 2 -> 24
total /= 4;  // total = total / 4 -> 6

Logical Assignment Operators

Assigning a value only under certain conditions.

let config = { theme: null };

// Only assigns if the current value is null/undefined
config.theme ??= "dark";
console.log(config.theme); // "dark"

config.theme ??= "light"; // no-op, theme is already set
console.log(config.theme); // still "dark"

let isActive = true;
isActive &&= false; // only assigns if isActive was truthy
console.log(isActive); // false

Best practices

  • Use ??= specifically for "assign a default if null or undefined", since it will not overwrite legitimate falsy values like 0 or ""
  • Prefer compound operators (+=, -=) over spelling out x = x + y for cleaner, more readable code
  • Reach for &&= and ||= sparingly - they can make control flow less obvious to readers unfamiliar with them
  • Avoid chaining too many assignment operators in a single line, as it hurts readability

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation