Skip to content
elephantoo

Conditionals

Lesson 5 of 34 12 min read

if/else, the ternary operator, switch, and truthy/falsy values in decisions.


Programs need to make decisions: show a discount if the cart is big enough, greet by time of day, reject an invalid password. JavaScript gives you if/else, the ternary operator, switch, and logical operators for this.

if, else if, else#

JavaScript
const hour = 14;

if (hour < 12) {
  console.log("Good morning");
} else if (hour < 18) {
  console.log("Good afternoon");
} else {
  console.log("Good evening");
}
Output
Good afternoon

JavaScript checks each condition from top to bottom and runs the first block whose condition is truthy. The else block runs if none match. Order matters: put the most specific conditions first.

Always use braces, even for one-line bodies. Braces prevent a classic bug where a second line looks like it's inside the if but isn't.

Conditions are truthy or falsy#

The condition doesn't have to be a boolean. Falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else is truthy.

JavaScript
const username = "";
if (username) {
  console.log(`Hello, ${username}`);
} else {
  console.log("Please enter a name");
}

const items = [];
if (items.length) {
  console.log("You have items");
} else {
  console.log("Your cart is empty"); // [] is truthy, but its length 0 is falsy
}
Output
Please enter a name
Your cart is empty

An empty array [] and empty object {} are truthy. Check arr.length === 0 or Object.keys(obj).length === 0 for emptiness.

Combining conditions#

JavaScript
const age = 25;
const hasId = true;
const isVip = false;

if (age >= 18 && hasId) {
  console.log("Entry allowed");
}

if (isVip || age > 60) {
  console.log("Free drink");
} else {
  console.log("Drinks are ₹150");
}

if (!isVip) {
  console.log("Join the VIP club!");
}
Output
Entry allowed
Drinks are ₹150
Join the VIP club!

When conditions get long, name them:

JavaScript
const cartTotal = 1200;
const isMember = true;
const qualifiesForFreeShipping = cartTotal >= 999 || isMember;
if (qualifiesForFreeShipping) console.log("Free shipping!");

Guard clauses: return early#

Deeply nested ifs are hard to read. In functions, handle the special cases first and return:

JavaScript
function checkout(cart, user) {
  if (!user) return "Please log in";
  if (cart.length === 0) return "Your cart is empty";
  if (!user.address) return "Add an address";
  return `Ordering ${cart.length} item(s) for ${user.name}`;
}

console.log(checkout([], { name: "Ada" }));
console.log(checkout(["book"], { name: "Ada", address: "Pune" }));
Output
Your cart is empty
Ordering 1 item(s) for Ada

The "happy path" stays at the bottom, un-indented.

The ternary operator#

condition ? valueIfTrue : valueIfFalse is an expression — it produces a value:

JavaScript
const score = 82;
const grade = score >= 50 ? "Pass" : "Fail";
console.log(`Result: ${grade}`);          // Result: Pass
console.log(`You have ${score} point${score === 1 ? "" : "s"}`);

Use ternaries for simple two-way choices. Nesting them (a ? b : c ? d : e) quickly becomes unreadable — switch to if/else or a lookup object.

switch#

switch compares one value against many cases using strict equality (===):

JavaScript
function dayType(day) {
  switch (day) {
    case "Saturday":
    case "Sunday":
      return "Weekend";
    case "Friday":
      return "Almost weekend";
    default:
      return "Weekday";
  }
}

console.log(dayType("Sunday")); // Weekend
console.log(dayType("Friday")); // Almost weekend
console.log(dayType("Monday")); // Weekday

Stacking case "Saturday": and case "Sunday": lets both share one block. Outside a function, end each case with break:

JavaScript
const level = 2;
switch (level) {
  case 1:
    console.log("Beginner");
    break;
  case 2:
    console.log("Intermediate");
    break; // without this, "Advanced" would also print!
  case 3:
    console.log("Advanced");
    break;
  default:
    console.log("Unknown level");
}
Output
Intermediate

Lookup objects: an alternative to long switches#

When you're just mapping values to values, an object is shorter:

JavaScript
const icons = { success: "✅", warning: "⚠️", error: "❌" };

function iconFor(status) {
  return icons[status] ?? "ℹ️";
}

console.log(iconFor("error"));   // ❌
console.log(iconFor("unknown")); // ℹ️

Logical operators as mini-conditionals#

You'll often see && and ?? used as short conditionals:

JavaScript
const user = { name: "Ada", nickname: null };
const displayName = user.nickname ?? user.name;
console.log(displayName); // Ada

const isAdmin = true;
isAdmin && console.log("Showing admin panel"); // runs only if isAdmin is truthy

cond && doSomething() is common in React JSX. In regular code, a plain if is usually clearer.

Comparing with ===, not =#

JavaScript
let status = "draft";
// if (status = "published") { ... }  ❌ assigns, and is always truthy!
if (status === "published") {
  console.log("Live");
} else {
  console.log("Not live yet"); // Not live yet
}

Common mistakes#

  • Using = instead of === in a condition.
  • Forgetting break in a switch (fall-through).
  • Assuming [] or "0" is falsy — both are truthy.
  • Writing if (x === 1 || 2) — that's always truthy because 2 is truthy. Write x === 1 || x === 2, or [1, 2].includes(x).

What's next#

Decisions let your code choose a path. Next, loops let it repeat work — over numbers, arrays and objects.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What does this log? const x = 0; if (x) { console.log("yes"); } else { console.log("no"); }

  2. 2.In a switch, what happens if you forget break at the end of a matching case?

  3. 3.Which is the idiomatic way to choose between two values in an expression?

Finished reading?

Mark this lesson complete to track your progress.