Tech Junkie Blog: JavaScript : The switch Statement

Friday, April 14, 2017

JavaScript : The switch Statement

The switch statement is there to make the code more readable if the if statements contains too many branches and becomes too hard to read.

Consider the code below

var x = 6;

if (x === 1)
{
     console.log("one");
}
else if (x === 2)
{
     console.log("two");
}
else if (x === 3)
{
     console.log("three");
}
else if (x === 4)
{
     console.log("four");
}
else if (x === 5)
{
     console.log("five");
}
else
{
     console.log("x is not 1-5");
}



As you can see the code is pretty hard to read, but if you convert it to a switch statement it becomes more readable.  Here is the code rewritten

var x = 6;

switch(x) {
    case 1 :
       console.log("one");
      break;
    case 2 :
       console.log("two");
      break;
    case 3:
       console.log("three");
      break;
    case 4:
       console.log("four");
      break;
    case 5:
       console.log("five");
      break;
   default:
        console.log("x is not 1-5");
        break;
}

The switch statement above is the same as the if statement above, but it's a lot cleaner to look at.  Each case is equivalent to an if or else if branch and the break keyword tells JavaScript to stop execution after a case has been met.  If you don't have the break for each case then you have what is called a cascading switch statement meaning the cases will execute until a break is encountered. Similarly the default label tells the switch statement to execute the default case if none of the other cases are met.

Both codes will produce the same output:








The syntax for a switch statement is

switch(expression) {
     case statements
}

The matching case of the switch expression uses the === equality not the == equality.  Meaning the expression must match without any type conversion.


No comments:

Post a Comment