Skip to content
elephantoo

Operators & type coercion

Lesson 3 of 34 14 min read

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#

JavaScript
console.log(10 + 3);  // 13
console.log(10 - 3);  // 7
console.log(10 * 3);  // 30
console.log(10 / 3);  // 3.3333333333333335
console.log(10 % 3);  // 1   remainder
console.log(2 ** 10); // 1024  exponent
console.log(-7 % 3);  // -1  (the sign follows the left operand)

% (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:

JavaScript
console.log(2 + 3 * 4);   // 14
console.log((2 + 3) * 4); // 20

Assignment shortcuts#

JavaScript
let score = 10;
score += 5;  // score = score + 5  → 15
score -= 3;  // 12
score *= 2;  // 24
score /= 4;  // 6
score **= 2; // 36
score %= 5;  // 1
console.log(score); // 1

Increment and decrement

JavaScript
let i = 5;
console.log(i++); // 5  (returns old value, then adds 1)
console.log(i);   // 6
console.log(++i); // 7  (adds 1, then returns new value)

Outside of for loops, i += 1 is often clearer than i++.

Comparison operators#

JavaScript
console.log(5 > 3);      // true
console.log(5 >= 5);     // true
console.log(5 === 5);    // true
console.log(5 !== "5");  // true
console.log("apple" < "banana"); // true – strings compare character by character
console.log("Zebra" < "apple");  // true – uppercase letters sort before lowercase!

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: &&, ||, !#

JavaScript
const age = 20;
const hasTicket = true;

console.log(age >= 18 && hasTicket); // true – both must be truthy
console.log(age < 13 || hasTicket);  // true – at least one truthy
console.log(!hasTicket);             // false

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):

JavaScript
console.log("Ada" || "Guest");  // "Ada"   – first truthy value
console.log("" || "Guest");     // "Guest"
console.log("Ada" && "Welcome"); // "Welcome" – last value if all truthy
console.log(0 && "Welcome");    // 0      – first falsy value

const user = null;
const name = user && user.name; // no crash: stops at null
console.log(name);              // null

Nullish coalescing ??#

|| treats 0, "" and false as "missing", which is often wrong. ?? only falls back for null or undefined:

JavaScript
const volume = 0;
console.log(volume || 50); // 50 – bug! the user chose 0
console.log(volume ?? 50); // 0  – correct

let theme;
theme ??= "light";         // assign only if null/undefined
console.log(theme);        // "light"

You'll also see ||= and &&=, which work the same way with || and &&.

The conditional (ternary) operator#

JavaScript
const points = 72;
const result = points >= 50 ? "pass" : "fail";
console.log(result); // "pass"

Type coercion: the rules#

Coercion is JavaScript converting a value's type automatically. The main cases:

+ with a string concatenates

JavaScript
console.log("5" + 3);     // "53"
console.log(3 + "5");     // "35"
console.log(1 + 2 + "3"); // "33"  – left to right: 1+2=3, then 3+"3"
console.log("1" + 2 + 3); // "123"

Other maths operators convert to numbers

JavaScript
console.log("5" - 3);    // 2
console.log("5" * "2");  // 10
console.log("abc" * 2);  // NaN
console.log(true + 1);   // 2   (true → 1)
console.log(null + 1);   // 1   (null → 0)
console.log(undefined + 1); // NaN (undefined → NaN)

Explicit conversion is clearer

Rather than relying on coercion, convert on purpose:

JavaScript
const input = "42";
console.log(Number(input) + 8);  // 50
console.log(String(42) + "!");   // "42!"
console.log(Boolean("hello"));   // true
console.log(Boolean(""));        // false
console.log(Number(""));         // 0 – careful: empty string becomes 0
console.log(Number("  12  "));   // 12 – whitespace is trimmed
console.log(parseFloat("3.5kg")); // 3.5

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:

JavaScript
console.log(0 == "0");          // true
console.log(0 == "");           // true
console.log("0" == "");         // false – not transitive!
console.log(false == "0");      // true
console.log(null == undefined); // true
console.log(null == 0);         // false – null only loosely equals undefined

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#

JavaScript
console.log(typeof 42);                   // "number"
console.log([] instanceof Array);         // true
console.log("name" in { name: "Ada" });   // true – does the property exist?
console.log(-"3");                        // -3  (unary minus converts)
console.log(+"3");                        // 3   (unary plus converts)

You'll meet the spread (...), optional chaining (?.) and delete operators in later lessons.

Common mistakes#

  • input.value + 1 giving "41" instead of 5 — convert strings from forms.
  • count || default replacing a legitimate 0 — use ??.
  • if (x = 5) — a single = assigns (and is truthy!). Use === to compare.
  • Chaining comparisons like maths: 1 < 5 < 3 is true, because 1 < 5 → true → 1, and 1 < 3. Write a < b && b < c instead.

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

0/3 answered
  1. 1.What does "5" + 3 evaluate to?

  2. 2.What does null ?? "default" return, and what does 0 ?? "default" return?

  3. 3.What is logged by let i = 5; console.log(i++); console.log(i);?

Finished reading?

Mark this lesson complete to track your progress.