Shehu-Hikmah

Shehu-Hikmah

The JavaScript switch Statement

The JavaScript switch Statement

Subscribe to my newsletter and never miss my upcoming articles

The JavaScript switch statement is one of the logical decision making conditional statements (like the for loop, while loop) that allows you to switch between segments of code based on the evaluated value of a variables or expressions that matches certain conditions.

It is evaluated once; once it is triggered it will compare the value of the expression to available values of each case associated with conditions to find match and execute the block of code found.

Below is a switch statement syntax:

switch( expression ) {
case aValue:
// Code to execute if expression == aValue;
break; // End execution
case anotherValue:
// Code to execute if expression == anotherValue;
break; // End execution
case thisIsAnotherValue:
// Code to execute if expression == thisIsAnotherValue;
break; // End execution
default:
// Code to execute if no values matched
}

From the above syntax, JavaScript evaluates the switch(expression) and then compares it to the value of each case[starting from aValue, anotherValue to thisIsAnotherValue ] sequentially. Once a match is established, the block of code starts executing at that point and continues through all the case statements until a statement break is found. The default case is an alternative case which will execute if none of the case statements match. This is a useful tool for tracking errors, where, for instance, when you expect a match to occur but a bug averts that from happening.

THE BREAK KEYWORD

The break Keyword serves as end point or stoppage of block of code execution once it is written after the case. The break; keyword signify to the JavaScript interpreter to stop evaluation and start evaluating the proceeding cases (values that follows) we have demonstrate that in the examples that follows below.

THE DEFAULT KEYWORD

This is an alternative value that the switch (expression) execute when there's no matching values between the cases after evaluation.

This could be handy to catch up with bug or certain errors in the block of code that stops them from been executed. Switch statement case values can be of any data type, it could be numbers, strings, arrays etc. You can include just one case or as many cases as you possible. Let’s look example below:

<html>
<body>
    <p id="p1"></p>
<script type="text/javascript">
// this Stores the number use in the variable userNumber
var userNumber = Number( prompt( "Enter a an odd number between 0 and 10", "" ) );
// the variable oddNumber holds the strings to the DOM on the paragraph above 
var oddNumber;
switch( userNumber ) {
// If userNumber is 1, write out and carry on
// executing after case statement
    case 1:
    oddNumber= "The odd number you entered is Number 1" ;
        break;
    case 3:
    oddNumber=  "The odd number you entered is Number 3" ;
        break;
    case 5:
    oddNumber=  "The odd number you entered is Number 5" ;
        break;
    case 7:
        oddNumber=  "The odd number you entered is Number 7" ;
        break;
    case 9:
        oddNumber=  "The odd number you entered is Number 9" ;
        break;
    default:
        oddNumber=  "Please enter a an odd number between 0 and 10.";
        break;
}
document.getElementById("p1").innerHTML =  oddNumber;
// Code continues executing here
</script>
</body>
</html>

If you try it out (you can check out through here ). You should just get the the following response The odd number you entered is (the you’ve entered 1,3,5,7 and 9) written out or otherwise, this sentence “Please enter an odd number between 0 and 10.” From the examples, you can deduce the importance of the break statement. If you don’t include break after each case, execution carries on within the block until the end of the switch. Try removing the breaks and then enter 1 then observed the behavior of the code execution. Another possibility the JavaScript statement offers us is that we can nest multiple case with the value (block of codes to be executed). In the example below we grouped the 12 months of the year in 4 different seasons of the year which is winter, spring, summer and autumn. Each first three cases [0-2], case [3-5] respectively holds the same value. Below is the code;

<html>
<body>
    <p id="p1"></p>
<script type="text/javascript">
// The variable months stores the months in the Date.getMonth() method.
var months = new Date().getMonth();
// The variable seasonOfTheYear holds the season of the year according to the season that matches the switch evaluation.
var seasonOfTheYear;
switch (months) {
    // Case 0 to case 2 hold thesame season winter which is January, February and March.
    case 0:
    case 1:
    case 2:
        seasonOfTheYear= " The season is Winter";
        break;
    //Case 3 to case 5 hold thesame season Spring which is April, May and June.
    case 3:
    case 4:
    case 5:
        seasonOfTheYear= " The season is Spring";
        break;
    // Case 6 to 8 hold thesame season Summer July, August and September.
    case 6:
    case 7:
    case 8:
        seasonOfTheYear= " The season is Summer";
        break;
    // Case 9 to case 11 hold thesame season Autumn October, November and December
    case 9:
    case 10:
    case 11:
        seasonOfTheYear= " The season is Autumn";
        break;
    default:
        seasonOfTheYear= "Something went wrong.";
    }
document.getElementById("p1").innerHTML =  seasonOfTheYear;
</script>
</body>
</html>

Try it out here

If you tried this out it will print out to your screen the season of the year

 
Share this