Assignment Returns the Assigned Value
What you'll learn: Assignment expressions don't just store values—they also return the value being assigned, which enables powerful patterns like chained assignments.
The Hidden Return Value
When you write x = 5, you're not just storing 5 in x. The entire expression x = 5 evaluates to 5. This means the assignment itself produces a value you can use immediately.
let result = (x = 10);
console.log(result); // 10
console.log(x); // 10
Both result and x now hold 10 because the assignment x = 10 returned that value.
Chained Assignments
This behavior lets you assign the same value to multiple variables in one line:
let a, b, c;
a = b = c = 7;
console.log(a); // 7
console.log(b); // 7
console.log(c); // 7
JavaScript evaluates right-to-left: c = 7 returns 7, then b = 7 returns 7, then a = 7.
Practical Use Cases
You can assign and immediately use the value:
let count = 0;
let doubled = (count = 5) * 2;
console.log(count); // 5
console.log(doubled); // 10
The assignment count = 5 happens first and returns 5, which then gets multiplied by 2.
Why It Matters
Understanding that assignments return values explains why chained assignments work and prepares you for more advanced patterns where you assign and test values in the same expression.
Key Takeaway: Assignment expressions in JavaScript return the value being assigned, allowing you to chain assignments or use the assigned value immediately in other operations.