JavaScript — Assignment
= means "store this"
Assignment puts a value into a variable:
let score = 0; // create + initialize
score = 50; // overwrite
score = score + 10; // read current, add 10, store back
Read it right-to-left: "compute the right side, put the result into the left name."
Compound assignment — update in place
Every math operator has an "apply to self" shortcut:
score += 10 // same as: score = score + 10
score -= 5 // subtract from self
score *= 2 // double it
score /= 3 // halve-ish it
count %= 7 // remainder-into-self
| Statement | Long form |
|---|---|
x += y | x = x + y |
x -= y | x = x - y |
x *= y | x = x * y |
x /= y | x = x / y |
Real-world shape:
cartTotal += item.price; // accumulate purchases
attempts -= 1; // burn a try
progress += 100 / steps; // percent complete
Chained assignment (works, rarely wise)
let a = b = c = 0; // all zero — but b,c become implicit globals in sloppy mode
Modern style declares each separately:
let a = 0;
let b = 0;
The three-stripe confusion
These symbols look related; they're entirely different:
| Symbol | Meaning | Type |
|---|---|---|
= | assign | statement action |
== | loose compare (converts!) | question → boolean |
=== | strict compare | question → boolean |
=> | arrow function | syntax |
if (x = 5) { … } // BUG! assigned 5 (truthy) — always runs!
if (x === 5) { … } // correct comparison
That single-character typo is a classic bug — good editors warn about assignment-in-condition for exactly this reason.
Destructuring — modern unpacking
Assignment can pull apart arrays and objects:
const [first, second] = ["Ada", "Grace"];
console.log(first); // "Ada"
const { name, age } = { name: "Ada", age: 36 };
console.log(name, age); // Ada 36
// swapping without a temp variable:
[a, b] = [b, a];
You'll meet this constantly in modern codebases (and React).
Mini Practice
- Build a counter using only
+=,-=,*=in sequence - Trigger the
if (x = 5)bug on purpose; then fix with=== - Destructure two properties from an object into variables
- Swap two variables via destructuring
- Predict-then-run: does
x += "5"on number 1 give 6 or "15"? Explain why
Next: data types → (already written)
Related Topics
Frequently Asked Questions about Assignment
What is Assignment in JavaScript?
Assignment is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Assignment?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Assignment.
Why is Assignment important in JavaScript?
Assignment is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.