30 Days Of JavaScript

Day 3: Logic

Lesson 5: If, Else if, Else

This is an awkwardly titled lesson! Let's build up an example to get us to it 😀

1let temperature = 8;
2
3if (temperature < 10) {
4  console.log("It's cold");
5} else {
6  console.log("It's not that cold");
7}

While it's true that 10 degrees C is a reasonable cut off for "cold" there's a whole lot more temperatures and feelings, let's expand it to be cold, comfortable, hot and very hot.

1let temperature = 8;
2
3if (temperature < 10) {
4  console.log("It's cold");
5}
6
7if (temperature >= 10 && temperature < 20) {
8  console.log("It's comfortable");
9}
10
11if (temperature >= 20 && temperature < 30) {
12  console.log("It's hot");
13}
14
15if (temperature >= 30) {
16  console.log("It's very hot");
17}

This works and is pretty clear but it has one annoyance. We have to specify the range in each temperature band and the if statements looks quite isolated from each other when in reality they are all related and only one is going to get executed.

To get rid of the range check though we would need to do this:

1let temperature = 8;
2if (temperature < 10) {
3  console.log("It's cold");
4} else {
5  if (temperature < 20) {
6    console.log("It's comfortable");
7  } else {
8    if (temperature < 30) {
9      console.log("It's hot");
10    } else {
11      console.log("It's very hot");
12    }
13  }
14}

This is pretty unreadable and we are only checking 4 temperature ranges. We've gotten rid of the range check and group the code together so that temperature is only checked until it meets a condition ... But it's horrible to read!

Thankfully we can improve this with else if

This is perfect, it's readable because it never indents more than one level and it has good performance because once a temperature condition is met the code stops executing the block and moves on to the next thing.

Exercise

In the playground below have a go at making an else if chain like this to say if someone is very short, short, middle, tall or very tall based on their height. It's up to you to decide what numbers to use for each height division.

One last thing

The Switch Statement

When else if chains get very long, many people will substitute them for a switch statement. Other people claim that switch statements shouldn't be used.

I personally don't like the switch statement syntax and prefer else if statements should I need a long conditional run like this.

To that end, I'm not going to cover switch statements in this course.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co