var number = 15
if(number < 5) {
console.log(‘Your number is between 0 and 4’);
} else if(number < 10) {
console.log(‘Your number is between 5 than 9’);
} else if(number < 15) {
console.log(‘Your number is between 10 than 14’);
} else {
console.log(‘Your number is over 15’);
}
As you can see in the above code, we have chained multiple if else statements together to form a flow. Imagine this piece of code like a waterfall, which runs from the top down. It first checks the first if statement; if the condition is met, it will run the code inside the curly braces, and then the execution of the if statement as a whole will stop and move on to the next section of your code; however, if the first statement is not true, it will not execute that first block of code, instead it will fall down to the next else if statement, and check that condition to see if it’s true. If it is, then that code gets executed. If not, once again it falls down to the next if else. It continues this flow all the way through the if statement until it either finds a condition that is true, reaches an else statement or reaches the end of the statement entirely (in which case nothing will happen and JavaScript will just move on to the next statement).
Looking at the above code, can you have a guess which piece of code will be executed, and what will be logged to the console? Feel free to create this exact scenario in your browser to test this out yourself. Did you guess right? The correct answer is ‘Your number is 15 or over’. This is because, as we work our way through the if statement, none of the if or else if statements render true. The closest one to being true is the final else if (number < 15), but our number is 15, so it’s not less than 15, it’s equal to 15, therefore none of the if statements run, instead the else statement runs, logging ‘Your number is 15 or over’ to the console.
If statements, when combined with else if and else statements allow us complete control and flexibility over our code and how it runs. We can control every possibility, as long as we code for it.
The slight problem with the if statement and all of its corresponding else if statements, is that when we have a large number of different conditions that we need to consider, the code can get quite messy and unruly. This makes debugging hard as it’s not always easy to decipher exactly what is going on. For situations with a small number of outcomes, an if statement is perfect. However, for more complex queries, we need something a little bit more adept at handling multiple cases. For this, we need the switch statement.
This conditional statement is perfect for situations where we have a large number of different actions that should be performed based on different conditions being met. The switch statement has different syntax to anything we have seen before. It can seem a little strange at first, so let’s waste no time in getting familiar with it. Let’s see some code: