SyntaxPilot
Courses/JavaScript/Lesson 5

JavaScript · Lesson 5 of 40 · 14 min

if/else, switch and the ternary operator

queued

These are the notes for JavaScript episode 5. Until now every program ran every line, top to bottom. Here you teach it to choose: if and else, else if ladders (and why their order matters), the = vs === trap, why you should always write braces, truthy values and && inside conditions, switch with case, break and default, fall-through, why switch needs converted input, and the ternary operator ? :. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

Why programs need decisions: free delivery above Rs 200

Ravi's chai stall has a delivery rule:

Order total What the app should say
under Rs 200 Delivery fee: Rs 30
Rs 200 or more Free delivery!

With only what we knew so far, the program prints both messages:

const total = 150;
console.log("Free delivery!");
console.log("Delivery fee: Rs 30");
Free delivery!
Delivery fee: Rs 30

Why it fails: a program runs every line, top to bottom, one after another. It has no way to skip a line. We need a way to say run this only when something is true. That is a decision (also called a conditional or control flow).

if and else: a railway junction

At the junction In JavaScript Meaning
The signal checks a question: is the track clear? (total >= 200) the condition: always true or false
True: take this track if (...) { ... } runs its block only when true
False: take the other track else { ... } runs its block only when false
  • Condition: an expression inside the round brackets of if, usually a comparison, that gives true or false.
  • Block: the lines inside curly brackets { }. They run together, or not at all.
  • Indentation: the two spaces before lines inside a block. JavaScript ignores it, but it shows the reader what is inside.
const total = 150;
if (total >= 200) {
  console.log("Free delivery!");
} else {
  console.log("Delivery fee: Rs 30");
  console.log(`Add Rs ${200 - total} more for free delivery`);
}
Delivery fee: Rs 30
Add Rs 50 more for free delivery

Change the first line to const total = 250;:

Free delivery!

Exactly one of the two blocks runs, never both. One program, two paths. else is optional: an if on its own simply skips its block when the condition is false.

const age = 18;
if (age === 18) {
  console.log("Just became an adult!");
}
Just became an adult!

else if ladders: the first true branch wins

Ravi's new offer has three paths:

Order total Discount
Rs 500 or more 20% off
Rs 200 or more 10% off
anything else no discount

For more than two paths, chain them: if, then else if, then else. The obvious attempt checks Rs 200 first:

const total = 600;
if (total >= 200) {
  console.log("10% off");
} else if (total >= 500) {
  console.log("20% off");
} else {
  console.log("No discount");
}
10% off

A Rs 600 customer should get 20%. Why it fails: JavaScript checks the conditions top to bottom and stops at the first true one. 600 >= 200 is true, so the first block ran and the rest were skipped. The 20% branch can never be reached.

Fix: strictest condition first.

const total = 600;
if (total >= 500) {
  console.log("20% off");
} else if (total >= 200) {
  console.log("10% off");
} else {
  console.log("No discount");
}
20% off

How the ladder works:

total >= 500 ?  ── yes → 20%   (step off the ladder)
      │ no
total >= 200 ?  ── yes → 10%   (step off the ladder)
      │ no
else           ──────→ no discount

The same bug on a report card: checking marks >= 60 before marks >= 70 puts a 75 in the 60 band, and the 70 band is never reached. A correct grading ladder, strictest first:

const marks = 82;
if (marks >= 90) {
  console.log("A");
} else if (marks >= 75) {
  console.log("B");
} else if (marks >= 50) {
  console.log("C");
} else {
  console.log("Fail");
}
B

The = trap: every order became a big order

We want to check whether an order is exactly Rs 500, but type one equals sign by habit:

let total = 100;
if (total = 500) {
  console.log("Big order!");
}
console.log(total);
Big order!
500

No error, and the customer's bill silently changed. Why: a single = doesn't ask a question, it assigns. It put 500 into total, and the value of the assignment (500) is truthy, so the block ran. Compare with ===:

let total = 100;
if (total === 500) {
  console.log("Big order!");
}
console.log(total);
100
Symbol Job Example
= puts a value in (assignment) total = 500
=== asks "exactly equal?" (same value and type) total === 500
!== asks "not equal?" total !== 500

Always use braces

If a block has only one line, JavaScript lets you leave out { }. Someone then adds a second indented line:

const total = 120;
if (total >= 200)
  console.log("Free delivery!");
  console.log("Delivery fee waived");
Delivery fee waived

A Rs 120 order had its fee waived. Why: without braces, if owns only the very next statement. The second line isn't inside anything, whatever its indentation, so it runs every time. Fix: always write the curly brackets, even for one line.

const total = 120;
if (total >= 200) {
  console.log("Free delivery!");
  console.log("Delivery fee waived");
}

(prints nothing)

Truthy values and && inside conditions

An if accepts any value, not just true/false. It asks "is this value truthy?" (episode 3: the six falsy values are false, 0, "", null, undefined, NaN). Conditions can also be combined with && (AND), || (OR) and ! (NOT).

const coupon = "";   // the box was left empty
if (coupon) {
  console.log(`Applying ${coupon}`);
} else {
  console.log("No coupon");
}
const isWeekend = true;
const total = 250;
if (isWeekend && total >= 200) {
  console.log("Free samosa!");
}
No coupon
Free samosa!

Empty text is falsy, so else ran. With &&, both conditions had to be true. || needs either one, and ! flips:

const age = 20;
const hasTicket = false;
if (age >= 18 || hasTicket) {
  console.log("Either one is enough");
}
if (!hasTicket) {
  console.log("Please buy a ticket");
}
Either one is enough
Please buy a ticket

switch: a special for every day

Ravi has a special for each day: Monday masala chai, Tuesday samosa, Wednesday vada pav... With else if that is seven rungs, each repeating day === "...": long, and the same variable asked the same question again and again.

Old radio In JavaScript
Press a station button switch (day): the value to match
The radio jumps straight to that station case "Mon": where to start when day === "Mon"
Stop listening break; leave the switch
No station matches: static default: runs when no case matched (like else)

Fall-through: the missing break

Most beginners forget break:

const day = "Tue";
switch (day) {
  case "Mon":
    console.log("Masala chai Rs 10");
  case "Tue":
    console.log("Samosa Rs 12");
  case "Wed":
    console.log("Vada pav Rs 15");
  default:
    console.log("Regular menu");
}
Samosa Rs 12
Vada pav Rs 15
Regular menu

Three specials on a Tuesday. Why: a case is only a starting point. Once JavaScript jumps in, it keeps running every line below, through the other cases, until it hits break or the end of the switch. This is fall-through.

break, grouped cases and default

End every case with break. Fall-through is useful on purpose: stack two cases to share one block.

const day = "Sun";
switch (day) {
  case "Mon":
    console.log("Masala chai Rs 10");
    break;
  case "Tue":
    console.log("Samosa Rs 12");
    break;
  case "Sat":
  case "Sun":
    console.log("Weekend combo Rs 40");
    break;
  default:
    console.log("Regular menu");
}
Weekend combo Rs 40

Another useful grouping, days in a month:

const month = 2;
let days;
switch (month) {
  case 2:
    days = 28;
    break;
  case 4:
  case 6:
  case 9:
  case 11:
    days = 30;
    break;
  default:
    days = 31;
}
console.log(`Month ${month} has ${days} days`);
Month 2 has 28 days

switch compares with ===

A menu: press 1 for chai, 2 for coffee. The choice is read from the keyboard, so it is text:

const choice = "2";   // typed on the keyboard
switch (choice) {
  case 1:
    console.log("Chai");
    break;
  case 2:
    console.log("Coffee");
    break;
  default:
    console.log("Invalid choice");
}
Invalid choice

switch uses strict equality (===): the string "2" is not the number 2. Convert first:

const choice = "2";   // typed on the keyboard
switch (Number(choice)) {
  case 1:
    console.log("Chai");
    break;
  case 2:
    console.log("Coffee");
    break;
  default:
    console.log("Invalid choice");
}
Coffee

switch or else if? Use switch when you compare one value against many exact values. Use else if for ranges (>= 500) or mixed conditions.

The ternary operator: "1 items"

Ravi's cart says "1 items". The if/else fix works but takes eight lines just to pick one word:

const qty = 1;
let label;
if (qty === 1) {
  label = "item";
} else {
  label = "items";
}
console.log(`${qty} ${label}`);
1 item

The ternary operator is a one-line decision with three parts: condition ? valueIfTrue : valueIfFalse.

const qty = 1;
const label = qty === 1 ? "item" : "items";
console.log(`${qty} ${label}`);
const hour = 19;
console.log(hour < 12 ? "Good morning" : "Good evening");
1 item
Good evening

Read it as a question: one item? then "item", else "items". Because it produces a value, it can go straight into const, a template literal or console.log. Even or odd:

const n = 7;
console.log(n % 2 === 0 ? "Even" : "Odd");
Odd

Rules of thumb:

  • Ternary: choose between two values.
  • if/else: run actions, or more than two paths.
  • Never nest ternaries inside ternaries: nobody can read them.

Common mistakes (and what really happens)

You wrote What happens Why Fix
if (total = 500) (no error) always runs, total becomes 500 = assigns, it doesn't compare if (total === 500)
if (t >= 200) … else if (t >= 500) (no error) 600 gets 10% the first true branch wins strictest condition first
if (t >= 200) + two indented lines, no { } (no error) the second line always runs if owns only the next statement always write { }
case "Tue": console.log(...) (no break) (no error) runs the next cases too fall-through end each case with break;
switch ("2") with case 2: (no error) goes to default switch uses === switch (Number(choice))
if (...) { ... } else { ... (no closing }) SyntaxError: Unexpected end of input a { was never closed close every { with }

The missing brace, run for real:

const x = 5;
if (x > 10) {
  console.log("big");
} else {
  console.log("small");
SyntaxError: Unexpected end of input

Node reached the end of the file still waiting for the }. Five of these six mistakes give no error at all, so read your output carefully.

Mini project: Ravi's order checker

Everything from today: a greeting with a ternary, the discount tier with an else if ladder (biggest first), a switch with stacked weekend cases, the delivery fee with a ternary, and the final amount.

const hour = 9;
const day = "Sat";
const total = 540;
console.log(hour < 12 ? "Good morning!" : "Good evening!");
let discount = 0;
if (total >= 500) {
  discount = 20;
} else if (total >= 200) {
  discount = 10;
}
switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend: free samosa!");
    break;
}
const fee = total >= 200 ? 0 : 30;
const pay = total - total * discount / 100 + fee;
console.log(`${discount}% off, delivery Rs ${fee}, pay Rs ${pay}`);
Good morning!
Weekend: free samosa!
20% off, delivery Rs 0, pay Rs 432

Try it: change hour, day and total, predict every line, then run. (With total = 150 on a "Mon" at hour 20 you get Good evening!, 0% off, delivery Rs 30, pay Rs 180.)

Practice

  1. Grade marks: 90+ → A, 75+ → B, 50+ → C, else Fail.
  2. A switch for months: 1-12 → number of days (ignore leap years).
  3. With a ternary, print "Even" or "Odd" for a number.
  4. Find the bug: if (age = 18) { console.log("Adult"); }
Solutions and hints
  1. Strictest first: if (marks >= 90) … else if (marks >= 75) … else if (marks >= 50) … else …. With marks = 82 it prints B.
  2. Group the 30-day months with stacked cases (case 4: case 6: case 9: case 11:), case 2 gives 28, and default gives 31. month = 2 prints Month 2 has 28 days.
  3. console.log(n % 2 === 0 ? "Even" : "Odd"); with n = 7 prints Odd.
  4. One = assigns 18 to age; 18 is truthy, so "Adult" always prints (and age is now 18). Write if (age === 18), or more likely if (age >= 18). (If age was declared with const, the assignment throws TypeError: Assignment to constant variable.)

Quick quiz

What does this print?

const marks = 75;
if (marks >= 60) {
  console.log("B");
} else if (marks >= 70) {
  console.log("A");
} else {
  console.log("C");
}
  • A. A
  • B. B
  • C. C
  • D. B and A
Answer

B. The ladder is checked top to bottom. 75 >= 60 is true, so "B" prints and the rest is skipped, even though 75 >= 70 is also true. Same bug as the discount ladder.

Interview questions

  • What's the difference between =, == and ===? What happens with if (x = 5)?
  • In an if … else if … else chain, how many blocks can run?
  • Why should you always use braces, even for one-line blocks?
  • What is fall-through in a switch? When is it useful?
  • What comparison does switch use? What happens with switch ("2") and case 2?
  • When would you choose switch over else if, and vice versa?
  • What is the ternary operator? When should you avoid it?
  • Which values are falsy in an if condition?

Glossary

Term Meaning Example
Decision / conditional code that runs only when a condition holds if (total >= 200) { … }
Condition an expression that gives true or false total >= 200
Block lines grouped by curly brackets; they run together { console.log("Hi"); }
Braces the curly brackets { } that mark a block if (x) { … }
Indentation spaces before lines inside a block, for the reader two spaces before console.log
if runs its block only when the condition is truthy if (age >= 18) { … }
else runs its block when the if condition is falsy } else { … }
else if another condition, checked only if the ones above failed } else if (t >= 200) {
Ladder an if … else if … else chain; the first true branch wins discount tiers
Assignment = puts a value into a variable total = 500
Strict equality === same value and same type total === 500
Truthy / falsy values that act like true / false in a condition "" falsy, "0" truthy
&&, \|\|, ! AND (both), OR (either), NOT (flip) isWeekend && total >= 200
switch jumps to the case matching one value switch (day) { … }
case a starting point inside a switch, matched with === case "Mon":
break leaves the switch (or a loop) immediately break;
default runs when no case matched default: …
Fall-through running on into the next cases when there is no break stacked case "Sat": case "Sun":
Ternary operator a one-line choice between two values qty === 1 ? "item" : "items"
SyntaxError Node can't read the code (grammar mistake), nothing runs Unexpected end of input

Summary

  • if (condition) { } runs a block only when the condition is true; else handles the rest. Exactly one block runs.
  • In an else if ladder the first true branch wins: put the strictest condition first.
  • Inside if use ===, never =. Always write { }.
  • Any value works as a condition (truthy/falsy); combine with &&, ||, !.
  • switch / case / break / default picks one of many exact values; it compares with ===, so convert input with Number(). A missing break falls through.
  • The ternary cond ? a : b picks one of two values in one line.

Next episode: loops. Ravi must print a token for every customer in a queue of a hundred, so you'll invent for, while, for...of and for...in.