JavaScript - Switch Case




JavaScript - Switch Case

The switch case statement may trip up even the most seasoned JavaScript developer. I use this statement often, especially in my nodejs AWS Lambdas, where my business heavy logic resides. Like other curly braced, C based languages, your JavaScript can benefit from a switch statement. I wrote an article on the C# Switch statement, demonstrating some of the switch statement basics and features C# adds to the statement. Today I am sharing a similar article on how the switch statement works in JavaScript. Use the switch statement to execute one of many code blocks based on a variable or expression's value. The switch expression is evaluated once. The comparison value will match either a statement value or trigger a default code block.

Switch statement is used as an alternate to multiple if .. else statements. Switch statements are a more efficient way to code when testing multiple conditions. This case statement is used to execute various actions for various conditions or variable states, Use the Switch Case statement to pick a block of code to execute, The Switch statement uses strict comparisons (===), values must be the same type to match

You can use multiple if… else if statement, as in previous chapter, to perform a multi way branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Starting with JavaScript 1.2, you can use a SWITCH statement which handles exactly this situation, and it does so more efficiently than repeated if..else if statements.

Syntax

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found, if nothing matches, a default condition will be used.

Switch(expression)

{

case   condition 1 : statement(s)

break;

Case condition 2: statement(s)

break;

…

Case condition n: statement(s)

break;

default:  statement(s)

Break

Statements indicate to the interpreter the end of that particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases, We will explain break statement in LOOP Control chapter.

Example

Following example illustrates a basic while loop:
<script type=”text/javascript”>
<!—

var grade=’A’;

document.write(“Entering switch block <br/>”);

switch(grade)

{

case   ‘A’ : document.write(“Good job<br />”);

break;

Case   ‘B’ :doucument.write(“Pretty good  <br/>”);

break;

case    ‘C’: document.write(“Passed<br />”);

break;

Case    ‘D’ :document.write(“Not So good <br/>”);

break;

Case     ‘F’ :documenet.write(“Failed <br/>”);

break;

default :document.write(“Unknown grade<br/>”)

break;

}

document.write(“Existing switch block”);

//-- >

</script>

Example

Consider a case if you do not use break statement:
<script type=”text/javascript”>

<!—

var grade=’A’;

document.write(“Entering switch block<br/>”);

switch(grade)

{

Case ‘A’ :document.write(“Good job <br />”);

Case ‘B’ :document.write(“Pretty good <br />”);

Case ‘C’ :document.write(“Passed<br/>”);

Case ‘D’ :document.write(“Not So good <br />”);

Case ‘F’ :document.write(“Failed <br />”);

default: document.write(“Unknown grade<br/>”);

}

document.write(“Existing switch block”);

//-- >

</script>

What is an JavaScript Switch Case ?

The switch statement evaluates an expression, and executes a block of code based on which case the expression evaluated to.

const hero = 'Batman';
let sidekick;

switch (hero) {
  case 'Batman':
    sidekick = 'Robin';
    break;
  case 'Aquaman':
    sidekick = 'Aqualad';
    break;
  case 'Superman':
    sidekick = 'Jimmy Olsen';
    break;
  default:
    throw new Error('Unknown hero');
}

sidekick; // 'Robin'

Make sure you don't forget the break statement at the end of a block! If you don't put a break statement at the end of a case block, JavaScript will "fall through" to the next case.

const hero = 'Batman';
let sidekick;

switch (hero) {
  case 'Batman':
    sidekick = 'Robin';
    // Unless there's a `break`, JavaScript will execute the next
    // `case` block.
    // break;
  case 'Aquaman':
    sidekick = 'Aqualad';
    break;
  case 'Superman':
    sidekick = 'Jimmy Olsen';
    break;
  default:
    throw new Error('Unknown hero');
}

// JavaScript executed both the 'Batman' and 'Aquaman' blocks,
// so you get the wrong `sidekick`.
sidekick; // 'Aqualad'

There are some benefits to this behavior. You can execute one block for multiple case statements. For example -

const sidekick = 'Nightwing';
let hero;

switch (sidekick) {
  // The 'Robin' and 'Nightwing' cases are "fallthrough" `case`
  // statements. They execute the same code block as the 'Bluebird'
  // case.
  case 'Robin':
  case 'Nightwing':
  case 'Bluebird':
    hero = 'Batman';
    break;
  case 'Aqualad':
  case 'Tempest':
    hero = 'Aquaman';
    break;
  default:
    throw new Error('Unknown sidekick');
}

hero; // 'Batman'

JavaScript switch statement evaluates a switch condition, base on switch condition value matched case will run until break or end of case statement.

Syntax

switch (expression)
{
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}

Example

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case  6:
    day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

Output

Today is Saturday

What is JavaScript Switch Case Statement?

The JavaScript switch case statement is used for decision-making purposes. Using if-else statements for this purpose will be less efficient over switch case statements and also it will make the code look complex. the switch case in JavaScript is a multi-way branch statement.

Syntax

switch(expression) 
{
case value 1:
        statement1;
        break;
case value 2:
        statement2;
        break;
case value N;
        statementN;
        break;
default: statement default;

Execution Flow of Switch Cases Statement -

Example

let a = 2+ 2;
Switch (a) {
 Case 1:
    alert( “Too small”);
    Break;
Case 2:
    alert(“exactly”);
    Break;
Case 3:
    alert(“Too large”);
    Break;
Default:
alert(“I don’t know such values”);
}

Here, the switch starts to compare ‘a’ from first case variant that is 1. Then, the match fails. Then 2. That’s a match, so the execution starts from case 2 until the nearest break. If there is no break then the execution continues with the next case without any choice. Both switch and case allow arbitrary expressions.

Example

let a = “1”;
 Let b = “0”;
switch(+a) {
    case b+1:
      alert(“this runs”);
     break;
default:
    alert(“this doesn’t run”);
}