var number = 15;
switch(number) {
case 5:
console.log(‘number is 5’);
break;
case 10:
console.log(‘number is 10’);
break;
case 15:
console.log(‘number is 15’);
}
Looking at the above code, there’s a lot of new syntax to analyse here, so let’s work our way from top to bottom.
During execution of the code, JavaScript will handle the switch statement very much like an if else statement. It will look for a single valid condition that returns TRUE, execute that code, then move on to the next section of your code outside of the statement.
You will notice that the final case in the switch statement doesn’t contain a break. This is because the code will stop here anyway, as this is not a loop, and as soon as JavaScript has worked its way through your statement, it will move on, even if it doesn’t find a match.
In the current state of our switch statement, it is entirely possible for there to be no matches, and therefore no code is executed. If we want to emulate the else functionality of an if statement, and mitigate against a situation where no matches are found, we can make use of the default keyword. The default keyword is largely identical to the else section of an if statement, in that it is run if no other match is found.
To use the default keyword, we simply add it into our switch statement, like so: