JavaScript Reference ยท Operators
JavaScript assignment operators
Reference for JavaScript assignment operators: =, compound arithmetic forms and the logical assignments ??=, ||= and &&=, with short-circuit behavior.
An assignment operator stores a value in a variable or property. The plain = assigns. Compound forms such as += combine an operation with assignment: x += 5 means x = x + 5, except that x is only evaluated once. The logical forms &&=, ||= and ??= assign only when a condition on the current value holds.
An assignment is itself an expression whose value is the assigned value, which is why a = b = 0 works.
x = value x += value x ??= value
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
x = y x += y x -= y x *= y x /= y x %= y x **= y x <<= y x >>= y x >>>= y x &= y x ^= y x |= y x &&= y x ||= y x ??= y
| Operator | Equivalent to |
|---|---|
x += y (and the other arithmetic and bitwise forms) |
x = x + y |
x &&= y |
x && (x = y) |
x ||= y |
x || (x = y) |
x ??= y |
x ?? (x = y) |
Return value: the value that was assigned (or, for a logical assignment that did not assign, the current value of x).
Exceptions: assigning to a const binding throws a TypeError. In strict mode, assigning to an undeclared variable throws a ReferenceError, and writing to a read-only or frozen property throws a TypeError. The left side must be a variable or property reference; 1 = 2 is a SyntaxError.
Usage notes
- Logical assignments short-circuit. In
x ||= f(), the functionfis not called whenxis already truthy, and no assignment (or setter call) happens. - Pick the right default operator.
||=replaces every falsy value (0,"",false),??=replaces onlynullandundefined. For numbers and strings that can legitimately be empty,??=is usually what you want. +=on strings concatenates, and on mixed types follows the same rules as+.- Chaining (
a = b = c) assigns right to left. Avoid it with declarations:let a = b = 0makesban accidental global in sloppy mode. - Assignments return values, so
if ((m = re.exec(s)))works, but separate statements are easier to read. - Destructuring is also an assignment form: see destructuring assignment.
constobjects can still be changed through their properties; only rebinding the name is blocked.
Browser support
= and the compound arithmetic forms work everywhere. The logical assignment operators &&=, ||= and ??= are newer (ES2021); they work in current browsers, but check a compatibility table if you must support old ones.