Topic 19 of 87
Assignment Operators
Overview
Assignment operators are used to assign values to JavaScript variables. The most basic assignment operator is the equal sign (=), which assigns the value on the right to the variable on the left.
However, JavaScript provides compound assignment operators that combine an arithmetic operation with assignment. These are incredibly useful for keeping your code concise and readable, especially when updating state variables or counters.
Syntax
Basic vs Compound Assignment
javascript
let score = 10;
// Basic Assignment
score = score + 5; // score is now 15
// Compound Assignment (Shorthand)
score += 5; // score is now 20
score -= 2; // score is now 18
score *= 2; // score is now 36
score /= 2; // score is now 18Modern Logical Assignments (ES2021)
javascript
let x = 10;
let y = null;
// Logical OR assignment (Assigns right side if left side is falsy)
y ||= 50; // y becomes 50
// Logical Nullish assignment (Assigns right side if left side is null/undefined)
x ??= 100; // x stays 10 (it's not null/undefined)Common Pitfalls
- Confusing the assignment operator (
=) with the equality comparison operators (==or===). Writingif (x = 10)will ALWAYS evaluate to true because it successfully assigns 10 to x, and 10 is a truthy value.
Interview Questions
Q:
What is the logical nullish assignment (??=) operator?
A:
Introduced in ES2021, x ??= y assigns y to x only if x is nullish (null or undefined). It's a great shorthand for setting default values.
Real-World Example
Updating a user's total score in a video game when they collect a coin.
example
javascript
let totalScore = 1250;
const coinValue = 100;
// Update score cleanly
totalScore += coinValue;Check Your Knowledge
Test your understanding of Assignment Operators with these quick questions.