Lesson 4 of 12

JavaScript Conditions: if, else and switch

Until now, every line in our scripts ran exactly once, from top to bottom. Real programs need to make choices: show “Free delivery” only above a certain cart value, greet users differently in the morning and the evening, or show an error only when a field is empty. Conditional statements let your code take different paths depending on whether something is true. This lesson covers JavaScript if else statements, switch and the ternary operator.

Conditions are built from the comparison and logical operators you met in JavaScript Operators, so keep ===, > and && fresh in your mind.

The if statement

An if statement runs a block of code only when its condition is true. The condition goes in round brackets, and the code to run goes in curly braces:

if (cartTotal >= 499) {
  message = 'You get free delivery!';
}

If the condition is false, the whole block is skipped and the program continues after the closing brace. Always use the braces, even for one line. Leaving them out works for a single statement, but it is easy to add a second line later and wonder why it runs every time.

JavaScript if else and else if

Add else to run something when the condition is false. When there are more than two possibilities, chain extra tests with else if. JavaScript checks each condition in order and runs the first block whose condition is true; the rest are ignored. That is why the order of your tests matters – put the most specific or highest values first.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Grades</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <p id="out"></p>

  <script>
const studentName = 'Karthik';
const marks = 72;   // change this and run again
let grade;

if (marks >= 90) {
  grade = 'A+';
} else if (marks >= 75) {
  grade = 'A';
} else if (marks >= 60) {
  grade = 'B';
} else if (marks >= 35) {
  grade = 'C';
} else {
  grade = 'Fail – try again';
}

document.getElementById('out').textContent =
  `${studentName} scored ${marks} marks. Grade: ${grade}`;
  </script>
</body>
</html>

Notice that the second test only says marks >= 75. We do not need marks < 90 as well, because if marks were 90 or more, the first block would already have run and the chain would have stopped.

Truthy and falsy values

The condition inside if ( ) does not have to be a boolean. JavaScript converts whatever you give it to true or false. Only a handful of values count as falsy:

  • false, 0, -0 and 0n
  • '' (an empty string)
  • null, undefined and NaN

Everything else is truthy – including '0', 'false', empty arrays [] and empty objects {}. This lets you write short checks such as if (username) { … } to test that a text field is not empty. Just remember that 0 is falsy: if zero is a valid value for you, compare explicitly with === 0 or check for null.

The switch statement

When you compare one value against many fixed options, a long else if chain becomes hard to read. switch is a tidier choice. It compares the value with each case using strict equality (===), runs the matching block, and break stops it there. default handles anything that did not match.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Switch</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <p id="out"></p>

  <script>
const day = new Date().getDay();   // 0 = Sunday … 6 = Saturday
let plan;

switch (day) {
  case 0:
    plan = 'Sunday: family lunch and rest.';
    break;
  case 6:
    plan = 'Saturday: market and movie.';
    break;
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    plan = 'Weekday: office and evening walk.';
    break;
  default:
    plan = 'Unknown day!';
}

document.getElementById('out').textContent = plan;
  </script>
</body>
</html>

Cases 1 to 5 are stacked on purpose: they share one block. This deliberate “fall-through” is the only time you should leave out break.

Watch out: Forgetting break by accident is the most common switch bug. Without it, JavaScript keeps running the code of the following cases too, until it reaches a break or the end of the switch.

The ternary operator

For a simple either-or choice that produces a value, the conditional (ternary) operator is compact: condition ? valueIfTrue : valueIfFalse. It is ideal for short labels and messages.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ternary</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <p id="stock"></p>
  <p id="greet"></p>

  <script>
const unitsLeft = 0;
const hour = new Date().getHours();

const stockLabel = unitsLeft > 0 ? 'In stock' : 'Out of stock';
const greeting = hour < 12 ? 'Good morning' : 'Good evening';

document.getElementById('stock').textContent = stockLabel;
document.getElementById('greet').textContent = `${greeting}, Meena!`;
  </script>
</body>
</html>

Tip: Avoid nesting ternaries inside ternaries. If you need more than two outcomes, an if … else if chain or a switch will be far easier to read.

Choosing the right tool

SituationBest choice
Run code only when something is trueif
Two outcomesif … else, or a ternary when you just need a value
Ranges such as marks or pricesif … else if … else
One value against many exact optionsswitch

Conditions become even more powerful when combined with repetition. In the next lesson, JavaScript Loops, you will run code many times and use if inside the loop to handle each item differently.

Further reading

Key takeaways

  • if runs a block only when its condition is true; else handles the false case.
  • else if chains are checked in order and stop at the first true condition.
  • Falsy values: false, 0, -0, 0n, '', null, undefined and NaN – everything else is truthy.
  • switch compares one value with many cases using ===; remember break.
  • condition ? a : b is a compact way to choose between two values.

Quick quiz

Check what you learned – pick an answer.

1. Which of these values is truthy?

2. What happens if you forget break at the end of a matching case?

3. What does age >= 18 ? 'Adult' : 'Minor' return when age is 18?

Practice exercise

Write a delivery charge calculator. If the cart total is Rs. 499 or more, delivery is free; if it is Rs. 200 or more, delivery costs Rs. 40; otherwise it costs Rs. 60. Show the cart total, the delivery charge and the amount to pay on the page.

Show a hint

Use an if … else if … else chain and test the highest value first.

Show the solution
<p id="out"></p>
<script>
  const cartTotal = 350;
  let delivery;

  if (cartTotal >= 499) {
    delivery = 0;
  } else if (cartTotal >= 200) {
    delivery = 40;
  } else {
    delivery = 60;
  }

  document.getElementById('out').textContent =
    `Cart: Rs. ${cartTotal}, delivery: Rs. ${delivery}, to pay: Rs. ${cartTotal + delivery}`;
</script>

Progress is saved in this browser only.