R
Rishtaara
JavaScript Fundamentals
Lesson 4 of 28Article15 min

If, Else, Switch & Truthy/Falsy

if runs code only when a condition is true. Use it for decisions — login checks, age rules, empty cart warnings.

if Statement

if runs code only when a condition is true. Use it for decisions — login checks, age rules, empty cart warnings.

Real-life example: IF it is raining, THEN take an umbrella. Otherwise walk normally.

Simple if
const score = 85;
if (score >= 60) {
  console.log("Pass");
}

else and else if

else runs when the if condition is false. else if checks another condition when the first one failed.

Real-life example: IF marks >= 90 → A grade, ELSE IF >= 75 → B grade, ELSE → practice more.

if / else if / else
const marks = 72;
if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else {
  console.log("Keep studying");
}

switch Statement

switch compares one value to many cases. Use break after each case or execution falls through to the next.

Real-life example: A vending machine button — press 1 for chai, 2 for coffee, default for water.

Use if/else for ranges (score >= 60). Use switch when comparing one variable to exact values (day === 3).
switch on day number
const day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Other day");
}

Truthy and Falsy Values

In conditions, JavaScript treats some values as false: false, 0, "", null, undefined, NaN. Everything else is truthy.

Real-life example: An empty wallet ("" or 0) means "no money" in a condition. A wallet with even 1 rupee is truthy.

Truthy / falsy in if
const name = "";
if (name) {
  console.log("Hello " + name);
} else {
  console.log("Please enter your name"); // runs
}

if ("Rishtaara") {
  console.log("Non-empty string is truthy"); // runs
}