JavaScript Assignment

Assignment operators put values into variables, and the compound forms let you update a variable based on its current value in one concise step.

The basic assignment operator

The equals sign is the assignment operator. It takes the value on its right and stores it in the variable on its left. It is important to remember that a single equals sign never means equality in JavaScript; it always means store this value here. Comparing values for equality uses a different operator entirely, which is a common source of confusion for beginners.

Storing values

<!DOCTYPE html>
<html>
<body>

<h2>Storing values</h2>

<script>
let score = 100;   // store 100 in score
let level = score; // copy the value of score into level

score = 120;       // reassign score to a new value

console.log(score); // 120
console.log(level); // 100 (unaffected by the reassignment)
</script>

</body>
</html>

Compound assignment

Compound assignment operators combine an arithmetic operation with assignment. Instead of writing total = total + 5, you can write total += 5, which reads and updates the variable in a single step. Every arithmetic operator has a matching compound form, and they keep code short and easy to follow, especially inside loops that accumulate a running total.

Compound operators at work

<!DOCTYPE html>
<html>
<body>

<h2>Compound operators at work</h2>

<script>
let total = 10;

total += 5;  // same as total = total + 5  -> 15
total -= 3;  // same as total = total - 3  -> 12
total *= 2;  // same as total = total * 2  -> 24
total /= 4;  // same as total = total / 4  -> 6
total %= 4;  // same as total = total % 4  -> 2

console.log(total); // 2
</script>

</body>
</html>

Logical assignment operators

Modern JavaScript adds logical assignment operators that only assign when a condition about the current value is met. The ||= operator assigns only if the variable is falsy, &&= assigns only if it is truthy, and ??= assigns only if the variable is null or undefined. These are handy for setting default values without overwriting a value the user already provided.

Setting a default the safe way

<!DOCTYPE html>
<html>
<body>

<h2>Setting a default the safe way</h2>

<script>
let settings = { theme: "" };

settings.theme ||= "light"; // empty string is falsy, so assign
settings.color ??= "blue";  // color is undefined, so assign

console.log(settings.theme); // "light"
console.log(settings.color); // "blue"
</script>

</body>
</html>
OperatorExampleSame as
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
**=x **= 2x = x ** 2
||=x ||= 5x = x || 5
&&=x &&= 5x = x && 5
??=x ??= 5x = x ?? 5
Note: Do not confuse = with == or ===. Using a single equals sign inside an if condition assigns a value instead of comparing, which is a subtle bug that can be hard to spot.