~/hackweb.dev
JavaScript if/else & Truthy/Falsy
Quiz
...

JavaScript if/else & Truthy/Falsy

beginner · updated Tue Sep 08 2026Contribute

Master conditionals to make your code decision-aware.

JavaScript if/else & Truthy/Falsy

Conditionals let your code make decisions based on different situations.

if Statement

Checks a condition and runs code only if it’s true:

let temperature = 30;

if (temperature > 25) {
  console.log("It's hot outside!");
}

else Statement

Provides an alternative when the condition is false:

let temperature = 15;

if (temperature > 25) {
  console.log("It's hot!");
} else {
  console.log("It's cool!");
}

else if — Multiple Conditions

let score = 85;
let grade;

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "F";
}

JavaScript checks conditions in order. It runs the first true block and skips the rest.

Truthy and Falsy Values

JavaScript treats non-boolean values as true or false:

// Falsy — treated as false
false, 0, "", null, undefined, NaN

// Truthy — treated as true
true, 1, -1, "hello", " ", [], {}, function(){}

Remember: An empty array [] is truthy, even though it has no elements.

let name = "John";

// Direct truthy check — cleaner
if (name) {
  console.log("Name exists");
}

Ternary Operator

Short if/else for simple conditions:

let age = 18;
let status = age >= 18 ? "Adult" : "Minor";

Format: condition ? valueIfTrue : valueIfFalse

Complete Example: Login Check

let username = null;
let isLoggedIn = false;
let isAdmin = false;

if (!username) {
  console.log("Please log in");
} else if (!isLoggedIn) {
  console.log("Account not active");
} else if (isAdmin) {
  console.log("Welcome, Admin!");
} else {
  console.log("Welcome, User!");
}

Best Practices

  1. Use strict equality=== prevents type coercion bugs
  2. Use early returns — Reduce nesting
  3. Keep conditions simple — Break complex logic apart
  4. Use ternary for simple cases — Don’t overcomplicate
  5. Understand truthy/falsy — Prevents unexpected behavior

Common Mistakes

  1. Using == instead of === — Type coercion causes bugs
  2. Forgetting else — No fallback case
  3. Deep nesting — Hard to read and maintain
  4. Confusing truthy/falsy0 and "" are falsy
  5. Assignment in condition — Use === not =