TypeScript Booleans and Operators

Boolean Basics

TypeScript uses boolean to declare true/false values:

let isActive: boolean = true;
let hasAccess: boolean = false;

Booleans are often used in conditions and loops.

Comparison Operators

These return true or false based on the relationship between operands:

  • == Equal to (performs type coercion)
  • === Strict equal to (no type coercion)
  • != Not equal to (performs type coercion)
  • !== Strict not equal to (no type coercion)
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to
console.log(5 > 3);     // true
console.log(4 === 4);   // true
console.log(5 !== 10);  // true
console.log(2 <= 2);    // true
console.log(10 == "10"); // true (type coercion)
console.log(10 === "10"); // false (different types)

Logical Operators

Used to build compound boolean expressions:

let isAdmin: boolean = true;
let isLoggedIn: boolean = false;

// AND (&&) — true only if both are true
console.log(isAdmin && isLoggedIn); // false

// OR (||) — true if at least one is true
console.log(isAdmin || isLoggedIn); // true

// NOT (!) — inverts the boolean value
console.log(!isAdmin); // false

// Nullish Coalescing (??) — returns the right-hand value if the left is null or undefined
let userRole: string | null = null;
console.log(userRole ?? "Guest"); // "Guest"
  • && — Logical AND
  • || — Logical OR
  • ! — Logical NOT
  • ?? — Nullish Coalescing (TypeScript/ES2020+)

Arithmetic Operators

Perform standard math operations:

let x = 10;
let y = 3;

console.log(x + y); // 13
console.log(x - y); // 7
console.log(x * y); // 30
console.log(x / y); // 3.33
console.log(x % y); // 1

Strict Equality vs. Loose Equality

TypeScript encourages using === (strict equality) to compare both value and type.

console.log(5 === "5"); // false
console.log(5 == "5");  // true — not recommended

Best Practices

  • Use strict comparisons (=== and !==) instead of loose ones (==).
  • Wrap complex logic in parentheses to improve clarity.
  • Avoid using any or implicit coercion in boolean checks.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic