Course contentsShow
← JavaScript
Lesson 252 of 2,7237. Arithmetic and OperatorsFree lesson

Common Assignment Patterns and Pitfalls

Learn idiomatic uses of assignment operators and avoid common mistakes like confusing = with ==.

Common Assignment Patterns and Pitfalls

You'll learn: Idiomatic ways to use assignment operators and how to avoid confusing assignment (=) with comparison (==).

The Core Idea

Assignment operators modify variables, but they're also expressions that return values. This makes them powerful but also prone to specific mistakes, especially for beginners who might confuse the single = (assignment) with == (equality comparison).

Common Patterns

Chaining Assignments Since assignment returns the assigned value, you can chain them:

let a, b, c;
a = b = c = 5; // All three get 5

Using Assignment in Conditions (be cautious!)

let value;
if (value = 10) {  // Assigns 10 AND evaluates to 10 (truthy)
  console.log("This runs");
}

The Most Common Pitfall

Confusing = with ==:

let score = 100;

// WRONG - Assignment instead of comparison
if (score = 50) {  // Assigns 50 to score, then checks if 50 is truthy
  console.log("This always runs!"); // score is now 50!
}

// CORRECT - Comparison
if (score === 50) {  // Checks if score equals 50
  console.log("This runs only if score is 50");
}

This mistake silently changes your variable instead of comparing it. Modern editors often warn about this pattern.

Another Pitfall: Accidentally using += when you meant =:

let total = 10;
total += 5; // Adds to existing value (15)
total = 5;  // Replaces with new value (5)

Key Takeaway: Always use = for assignment and ==/=== for comparison. When you see = in a condition, double-check it's intentional, not a typo.