Operators & type coercion
Arithmetic, comparison and logical operators — and how JavaScript converts types behind your back.
Operators are the verbs of a programming language: they add, compare, combine and choose. JavaScript also coerces — automatically converts — values from one type to another when an operator needs it. Knowing the rules saves you from some of the language's most famous bugs.
Arithmetic operators#
% (remainder) is handy for "every Nth item" and even/odd checks: n % 2 === 0 means n is even.
Operator precedence works like maths: ** first, then * / %, then + -. Use parentheses whenever it helps a reader:
Assignment shortcuts#
Increment and decrement
Outside of for loops, i += 1 is often clearer than i++.
Comparison operators#
String comparison uses UTF-16 code units, so it's not a "dictionary" order. For human-friendly sorting use a.localeCompare(b) (covered in Array methods).
Logical operators: &&, ||, !#
Here's the twist: && and || don't return true/false — they return one of their operands, and they short-circuit (stop as soon as the answer is known):
Nullish coalescing ??#
|| treats 0, "" and false as "missing", which is often wrong. ?? only falls back for null or undefined:
You'll also see ||= and &&=, which work the same way with || and &&.
The conditional (ternary) operator#
Type coercion: the rules#
Coercion is JavaScript converting a value's type automatically. The main cases:
+ with a string concatenates
Other maths operators convert to numbers
Explicit conversion is clearer
Rather than relying on coercion, convert on purpose:
Values from HTML inputs are always strings, so input.value + 1 concatenates. Convert first: Number(input.value) + 1.
What == actually does
Loose equality coerces both sides (usually towards numbers) before comparing:
The one common idiom is value == null, which is true for both null and undefined. Even so, many teams prefer value === null || value === undefined or simply value ?? fallback. The safe default: use ===.
Other useful operators#
You'll meet the spread (...), optional chaining (?.) and delete operators in later lessons.
Common mistakes#
input.value + 1giving"41"instead of5— convert strings from forms.count || defaultreplacing a legitimate0— use??.if (x = 5)— a single=assigns (and is truthy!). Use===to compare.- Chaining comparisons like maths:
1 < 5 < 3istrue, because1 < 5→true→1, and1 < 3. Writea < b && b < cinstead.
What's next#
Next you'll master strings — JavaScript's text type — and the template literals that make building text painless.
Check your understanding
Quick quiz
1.What does
"5" + 3evaluate to?2.What does
null ?? "default"return, and what does0 ?? "default"return?3.What is logged by
let i = 5; console.log(i++); console.log(i);?
Finished reading?
Mark this lesson complete to track your progress.