Skip to main content

Command Palette

Search for a command to run...

Lesson 17: Mastering JavaScript Comma Operator with challenges!

Published
β€’2 min readβ€’View as Markdown

βœ… 1. What is the comma operator?

  • The comma operator evaluates multiple expressions from left to right, and returns only the result of the last expression.

πŸ” 2. Syntax Example

let a = (1 + 2, 3 + 4);
console.log(a); // 7
  • 1 + 2 is evaluated (value is 3) β€” then discarded.

  • 3 + 4 is evaluated β†’ returned β†’ assigned to a.


πŸ“Œ 3. Important Rule: Low Precedence

The comma operator has very low precedence β€” lower than =.

So this:

let a = 1 + 2, 3 + 4;

is interpreted as:

let a = 3; // from 1 + 2
3 + 4;     // evaluated but ignored

πŸ”’ To use it correctly, wrap in parentheses:

let a = (1 + 2, 3 + 4); // Now a = 7

🎯 4. Real-World Use Case

Used in places where multiple expressions must be evaluated, but only one value is needed.

βœ… Example: Shortening for loop declarations

for (let i = 0, j = 10; i < 10; i++, j--) {
  console.log(i, j);
}
  • Here i++, j-- uses the comma operator to perform two actions during i increment step.

❗ 5. Warning: Don’t Overuse It

Yes, it’s compact and used in frameworks, but:

❌ It reduces readability
βœ” Use only in very controlled, intentional situations (e.g., one-liners, for loops)


🧠 6. Tricky Examples to Watch Out For

πŸ”Έ Example 1:

let x = (console.log("first"), console.log("second"));

Output:

first
second
  • Both console.log() calls run, but x will be undefined (the return value of last console.log()).

πŸ”Έ Example 2:

let result = (5 + 5, 10 * 2, 99);
console.log(result); // 99

All expressions run, only 99 is returned.


πŸ”₯ 7. Interview Trick Questions

❓ What will this print?

let x = 10;
let y = (x += 5, x * 2);
console.log(y); // ?

Answer:

  • x += 5 β†’ 15

  • x * 2 β†’ 30

  • So y = 30


πŸ”§ 8. Debug Tip

If you see expressions separated by commas inside parentheses, you're likely looking at this operator.

Watch out for this in minified code or one-liner functions.


🧩 9. Fun/Obscure Usage

let value = ((alert("Hi"), 42));
console.log(value); // shows alert, then logs 42

Even alert works in comma expressions, but again β€” it's just evaluated, result discarded.


🧠 Memory Mnemonic

"Comma goes left-to-right, but keeps only the last bite."

More from this blog

JS Journey : Concepts & Challenges

57 posts