Docs
README
3.4 Assignment Operators
Table of Contents
- •Introduction
- •Basic Assignment (=)
- •Compound Assignment Operators
- •Arithmetic Assignment
- •Bitwise Assignment
- •Logical Assignment
- •Destructuring Assignment
- •Chained Assignment
- •Common Patterns
- •Best Practices
Introduction
Assignment operators store values in variables. Beyond the basic =, JavaScript provides compound operators that combine assignment with other operations.
Quick Reference
| Operator | Name | Example | Equivalent |
|---|---|---|---|
= | Assignment | x = 5 | - |
+= | Add and assign | x += 5 | x = x + 5 |
-= | Subtract and assign | x -= 5 | x = x - 5 |
*= | Multiply and assign | x *= 5 | x = x * 5 |
/= | Divide and assign | x /= 5 | x = x / 5 |
%= | Modulo and assign | x %= 5 | x = x % 5 |
**= | Exponent and assign | x **= 2 | x = x ** 2 |
&&= | Logical AND assign | x &&= y | x && (x = y) |
||= | Logical OR assign | x ||= y | x || (x = y) |
??= | Nullish assign | x ??= y | x ?? (x = y) |
Basic Assignment (=)
Simple Assignment
// Assign value to variable
let x = 10;
let name = 'John';
let isActive = true;
// Assign expression result
let sum = 5 + 3;
let fullName = firstName + ' ' + lastName;
// Assign function result
let length = str.length;
let parsed = parseInt('42');
Assignment Returns a Value
// Assignment is an expression that returns the assigned value
let a;
let b = (a = 5); // a = 5, b = 5
console.log(a); // 5
console.log(b); // 5
// Can be used in conditions (but usually shouldn't)
let value;
if ((value = getValue())) {
console.log('Got value:', value);
}
Reference vs Value
// Primitives - assigned by value (copy)
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (unchanged)
// Objects - assigned by reference
let obj1 = { x: 10 };
let obj2 = obj1;
obj2.x = 20;
console.log(obj1.x); // 20 (changed!)
Compound Assignment Operators
The Concept
Compound operators combine an operation with assignment:
COMPOUND ASSIGNMENT
x += 5 is equivalent to x = x + 5
┌─────┐ ┌──────────────────┐
│ x │ ← │ x [operator] 5 │
└─────┘ └──────────────────┘
Why Use Them?
// Without compound operators
count = count + 1;
total = total * 2;
name = name + ' Smith';
// With compound operators - cleaner
count += 1;
total *= 2;
name += ' Smith';
Arithmetic Assignment
Addition Assignment (+=)
let count = 10;
count += 5; // 15
count += 3; // 18
// Also works for string concatenation
let message = 'Hello';
message += ' World'; // "Hello World"
Subtraction Assignment (-=)
let balance = 100;
balance -= 25; // 75
balance -= 10; // 65
Multiplication Assignment (*=)
let value = 5;
value *= 3; // 15
value *= 2; // 30
Division Assignment (/=)
let total = 100;
total /= 4; // 25
total /= 5; // 5
Modulo Assignment (%=)
let num = 17;
num %= 5; // 2 (remainder of 17/5)
// Useful for wrapping values
let angle = 450;
angle %= 360; // 90
Exponentiation Assignment (**=)
let base = 2;
base **= 3; // 8 (2^3)
base **= 2; // 64 (8^2)
Bitwise Assignment
Bitwise AND Assignment (&=)
let a = 0b1100; // 12 in binary
a &= 0b1010; // 0b1000 = 8
Bitwise OR Assignment (|=)
let a = 0b1100; // 12 in binary
a |= 0b0011; // 0b1111 = 15
Bitwise XOR Assignment (^=)
let a = 0b1100; // 12
a ^= 0b1010; // 0b0110 = 6
Left Shift Assignment (<<=)
let a = 5; // 0b0101
a <<= 2; // 0b10100 = 20 (5 * 4)
Right Shift Assignment (>>=)
let a = 20; // 0b10100
a >>= 2; // 0b00101 = 5 (20 / 4)
Unsigned Right Shift Assignment (>>>=)
let a = -8;
a >>>= 2; // Large positive number
Logical Assignment
Logical AND Assignment (&&=)
Assigns only if the variable is truthy:
let a = 1;
a &&= 5; // a = 5 (1 is truthy)
let b = 0;
b &&= 5; // b = 0 (0 is falsy, no assignment)
let c = 'hello';
c &&= 'world'; // c = "world"
Logical OR Assignment (||=)
Assigns only if the variable is falsy:
let a = 0;
a ||= 10; // a = 10 (0 is falsy)
let b = 5;
b ||= 10; // b = 5 (5 is truthy, no assignment)
// Great for defaults
let config = {};
config.timeout ||= 3000;
config.retries ||= 3;
Nullish Coalescing Assignment (??=)
Assigns only if the variable is null or undefined:
let a = null;
a ??= 10; // a = 10
let b = 0;
b ??= 10; // b = 0 (0 is not nullish)
let c = '';
c ??= 'default'; // c = "" (empty string is not nullish)
// Perfect for optional values
let settings = { volume: 0 };
settings.volume ??= 50; // stays 0
settings.theme ??= 'dark'; // gets set
Destructuring Assignment
Array Destructuring
// Basic array destructuring
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
// Skip elements
let [first, , third] = [1, 2, 3];
console.log(first, third); // 1 3
// Rest pattern
let [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
// Default values
let [x = 10, y = 20] = [5];
console.log(x, y); // 5 20
// Swap variables
let m = 1,
n = 2;
[m, n] = [n, m];
console.log(m, n); // 2 1
Object Destructuring
// Basic object destructuring
let { name, age } = { name: 'John', age: 30 };
console.log(name, age); // "John" 30
// Rename variables
let { name: userName, age: userAge } = { name: 'John', age: 30 };
console.log(userName, userAge); // "John" 30
// Default values
let { a = 10, b = 20 } = { a: 5 };
console.log(a, b); // 5 20
// Nested destructuring
let {
address: { city },
} = { address: { city: 'NYC' } };
console.log(city); // "NYC"
// Rest pattern
let { id, ...rest } = { id: 1, name: 'John', age: 30 };
console.log(id); // 1
console.log(rest); // { name: "John", age: 30 }
Function Parameter Destructuring
// Array parameter
function sum([a, b, c]) {
return a + b + c;
}
console.log(sum([1, 2, 3])); // 6
// Object parameter with defaults
function createUser({ name = 'Anonymous', age = 0 } = {}) {
return { name, age };
}
console.log(createUser({ name: 'John' })); // { name: "John", age: 0 }
console.log(createUser()); // { name: "Anonymous", age: 0 }
Chained Assignment
Multiple Variables
// Assign same value to multiple variables
let a, b, c;
a = b = c = 10;
console.log(a, b, c); // 10 10 10
// Right-to-left evaluation
let x, y;
x = y = 5 + 3; // y = 8, then x = 8
console.log(x, y); // 8 8
Caution with Objects
// All variables point to SAME object!
let obj1, obj2, obj3;
obj1 = obj2 = obj3 = { value: 10 };
obj1.value = 20;
console.log(obj2.value); // 20 (same object!)
console.log(obj3.value); // 20
// To create separate objects:
obj1 = { value: 10 };
obj2 = { value: 10 };
obj3 = { value: 10 };
Common Patterns
Counter
let count = 0;
function increment() {
count += 1;
return count;
}
console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment()); // 3
Accumulator
let total = 0;
let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
total += num;
}
console.log(total); // 15
String Building
let result = '';
result += 'Hello';
result += ' ';
result += 'World';
console.log(result); // "Hello World"
// Or with template literals
let parts = ['Hello', 'World'];
let message = '';
for (let part of parts) {
message += part + ' ';
}
Toggle
let isEnabled = true;
// Toggle using XOR (for booleans)
// isEnabled ^= true; // Works but not clear
// Clearer way
isEnabled = !isEnabled; // false
isEnabled = !isEnabled; // true
Conditional Default
// Set default only if undefined/null
function configure(options = {}) {
options.timeout ??= 5000;
options.retries ??= 3;
options.debug ??= false;
return options;
}
console.log(configure({ timeout: 1000 }));
// { timeout: 1000, retries: 3, debug: false }
Safe Increment
// Initialize if undefined
let counts = {};
// Unsafe - NaN on first increment
// counts.views++; // NaN
// Safe with ||=
counts.views ||= 0;
counts.views += 1;
// Or with ??=
counts.likes ??= 0;
counts.likes += 1;
// One-liner
counts.shares = (counts.shares ?? 0) + 1;
Best Practices
1. Use Compound Operators for Clarity
// ❌ Verbose
count = count + 1;
total = total * 2;
// ✅ Concise
count += 1;
total *= 2;
// ✅ Even better for increment by 1
count++;
2. Prefer ??= Over ||= for Defaults
// ❌ Might override valid falsy values
config.count ||= 10; // Overrides 0
// ✅ Only overrides null/undefined
config.count ??= 10; // Keeps 0
3. Avoid Assignment in Conditions
// ❌ Confusing - assignment or comparison?
if ((result = calculate())) {
// ...
}
// ✅ Clear separation
result = calculate();
if (result) {
// ...
}
// ✅ If intentional, use parentheses
if ((result = calculate())) {
// ...
}
4. Avoid Chained Assignment for Objects
// ❌ Creates shared reference
let a = (b = c = { x: 1 });
// ✅ Separate objects
let a = { x: 1 };
let b = { x: 1 };
let c = { x: 1 };
5. Use Destructuring for Multiple Values
// ❌ Multiple assignments
let name = user.name;
let age = user.age;
let email = user.email;
// ✅ Destructuring
let { name, age, email } = user;
6. Initialize Before Compound Assignment
// ❌ NaN result
let total;
total += 5; // NaN
// ✅ Initialize first
let total = 0;
total += 5; // 5
Summary
Arithmetic Assignment
| Operator | Example | Equivalent |
|---|---|---|
+= | 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 **= 2 | x = x ** 2 |
Logical Assignment
| Operator | Assigns When | Example |
|---|---|---|
&&= | Left is truthy | x &&= 5 |
||= | Left is falsy | x ||= 5 |
??= | Left is null/undefined | x ??= 5 |
Next Steps
Continue learning operators: