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. error404-store




    - -- Spamming tools --




    1-- cpanel https ssl secure
    2-- shell ssl secure
    3-- web-mail
    4-- smtp
    5-- rdp with send bluster
    6-- scam pages
    7-- ceo or cfo leads




    -- Spy virus slinet Exploits --




    1-- privet rat
    2-- crypter exploits
    3-- privet rdp hosting
    4-- os andriod spy virus
    5-- iso iPhone spy virus
    6-- Nokia spy virus




    - -- scanners brute-force ---




    1-- linux roots
    2-- cpanel scanner
    3-- cpanel bruter
    4-- shell scanner
    5-- smtp scanner
    6-- smtp bruter
    7-- zimbra scanners


    - -------------------


    cpanel,shell,smtp,scampages,sender,ceo or cfo leads,rdp,spyvirus,crypter,exploits,scanners


    Telegram:- @Donsmith000


    icq :- @Donsmith000


    https://error404-store.blogspot.com



    ReplyDelete

Search This Blog