Follow AiTechWorlds on LinkedIn for professional AI content!Follow Now →
14 minLesson 4 of 35
JavaScript Fundamentals

Operators & Comparisons

Operators & Comparisons

JavaScript has a reputation for quirky operator behavior — and that reputation is earned. This lesson covers every operator type and explains the type coercion rules that trip up developers daily.

Arithmetic Operators

// Standard arithmetic
console.log(10 + 3);   // 13
console.log(10 - 3);   // 7
console.log(10 * 3);   // 30
console.log(10 / 3);   // 3.3333...
console.log(10 % 3);   // 1  (remainder)
console.log(10 ** 3);  // 1000 (exponentiation)

// Increment and decrement
let a = 5;
console.log(a++);  // 5  (post-increment: returns THEN increments)
console.log(a);    // 6
console.log(++a);  // 7  (pre-increment: increments THEN returns)
console.log(a--);  // 7  (post-decrement)
console.log(a);    // 6

String Operators

// + with strings = concatenation
"Hello" + " " + "World"  // "Hello World"

// + with mixed types = type coercion to string
"5" + 3     // "53"  (3 becomes string)
3 + "5"     // "35"
3 + 4 + "5" // "75"  (left-to-right: 3+4=7, then "7"+"5"="75")
"5" + 3 + 4 // "534" (left-to-right: "5"+3="53", "53"+4="534")

// Other arithmetic operators convert strings to numbers
"10" - 5    // 5
"10" * 2    // 20
"10" / 2    // 5
"10" % 3    // 1

Comparison Operators

This is where JavaScript gets notorious. There are two equality operators:

// == (loose equality) — converts types before comparing
0 == false    // true  (false converts to 0)
1 == true     // true  (true converts to 1)
"" == false   // true  (both become 0)
null == undefined  // true (special case)
"5" == 5      // true  (string converts to number)

// === (strict equality) — NO type conversion
0 === false   // false (different types)
"5" === 5     // false (different types)
null === undefined  // false
5 === 5       // true
"hello" === "hello" // true

Rule: Always use === and !== unless you have a specific reason to use loose equality.

// Relational operators
5 > 3     // true
5 >= 5    // true
3 < 5     // true
3 <= 2    // false

// String comparison uses lexicographic (dictionary) order
"apple" < "banana"  // true
"b" > "a"           // true
"B" < "a"           // true (uppercase letters have lower code points)

// Comparing different types produces confusing results
null > 0    // false
null == 0   // false (special case)
null >= 0   // true  (!!!!)  — don't rely on null comparisons

Logical Operators

// && (AND) — returns first falsy value, or last value
true && true    // true
true && false   // false
"hello" && 42   // 42    (both truthy, returns last)
false && "oops" // false (short-circuits at false)
null && "oops"  // null  (null is falsy, returns it)

// || (OR) — returns first truthy value, or last value
false || "default"  // "default"
null || undefined   // undefined (both falsy, returns last)
"first" || "second" // "first"   (first is truthy, short-circuits)
0 || ""  || "last"  // "last"    (0 and "" are falsy)

// Common pattern: default values
const name = userInput || "Anonymous";
const config = userConfig || defaultConfig;

// ! (NOT) — converts to boolean and flips it
!true     // false
!false    // true
!0        // true  (0 is falsy)
!""       // true  ("" is falsy)
!"hello"  // false (non-empty string is truthy)

// !! (double NOT) — convert any value to boolean
!!0       // false
!!""      // false
!!null    // false
!!"text"  // true
!!42      // true

Nullish Coalescing (??)

// ?? returns right side only when left side is null or undefined
// Unlike ||, it does NOT trigger on 0, "", or false

const score = 0;
score || 100    // 100  (wrong! 0 is falsy, so we get the default)
score ?? 100    // 0    (correct! 0 is not null/undefined)

const label = "";
label || "default"  // "default" (wrong for empty strings that are intentional)
label ?? "default"  // ""        (correct)

// Real usage
function greet(name) {
    const displayName = name ?? "Anonymous";
    return `Hello, ${displayName}!`;
}

greet("Alice")     // "Hello, Alice!"
greet(null)        // "Hello, Anonymous!"
greet(undefined)   // "Hello, Anonymous!"
greet("")          // "Hello, !"   (empty string is not null)

Assignment Operators

let x = 10;

x += 5;   // x = x + 5  → 15
x -= 3;   // x = x - 3  → 12
x *= 2;   // x = x * 2  → 24
x /= 4;   // x = x / 4  → 6
x **= 2;  // x = x ** 2 → 36
x %= 10;  // x = x % 10 → 6

// Logical assignment (ES2021)
let a = null;
a ||= "default";   // a = a || "default" → a is now "default"

let b = 5;
b &&= b * 2;       // b = b && b*2 → b is now 10 (b was truthy)

let c = null;
c ??= "fallback";  // c = c ?? "fallback" → c is now "fallback"

Ternary Operator

// condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? "adult" : "minor";  // "adult"

// Can be nested (but limit to 2 levels for readability)
const grade = score >= 90 ? "A" 
            : score >= 80 ? "B"
            : score >= 70 ? "C"
            : "F";

// Great for JSX and template literals
const greeting = `Hello, ${user ? user.name : "Guest"}!`;

typeof and instanceof

typeof 42           // "number"
typeof "hello"      // "string"
typeof true         // "boolean"
typeof undefined    // "undefined"
typeof null         // "object"  (famous JavaScript bug)
typeof {}           // "object"
typeof []           // "object"  (arrays are objects)
typeof function(){} // "function"
typeof Symbol()     // "symbol"

// Check for array specifically
Array.isArray([])   // true
Array.isArray({})   // false

// instanceof checks the prototype chain
[] instanceof Array        // true
[] instanceof Object       // true (arrays are objects)
new Date() instanceof Date // true

class Dog {}
const rex = new Dog();
rex instanceof Dog    // true
rex instanceof Object // true

Operator Precedence

When mixing operators, precedence determines the order of evaluation:

// Higher precedence = evaluated first
// Full table: MDN Operator Precedence

2 + 3 * 4    // 14 (not 20) — * before +
(2 + 3) * 4  // 20 — parentheses override
2 ** 3 ** 2  // 512 (not 64) — ** is right-associative: 2 ** (3**2)

// Logical precedence: ! > && > ||
true || false && false  // true (&&  before ||)
(true || false) && false  // false

Quick reference:

  1. () — Grouping
  2. !, ++, -- — Unary
  3. ** — Exponentiation
  4. *, /, % — Multiplication
  5. +, - — Addition
  6. <, >, <=, >= — Comparison
  7. ===, !==, ==, != — Equality
  8. && — Logical AND
  9. ||, ?? — Logical OR / Nullish
  10. =, +=, -=, ... — Assignment

Next lesson: Control Flow — if statements, switch, and ternary for branching logic.

📱

Get this course's notes on Telegram!

Free cheat sheets, summaries & practice exercises

Get Notes Free →
!