JavaScript ยท Chapter 10 of 55
JavaScript Assignment Operators
Assignment operators store values into variables. The basic `=` assigns, while compound operators like `+=`, `-=`, `*=`, `/=` combine an operation with assignment in one step.
These shorthand operators make code more concise, especially in loops and counters.
Compound assignment
`x += 5` is shorthand for `x = x + 5`. The same pattern applies to `-=`, `*=`, `/=`, `%=` and `**=`.
Logical assignment
Modern JS adds `&&=`, `||=`, and `??=` to conditionally assign values based on truthiness or nullishness.
Example 1 (javascript)
let x = 10;
x += 5;
x *= 2;
console.log(x);Output
30x becomes 15 after +=, then 30 after *=.
Example 2 (javascript)
let name = null;
name ??= "Guest";
console.log(name);Output
Guest??= assigns only when the variable is null or undefined.
Key points
- `+=` combines addition and assignment.
- Compound operators exist for all arithmetic operations.
- `??=` assigns only if the current value is null/undefined.
- Assignment operators improve conciseness and readability.
๐ก Note: Compound assignment reduces repetition and is generally preferred over spelled-out `x = x + 5`.
