Switch statement in Javascript

Sometime we will use the Switch statement in Javascript to replace the if else statement because it is shorter. The switch statement will take in a string or a number and then compares it with each case within the switch block and if it found the match then it will run the command under that case or else if nothing has been found then the default statement will be called. The break statement under each case indicates the end of a particular switch case which means the javascript program will continue on the next statement after the Switch block.

Below program will show you the operation of the switch statement.

 * Switch statement in action

var a = 1;

switch (a)
   case 1 : console.log("That is the one!");

   case 2: console.log("That is the two!");

   default:  console.log("undefined!");

Since a == 1 the line “That is the one!” will get printed on the console.

Leave a Reply

Be the First to Comment!

Notify of