Assignment operators evaluate the right-hand operand and assign the resulting value to the left-hand variable. ES2021 introduced logical assignment operators (&&=, ||=, ??=) combining logical short-circuiting with assignment.
flowchart TD
Assign["Assignment Operators"] --> Basic["Basic Assignment (=)"]
Assign --> Compound["Compound Arithmetic (+=, -=, *=, /=, %=, **=)"]
Assign --> Logical["Logical Assignment (&&=, ||=, ??=)"]
| Operator | Syntax Equivalent | Short Description |
|---|---|---|
= |
x = y |
Assigns y to x. |
+= |
x = x + y |
Adds y to x and assigns result. |
-= |
x = x - y |
Subtracts y from x and assigns result. |
*= |
x = x * y |
Multiplies x by y and assigns result. |
??= |
x ??= y |
Assigns y to x only if x is nullish (null or undefined). |
| ` | =` | |
&&= |
x &&= y |
Assigns y to x only if x is truthy. |
// Demonstrating compound and logical assignment operators
// 1. Compound Arithmetic Assignment
let score = 100;
score += 50; // 150
score *= 2; // 300
score %= 70; // 20
console.log(`Final Compound Score: ${score}`);
// 2. Logical Nullish Assignment (??=)
let userConfig = {
theme: undefined,
maxConnections: 0 // Valid falsy number
};
// Assign default ONLY if null or undefined
userConfig.theme ??= "dark"; // Assigned "dark" because theme was undefined
userConfig.maxConnections ??= 10; // NOT assigned! 0 is preserved
console.log("Config after ??= :", userConfig);
// 3. Logical OR Assignment (||=)
let userTitle = "";
userTitle ||= "Guest User"; // Assigned "Guest User" because "" is falsy
console.log(`User Title after ||= : "${userTitle}"`);
// 4. Destructuring Assignment
const point = { x: 10, y: 25 };
let posX, posY;
({ x: posX, y: posY } = point);
console.log(`Destructured Positions: X=${posX}, Y=${posY}`);
??= to Preserve Falsy Defaults: Prefer ??= over ||= when configuring optional defaults where 0 or false are valid settings.let/const, wrap the expression in (...) to avoid syntax errors.let a = b = c = 5; implicitly creates global variables b and c in non-strict mode.Given let opts = { timeout: 0 }; opts.timeout ||= 5000; opts.delay ??= 1000;, what are opts.timeout and opts.delay?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.