Tutorials / JavaScript Fundamentals / Conditionals: if, else and switch

Conditionals: if, else and switch

13 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

Programs need to choose

Up to now our code ran from top to bottom, one line after another. Real programs need to make choices. Show the login form or the dashboard. Charge shipping or not. A conditional runs a block of code only when a condition is true.

if, else if and else

function describeTemperature(celsius) {
  if (celsius >= 35) {
    return "very hot";
  } else if (celsius >= 25) {
    return "warm";
  } else if (celsius >= 15) {
    return "mild";
  } else {
    return "cold";
  }
}

console.log(describeTemperature(40)); // very hot
console.log(describeTemperature(28)); // warm
console.log(describeTemperature(10)); // cold

JavaScript checks the conditions from top to bottom. The first one that is true wins, its block runs, and the rest are skipped. That is why the order matters. If we had put celsius >= 15 first, 40 degrees would be called "mild".

The final else is optional. It catches everything that did not match above.

Curly braces are technically optional for a one-line body, but I always write them. Code without braces is a common source of bugs when someone adds a second line later and assumes it belongs to the if.

Conditions can be any expression

The condition inside the brackets is turned into a boolean. As we saw in the types lesson, these values count as false: false, 0, "", null, undefined and NaN. Everything else counts as true.

const name = "";

if (name) {
  console.log("Hello, " + name);
} else {
  console.log("Please enter your name");
}

This is called a truthy or falsy check. It is short and common, but it fails when 0 is a valid value:

const items = 0;

if (items) {
  console.log("You have items");
} else {
  console.log("Basket is empty"); // correct here
}

const rating = 0;
if (rating) {
  console.log("Rated");
} else {
  console.log("Not rated"); // wrong, 0 is a real rating
}

When zero or an empty string is a legal value, compare explicitly: if (rating !== undefined).

Combining conditions

Use &&, || and ! to build bigger conditions.

const age = 22;
const hasId = true;

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

const day = "Sunday";
if (day === "Saturday" || day === "Sunday") {
  console.log("Weekend");
}

If a condition grows past two or three parts, put pieces into named variables:

const isAdult = age >= 18;
const canEnter = isAdult && hasId;
if (canEnter) { /* ... */ }

That reads like English and is far easier to debug.

Early return

Deep nesting makes code hard to follow. A trick I use all the time is to deal with the bad cases first and return early.

function shippingCost(total, country) {
  if (total <= 0) return 0;
  if (country !== "PK") return 2500;
  if (total >= 5000) return 0;
  return 300;
}

console.log(shippingCost(6000, "PK")); // 0
console.log(shippingCost(1200, "PK")); // 300
console.log(shippingCost(1200, "AE")); // 2500

Each line handles one rule and exits. There is no pyramid of nested braces.

switch

When you compare one value against many fixed options, switch can be tidier:

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("Monday"));   // weekday

switch uses strict comparison (===). Two cases stacked with no code between them, like Saturday and Sunday, share one result. The default runs when nothing matches.

If you do not use return inside each case, you must end it with break. Without it, JavaScript "falls through" and runs the next case as well, which is almost never what you want:

switch (1) {
  case 1:
    console.log("one");
    break;
  case 2:
    console.log("two");
    break;
}

For a small number of branches, if and else if is fine. I use switch when I have four or more fixed values.

Common mistakes

  • Writing = instead of ===. if (score = 10) assigns and always passes. Your editor often warns about this.
  • Wrong order of checks. Put the most specific condition first.
  • Truthy checks on zero. Be explicit when 0 or an empty string is valid.
  • Forgetting break in switch. The next case runs too.
  • Comparing strings of different case. "yes" === "Yes" is false. Normalise with toLowerCase() first.

Try it yourself

  1. Write a function grade(score) that returns "A" for 80 and above, "B" for 70 to 79, "C" for 60 to 69 and "Fail" below that.
  2. Write a check that prints "leap year" when a year is divisible by 4, except for years divisible by 100 unless they are also divisible by 400. Test with 1900, 2000 and 2024.
  3. Rewrite dayType with if statements and compare which version reads better to you.
  4. Make a function that takes "red", "yellow" or "green" and returns what a driver should do.
javascript
function describeTemperature(celsius) {
  if (celsius >= 35) {
    return "very hot";
  } else if (celsius >= 25) {
    return "warm";
  } else if (celsius >= 15) {
    return "mild";
  } else {
    return "cold";
  }
}

console.log(describeTemperature(40)); // very hot
console.log(describeTemperature(28)); // warm
console.log(describeTemperature(10)); // cold

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account