JavaScript Operators

๐Ÿ“š Lesson 3 of 22  โ€ข  โฑ 10 min read  โ€ข  Beginner

Arithmetic Operators

JavaScript
let a = 10, b = 3;

console.log(a + b);   // 13 โ€” addition
console.log(a - b);   // 7  โ€” subtraction
console.log(a * b);   // 30 โ€” multiplication
console.log(a / b);   // 3.33 โ€” division
console.log(a % b);   // 1  โ€” remainder (modulo)
console.log(a ** b);  // 1000 โ€” exponentiation (10ยณ)

// Increment / Decrement
let x = 5;
x++;  // x is now 6 (post-increment)
x--;  // x is now 5 (post-decrement)
++x;  // increment THEN use value

Assignment Operators

JavaScript
let n = 10;
n += 5;   // n = n + 5  โ†’ 15
n -= 3;   // n = n - 3  โ†’ 12
n *= 2;   // n = n * 2  โ†’ 24
n /= 4;   // n = n / 4  โ†’ 6
n **= 2;  // n = n ** 2 โ†’ 36
n %= 5;   // n = n % 5  โ†’ 1

Comparison Operators

JavaScript
// == (loose) vs === (strict) โ€” always use ===
5 == "5"   // true  โ€” type coercion (dangerous!)
5 === "5"  // false โ€” different types, no coercion
5 !== "5"  // true  โ€” use !== instead of !=

10 > 5    // true
10 < 5    // false
10 >= 10  // true
10 <= 9   // false

Logical Operators

JavaScript
// && (AND) โ€” both must be true
true && true   // true
true && false  // false

// || (OR) โ€” at least one must be true
false || true  // true
false || false // false

// ! (NOT) โ€” inverts
!true   // false
!false  // true

// Short-circuit evaluation
const name = "" || "Guest";   // "Guest" (falsy || fallback)
const user = null;
const age  = user && user.age; // null (stops at null)

Ternary Operator

JavaScript
// condition ? value-if-true : value-if-false
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

// In JSX / template strings
const msg = `You are ${age >= 18 ? "allowed" : "not allowed"}`;

Nullish Coalescing (??)

JavaScript
// ?? returns right side only if left is null or undefined
// Different from || which triggers on ANY falsy value (0, "", false)
const score = 0;
score || 100   // 100  (wrong! 0 is falsy)
score ?? 100   // 0    (correct! 0 is not null/undefined)

const config = null;
config ?? "default"  // "default"