Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript : The switch Statement

Friday, November 26, 2021

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.





1 comment:

  1. JavaScript's switch statement is an effective tool for handling several circumstances in a clear and understandable manner. Switch can help you reduce intricate if-else chains and improve the maintainability of your code. In a switch statement, every case is compared to the expression until a match is discovered, at which point the relevant block of code is executed. The switch statement is an invaluable tool for any JavaScript developer, whether you're processing user inputs or managing state changes. It's especially helpful if you're seeking for the best online exam help to help you learn difficult programming topics.

    ReplyDelete

Search This Blog