Chapter 5: Conditional Statements and Decision Making in JS


Chapter 5: Conditional Statements and Decision Making in JS

Arjun, a first-year BCA student in Jaipur, wants to help his mother, a school teacher, with her class results. Her rule is simple: 90 and above is an A, 80 and above is a B, 70 and above is a C, and anything lower is a D. She applies it without thinking, the same way she carries an umbrella when it is raining or skips breakfast when she is late. Each of these is a small rule: check something, then act on the answer. Arjun's program, though, prints the same line for every student, whatever their marks. How do you make a program look at a value and choose what to do next?

A computer is very fast, but it cannot make any of these choices on its own. It only follows instructions, so if a program should behave differently in different situations, we have to spell out every rule. That is the job of conditional statements. In Chapter 4 we learned the comparison and logical operators that produce true and false. In this chapter we use those answers to choose which code runs.

What Is a Conditional Statement?

A conditional statement is a block of code that runs only when a condition is true. Think of a security guard at an office gate who follows one rule: if the person has an ID card, let them in, otherwise stop them. Written as plain logic and then as JavaScript, it looks like this:

IF person has ID card
  Allow entry
ELSE
  Deny entry
let hasIdCard = true;

if (hasIdCard) {
  console.log("Allow entry");
} else {
  console.log("Deny entry");
}
// Allow entry

JavaScript checks the condition inside the brackets. If it is true, the first block runs. If it is false, the else block runs. Exactly one of the two blocks runs, never both and never neither.

Almost every app you use is built on rules like this. When you tap "Buy Now", the shop has to ask: is the user logged in, is the product in stock, did the payment succeed, does the courier deliver to this PIN code? Each question is a condition, and each answer decides what happens next. Without conditions, every user would get exactly the same result whatever their situation, and the software would be useless.

Booleans: The Answer to Every Condition

A condition always ends up as a Boolean, a value that is either true or false, like a light switch that is on or off. You can store Booleans in variables with clear names, which makes conditions read almost like English:

let isLoggedIn = true;
let isAdmin = false;

if (isLoggedIn && !isAdmin) {
  console.log("Show normal dashboard");
}
// Show normal dashboard

Most conditions are built with the comparison operators from Chapter 4. Here is a quick reminder of how each one looks inside an if:

OperatorMeaningExample conditionResult
===Equal (same value and type)5 === "5"false
!==Not equal (value or type differs)10 !== "10"true
== / !=Loose equal / not equal (converts types first)5 == "5"true
> / <Greater / less than20 > 10true
>= / <=Greater / less than or equal18 >= 18true

Use === and !== in your conditions. The loose versions convert types behind your back, which is how 5 == "5" ends up true. Chapter 4 explains why this causes bugs.

The if Statement

The simplest form is a plain if: "if this is true, do that". There is no else, so when the condition is false, JavaScript simply skips the block and carries on with the next line.

let age = 20;

if (age >= 18) {
  console.log("You can vote");
}
// You can vote

JavaScript works out 20 >= 18, gets true, and runs the block. Now change the age to 15:

let age = 15;

if (age >= 18) {
  console.log("You can vote");
}
console.log("Check finished");
// Check finished

Nothing from inside the block is printed, and the program does not stop or show an error. It just moves on. You can picture it as a checkpoint on a road: if the answer is yes, you take the side lane; if not, you continue straight.

The if...else Statement

Most real decisions have two outcomes, and else handles the second one. An ATM is a good example. It checks whether your balance covers the amount you asked for, then either gives you cash or shows an error:

let balance = 500;
let withdrawal = 1000;

if (balance >= withdrawal) {
  console.log("Cash dispensed");
} else {
  console.log("Insufficient balance");
}
// Insufficient balance

A login check works the same way: if the password is correct, show "Login successful", otherwise show "Invalid password". Any time you hear yourself say "otherwise", you are describing an else.

The if...else if...else Chain

Some decisions have more than two answers. A school grading system is the classic example: 90 and above is an A, 80 and above is a B, 70 and above is a C, and anything lower is a D. For this, you chain several conditions with else if:

let marks = 85;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 80) {
  console.log("Grade B");
} else if (marks >= 70) {
  console.log("Grade C");
} else {
  console.log("Grade D");
}
// Grade B

JavaScript checks the conditions from top to bottom. It runs the block of the first condition that is true and then skips everything else in the chain. For 85, the first check (85 >= 90) is false, the second (85 >= 80) is true, so it prints "Grade B" and never even looks at the C check. The final else is the "none of the above" case, and it runs only if every condition before it was false.

The Order of Conditions Matters

Because JavaScript stops at the first true condition, putting the checks in the wrong order gives wrong answers without any error. Here is the same grading code with the conditions written from the lowest grade upwards:

let marks = 95;

if (marks >= 70) {
  console.log("Grade C");
} else if (marks >= 80) {
  console.log("Grade B");
} else if (marks >= 90) {
  console.log("Grade A");
} else {
  console.log("Grade D");
}
// Grade C  ← wrong! A student with 95 should get an A

A score of 95 is also greater than 70, so the very first check matches and the student gets a C. The A and B branches can never run for anyone. The rule is simple: when your ranges overlap like this (every 95 is also above 70), check the narrowest or most demanding condition first. With >=, go from the highest number down. With <=, go from the lowest number up, as in the next example.

This is exactly the mistake Arjun makes on his first try. He starts with the easiest check, marks >= 70, and works upwards, so his mother's top student, with 95 marks, comes out as "Grade C". There is no error message; the result just looks wrong. Flipping the order to start from 90 fixes every student's grade at once.

Example: Delivery Charges by Distance

Say a food delivery app charges by distance: up to 5 km costs ₹30, up to 10 km costs ₹60, up to 20 km costs ₹100, and anything further costs ₹150. Since we are using <=, the smallest distance goes first:

for (const distance of [3, 5, 5.5, 12, 25]) {
  let fee;
  if (distance <= 5) {
    fee = 30;
  } else if (distance <= 10) {
    fee = 60;
  } else if (distance <= 20) {
    fee = 100;
  } else {
    fee = 150;
  }
  console.log(distance + " km → ₹" + fee);
}
// 3 km → ₹30
// 5 km → ₹30
// 5.5 km → ₹60
// 12 km → ₹100
// 25 km → ₹150

Notice that we don't write distance > 5 && distance <= 10 in the second branch. We don't need to, because we only reach that line if the first check already failed, so the distance must be more than 5. Also check the boundaries on purpose: exactly 5 km gives ₹30 because we used <=. If the business rule says "5 km and above costs ₹60", you would need < instead. Off-by-one mistakes at the edges are among the most common bugs in pricing code. (The for loop simply repeats the block for each distance in the list; loops come later in this series.)

The Ternary Operator: A One-Line if...else

When you only need to pick between two values, the ternary operator from Chapter 4 is shorter than a full if...else. It reads as "condition ? value if true : value if false".

let cartTotal = 350;
const fee = cartTotal >= 499 ? 0 : 40;
console.log("Delivery fee: ₹" + fee); // Delivery fee: ₹40

It is tempting to chain ternaries to replace a whole else if ladder. This works, but it gets hard to read very quickly:

let marks = 85;
const grade = marks >= 90 ? "A" : marks >= 80 ? "B" : marks >= 70 ? "C" : "D";
console.log(grade); // B

A good rule: use the ternary when choosing between two simple values, and use if...else when there are more branches or when each branch needs to do something (log, save, call a function) rather than just produce a value.

The switch Statement

When you compare one value against a list of exact options, a switch can be cleaner than a long else if chain. Here a checkout page reacts to the payment method the customer chose:

let method = "upi";

switch (method) {
  case "upi":
    console.log("Open UPI app");
    break;
  case "card":
    console.log("Ask for card details");
    break;
  case "cod":
    console.log("Pay on delivery");
    break;
  default:
    console.log("Unknown payment method");
}
// Open UPI app

JavaScript compares method with each case from top to bottom. When it finds a match, it starts running code from that point. The break tells it to leave the switch. The default branch works like the final else: it runs when no case matched.

Fall-Through and the Missing break Bug

Here is the part that surprises beginners. A switch does not stop at the end of a case on its own. Once it finds a match, it keeps running every line below until it hits a break or reaches the end. This is called fall-through. Forget the break statements and watch what happens:

let method = "upi";

switch (method) {
  case "upi":
    console.log("Open UPI app");
  case "card":
    console.log("Ask for card details");
  case "cod":
    console.log("Pay on delivery");
    break;
  default:
    console.log("Unknown payment method");
}
// Open UPI app
// Ask for card details
// Pay on delivery

The customer chose UPI, but the code also asks for card details and offers cash on delivery. No error appears, so this kind of bug can easily slip through. Make it a habit to write break (or return, inside a function) at the end of every case, and to add default even if you think every option is covered.

Grouping Cases on Purpose

Fall-through does have one honest use: letting several values share the same code. Put the cases one after another with nothing between them:

let day = "Sun";

switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend: shop opens at 10 am");
    break;
  default:
    console.log("Weekday: shop opens at 8 am");
}
// Weekend: shop opens at 10 am

"Sat" has no code of its own, so it falls into the "Sun" block. This is clear because the empty case is obviously intentional. If you ever let a case with code fall through on purpose, add a comment like // falls through so the next reader knows it isn't a mistake.

switch Uses Strict Comparison (===)

A switch compares values with ===, so the type must match as well as the value. This matters because input from forms, prompts and URLs arrives as text:

let choice = "2"; // from a form, so it is a string

switch (choice) {
  case 1:
    console.log("You picked Hindi");
    break;
  case 2:
    console.log("You picked English");
    break;
  default:
    console.log("Invalid choice");
}
// Invalid choice  ← "2" is not === 2

switch (Number(choice)) {
  case 1:
    console.log("You picked Hindi");
    break;
  case 2:
    console.log("You picked English");
    break;
  default:
    console.log("Invalid choice");
}
// You picked English

The fix is to convert the value before the switch, just like we converted form input in Chapter 4. String cases are also case-sensitive, so "mon" will not match case "Mon". If the text could arrive in any case, use switch (day.toLowerCase()) and write all cases in lower case.

switch or if...else?

SituationBetter choiceWhy
One value compared with several fixed options ("upi", "card", "cod")switchEach option is easy to see and add
Ranges (marks >= 90, distance <= 5)if...else ifswitch only checks exact equality
Conditions on different variables (isLoggedIn, stock)if...else ifswitch looks at a single value
Each option just maps to a value (a label, a price)Lookup object (below)Data instead of code, shortest to read

Truthy and Falsy Values in Conditions

The condition inside an if does not have to be a real Boolean. JavaScript converts whatever you give it into true or false. Values that become false are called falsy (like 0, "", null and undefined), and everything else is truthy. The full list is in the Truthy and Falsy section of Chapter 4, so here we only look at how it affects conditions.

let username = "";
if (username) {
  console.log("Welcome, " + username);
} else {
  console.log("Please enter your name");
}
// Please enter your name

let quantity = 0;
if (quantity) {
  console.log("Quantity set");
} else {
  console.log("No quantity?");
}
// No quantity?  ← but 0 was a real, chosen value

if (quantity !== undefined) {
  console.log("Quantity is", quantity);
}
// Quantity is 0

The short form if (username) is a neat way to check that something was typed. The trap is numbers: if (quantity) treats a valid 0 the same as "missing". When zero (or an empty string) is a meaningful answer, compare explicitly instead of relying on truthiness.

Nested Conditions vs Guard Clauses

Sometimes one decision depends on another. For example, only an active employee who is also a manager should see the management dashboard. You can put one if inside another, which is called nesting:

let active = true;
let manager = true;

if (active) {
  if (manager) {
    console.log("Access management dashboard");
  }
}
// Access management dashboard

For two simple checks, if (active && manager) says the same thing on one line. Nesting becomes a real problem when every level has its own else. Here is a checkout check written in the nested style. (We wrap it in a function, a reusable block of code that returns an answer. Functions are the topic of Chapter 6; for now just read return as "give back this answer and stop".)

function checkoutNested(user, cart, address) {
  if (user) {
    if (cart.length > 0) {
      if (address) {
        return "Order placed";
      } else {
        return "Add a delivery address";
      }
    } else {
      return "Your cart is empty";
    }
  } else {
    return "Please log in";
  }
}

console.log(checkoutNested({ name: "Asha" }, ["rice"], null));
// Add a delivery address

The code works, but the real action ("Order placed") is buried three levels deep, and each error message sits far away from the check that causes it. Some people call this shape the "pyramid" or "arrow" because of the way the code drifts to the right.

A guard clause flips the logic. You check for each problem first and leave immediately with return if you find one. Whatever is left at the bottom is the happy path:

function checkout(user, cart, address) {
  if (!user) return "Please log in";
  if (cart.length === 0) return "Your cart is empty";
  if (!address) return "Add a delivery address";

  return "Order placed";
}

console.log(checkout({ name: "Asha" }, ["rice"], null));       // Add a delivery address
console.log(checkout(null, [], null));                         // Please log in
console.log(checkout({ name: "Asha" }, ["rice"], "110001"));   // Order placed

Both versions give the same answers, but the second one reads like a checklist. Each rule sits on one line next to its message, and adding a new rule (say, "PIN code not serviceable") means adding one line instead of another level of brackets. This "early return" style is common in professional code for exactly that reason.

The original login example in this series used the nested style: check the email, and inside that, check the password. As a learning exercise it is fine. In a real login system, though, you should show one message such as "Invalid email or password" for both cases, so an attacker cannot use the error to find out which email addresses are registered.

Lookup Tables: Replacing Long switch and if Chains

A lot of switch statements only translate one value into another. When that is all a chain does, a plain object can hold the mapping as data:

const statusText = {
  placed: "Order received",
  packed: "Packed and ready",
  shipped: "On the way",
  delivered: "Delivered",
};

let status = "shipped";
console.log(statusText[status] ?? "Unknown status"); // On the way

status = "lost";
console.log(statusText[status] ?? "Unknown status"); // Unknown status

The object does the job of four case blocks, and ?? plays the role of default. Adding a new status is one new line, and the table can even come from a settings file or a database later. Objects are covered properly in Chapter 7.

One edge case most tutorials skip: every object quietly inherits some built-in properties, such as toString. If the key comes from user input, a value like "toString" will find something you never put there:

console.log(statusText["toString"] ?? "Unknown status");
// [Function: toString]  ← not one of our statuses!

console.log(Object.hasOwn(statusText, "toString") ? statusText["toString"] : "Unknown status");
// Unknown status

Object.hasOwn() checks only the keys you added yourself. Use it whenever the key comes from outside your code. (A Map avoids the issue entirely, which you will meet later in the series.)

Putting It Together: Movie Ticket Pricing

Let's combine a lookup table, guard clauses and plain if statements into one realistic rule set. A cinema has these prices:

  • Regular seat ₹150, premium seat ₹250, recliner ₹450.
  • Children under 3 watch free.
  • Every Tuesday, ₹50 off any seat.
  • Senior citizens (60 and above) get a further ₹30 off.
const seatPrice = {
  regular: 150,
  premium: 250,
  recliner: 450,
};

function ticketPrice(seat, age, day) {
  if (!Object.hasOwn(seatPrice, seat)) return "Unknown seat type";
  if (age < 3) return 0;

  let price = seatPrice[seat];
  if (day === "Tue") price -= 50;
  if (age >= 60) price -= 30;
  return price;
}

console.log(ticketPrice("premium", 30, "Sat"));  // 250
console.log(ticketPrice("premium", 30, "Tue"));  // 200
console.log(ticketPrice("regular", 65, "Tue"));  // 70
console.log(ticketPrice("recliner", 2, "Sun"));  // 0
console.log(ticketPrice("balcony", 30, "Mon"));  // Unknown seat type

A few design choices are worth noticing. The two guard clauses deal with the special cases first (bad input, free tickets), so the main calculation does not need to worry about them. The prices live in an object, not in a switch, so a new seat type is a one-line change. And the two discounts are separate if statements, not an else if chain, because both can apply to the same ticket. A senior on a Tuesday pays ₹150 − ₹50 − ₹30 = ₹70. Choosing between "independent ifs" and "one else if chain" is really a question about the business rule: can several rules apply together, or only one?

Common Mistakes (and the Fix)

MistakeWhat happensFix
if (age = 18)= assigns 18 to age; the condition is always true and the old value is lostCompare with ===: if (age === 18)
Checking marks >= 70 before marks >= 90Higher grades can never be reachedPut the narrowest range first
Forgetting break in a switchCode from the next cases also runs (fall-through)End every case with break or return
switch on form input with number cases"2" never matches case 2, so default runsConvert first: switch (Number(choice))
if (quantity) when 0 is validA real 0 is treated as missingCompare explicitly: quantity !== undefined
Four levels of nested if/elseHard to read; messages far from their checksUse guard clauses with early return

The first one deserves a closer look, because it doesn't throw an error. The assignment returns the value 18, which is truthy, so the block always runs:

let age = 25;

if (age = 18) {
  console.log("You are exactly 18");
}
console.log(age);
// You are exactly 18
// 18

My Opinion

Reach for guard clauses before nesting. Once a function needs more than two levels of if, rewrite it so each problem is checked and returned at the top. It is the single easiest way to make beginner code look and read like professional code.

Always write a default or a final else. Even if you are sure every case is covered, data changes. A default that logs "Unknown payment method" turns a silent bug into a visible one.

Prefer a lookup object when every branch just returns a value. A switch with twenty cases that each set a label is really a table pretending to be code. Store it as data and the logic shrinks to one line.

Don't nest ternaries. One ternary choosing between two values is great. Two or more in a row should become an if...else if chain or a lookup, because the reader's time matters more than the saved lines.

Test the edges, not just the middle. For any range-based rule, run the exact boundary values (5 km, 499 rupees, age 60) before trusting it. That is where wrong operators and wrong ordering show up.

Try It Yourself

Predict the output of each snippet before running it in your browser console (press F12 → Console). Answers are below.

1. let t = 30;
   if (t > 25) console.log("Hot");
   else if (t > 35) console.log("Very hot");
   else console.log("Pleasant");

2. switch ("5") {
     case 5: console.log("number five"); break;
     case "5": console.log("text five"); break;
   }

3. switch ("b") {
     case "a": console.log("A");
     case "b": console.log("B");
     case "c": console.log("C");
     default: console.log("D");
   }

4. let day = "mon";
   switch (day) {
     case "Mon": console.log("Monday"); break;
     default: console.log("No match");
   }

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

6. let stock = 0;
   if (stock > 0) console.log("Add to cart");
   else if (stock === 0) console.log("Notify me");
Show answers
1. Hot        → 30 > 25 matches first; the "Very hot" check is in the wrong
                order and can never run (36 would also print "Hot")
2. text five  → switch uses ===, so "5" only matches the string case
3. B C D      → no break, so it falls through every case below "b"
4. No match   → "mon" and "Mon" are different strings
5. Odd        → 7 % 2 is 1, not 0
6. Notify me  → 0 > 0 is false, 0 === 0 is true

Frequently Asked Questions

Do I need curly braces for a one-line if?

No, if (x) doSomething(); works. But if you later add a second line, only the first one is controlled by the if, which is an easy bug to miss. Many teams require braces everywhere for that reason, and beginners should follow the same habit.

Is switch faster than if...else?

For the small number of branches in normal code, any difference is too small to matter. Choose the one that reads better: switch for one value against fixed options, if...else for ranges and mixed conditions.

Can a switch check ranges like marks >= 90?

Only with a trick called switch (true), where each case is a condition. It works, but an if...else if chain says the same thing more clearly, so prefer that for ranges.

When should I use several ifs instead of else if?

Use one else if chain when only one branch should ever run (a grade, a delivery slab). Use separate if statements when several rules can apply together, like the Tuesday and senior discounts in the movie ticket example.

Key Takeaways

  • A conditional statement runs code only when its condition is true; else handles the "otherwise" case.
  • An else if chain runs the first matching branch only, so put the narrowest range first.
  • Use the ternary for choosing between two simple values; avoid nesting it.
  • switch compares with ===, falls through without break, and can group cases on purpose.
  • Conditions use truthy/falsy rules, so compare explicitly when 0 or "" are valid values.
  • Guard clauses with early return keep code flat and readable compared to deep nesting.
  • When each branch only maps a value to another value, a lookup object is simpler than switch.
  • Never write = inside a condition when you mean ===.

In the next chapter we look at functions properly, the reusable blocks we used here for guard clauses and ticket pricing.

References

Related Articles

Post a Comment

0 Comments