TExcelTAD
Home › JavaScript › JS Assignment

JavaScript Assignment

Assignment operators store a value in a variable. Besides the plain =, JavaScript has compound operators that combine a calculation with the assignment, and logical assignment operators that only assign under certain conditions.

Basic and compound assignment

Operator Example Same as
= x = 5 x = 5
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
**= x **= 5 x = x ** 5
js · try it yourself
let balance = 100;
balance += 50;    // deposit
console.log(balance);
balance -= 30;    // withdrawal
console.log(balance);
balance *= 1.1;   // 10% interest
console.log(balance);
balance /= 2;     // split with a friend
console.log(balance);
balance %= 10;
console.log(balance);
150
120
132
66
6

Building strings with +=

+= also appends to strings, which is a simple way to build up text piece by piece:

js · try it yourself
let receipt = "Items:";
receipt += " coffee";
receipt += ", croissant";
receipt += ", juice";
console.log(receipt);
Items: coffee, croissant, juice

Assignment is an expression

An assignment produces the assigned value, so you can chain them. It works, but use it sparingly:

js · try it yourself
let a, b, c;
a = b = c = 10;   // evaluated right to left
console.log(a, b, c);
10 10 10

Logical assignment

Three operators (added in ES2021) assign only when a condition about the current value holds:

Operator Assigns when the variable is… Same as
x ||= y falsy (0, "", null, undefined, false, NaN) x || (x = y)
x &&= y truthy x && (x = y)
x ??= y null or undefined x ?? (x = y)

They're great for filling in defaults on settings objects:

js · try it yourself
const settings = { volume: 0, theme: "", user: null };

settings.volume ??= 50;   // 0 is a real value, keep it
settings.theme ||= "light"; // "" is falsy, replace it
settings.user ??= "guest";
settings.language ??= "en"; // missing property is undefined

console.log(settings);

let session = "abc123";
session &&= session.toUpperCase();  // only transform if present
console.log(session);
{ volume: 0, theme: 'light', user: 'guest', language: 'en' }
ABC123

Destructuring assignment (preview)

You can also assign several variables from an array or object at once. A popular trick is swapping two variables without a temporary one:

js · try it yourself
let left = "L";
let right = "R";
[left, right] = [right, left];
console.log(left, right);
R L

The Destructuring chapter covers this syntax in detail.

Note: = assigns; === compares. Writing if (x = 5) instead of if (x === 5) assigns 5 to x and is always true — a classic bug that linters warn about.

Test yourself

After let x = 10; x -= 3; x *= 2;, what is x?

  1. 14
  2. 17
  3. 4
  4. 13

Given let n = 0; n ??= 5;, what is n?

  1. 0
  2. 5
  3. null
  4. undefined

Given let s = ""; s ||= "none";, what is s?

  1. ""
  2. "none"
  3. undefined
  4. false