JavaScript assignment operators store values in variables and update existing bindings concisely. Beyond the basic = operator, JavaScript includes math shortcuts like += and modern ES2021 logical assignment operators like ??=.
| Operator | Equivalent To | Common Use Case |
|---|---|---|
x += y |
x = x + y |
Add to totals or build strings |
x -= y |
x = x - y |
Subtract stock or scores |
x *= y |
x = x * y |
Apply multipliers |
x ??= y |
x ?? (x = y) |
Set default only if null or undefined |
| `x | = y` | |
x &&= y |
x && (x = y) |
Update value only if currently truthy |
Logical assignment operators short-circuit, meaning they only assign when needed. This avoids overwriting valid 0 or false settings and skips unnecessary property writes.
const config = { retries: 0, label: "" };
// ??= keeps 0 because 0 is neither null nor undefined
config.retries ??= 3;
config.timeoutMs ??= 2500;
// ||= replaces empty string "" because "" is falsy
config.label ||= "Default Service";
let score = 50;
score += 15; // 65
console.log({ config, score });
Although let a = b = 5; works in loose mode, it secretly turns b into an accidental global variable if b was not declared earlier. Declare each variable on its own line with let or const instead.
Compound assignment also works with strings (+=), remainders (%=), and exponentiation (**=). Keep each update focused on one clear variable so debugging stays simple.
= with === inside if: Writing if (isReady = true) assigns true instead of checking it, so the branch always runs.+= on uninitialized numbers: Starting with let sum; and running sum += 5 yields NaN because undefined + 5 is NaN. Always initialize numbers to 0.||= for numeric options: Writing options.limit ||= 10 overwrites 0 with 10; use ??= instead.??= do differently from ||=???= assigns the right-hand value only when the left side is null or undefined. ||= assigns whenever the left side is any falsy value, including 0, false, or "".
+= with const variables?No, += reassigns the variable binding, so using += on a const variable throws a TypeError. Use let for variables that accumulate values.
&&= skip calling the right-hand side if the left side is falsy?Yes, x &&= compute() short-circuits and never calls compute() when x is falsy.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.