References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Assignment = operator

Operator JavaScript All modern browsers Updated
Quick answer

The assignment operator = stores a value in a variable: let x = 5. It's a single equals sign — not to be confused with == or ===, which compare. Compound forms like += and *= combine an operation with assignment.

Overview

= assigns: it puts the value on the right into the variable on the left. let count = 0, name = "Ada". It's the most basic operator there is, and the most common beginner trap is mixing it up with comparison. One equals sign assigns; two or three compare. if (x = 5) assigns 5 to x (and is always truthy) — a bug — while if (x === 5) checks whether x equals 5, which is almost always what you meant.

There's a family of compound assignment operators that do an operation and assign in one step: +=, -=, *=, /=, %=, **=, and the logical ones &&=, ||=, ??=. So x += 5 is x = x + 5, and the handy x ??= 10 assigns 10 only if x is null or undefined.

Assignment is itself an expression that returns the assigned value, which enables (rarely needed) chaining like a = b = 0. More usefully, the left side can be a destructuring pattern — const { name } = user or [a, b] = [b, a] — to assign several variables at once. And remember const bindings can't be reassigned, so = on a const after declaration throws.

Syntax

x = value          // assign
x += 5             // compound: x = x + 5
x ??= 10           // assign only if x is null/undefined
a = b = 0          // chained (both become 0)
const { name } = user  // destructuring assignment

// don't confuse with comparison:
if (x === 5) { ... }   // compare (not x = 5)

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  let total = 0;
  total += 10;
  total *= 3;

  let name;
  name ??= 'Guest'; // assigns because name is undefined

  document.getElementById('out').textContent =
    'total: ' + total + '\n' +
    'name:  ' + name; // total: 30 / name: Guest
</script>

Best practices

  • Use = to assign and === to compare — a classic bug is writing = in an if.
  • Use compound operators (+=, *=, ??=) to combine an operation with assignment.
  • Use destructuring assignment to set multiple variables from an object or array.
  • Remember const can't be reassigned — = on it after declaration throws.

Frequently asked questions

What is the difference between =, == and ===?
= assigns a value; == compares with type coercion; === compares without coercion. Use = to assign and === to compare.
What does += mean?
It's compound assignment: x += 5 is shorthand for x = x + 5. The same pattern works for -=, *=, /= and others.
What does ??= do?
It assigns only if the variable is null or undefined: x ??= 10 sets x to 10 only when it's nullish.
Why is if (x = 5) always true?
Because = assigns 5 to x and the expression evaluates to 5 (truthy). You almost certainly meant x === 5.