JavaScript Switch Case


JavaScript Switch Case

The switch statement runs a block of code based on the circumstances.

The switch statement is part of JavaScript's "Conditional" Statements, used to do various actions depending on certain conditions. Select one of the numerous code blocks to be performed using the switch. This is the ideal answer for long, nested if/else statements.

A switch statement's goal is to give an expression to evaluate and multiple different statements to execute depending on the expression's value. Until a match is found, the interpreter compares each case to the value of the expression. If no match is found, a default condition will be used.

Break statements denote the end of a specific scenario. If they were omitted in each of the following circumstances, the interpreter would proceed to execute each statement.

The following is how it works:

  • Only one time is the switch expression evaluated.
  • The expression's value is compared against the values in each circumstance.
  • If a match is found, the relevant code block is run.
  • If no match is found, the default code block is run.

A Close Examination

In switch circumstances, stringent comparison (===) is used. To match, the values must be of the same type. Only if the operands are of the same type may a rigorous comparison be made.

Example No.1:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> let 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:

Knowledge2life

Today is Wednesday

Example No.2:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> let text; switch (new Date().getDay()) { case 6: text = "Today is Saturday"; break; case 0: text = "Today is Sunday"; break; default: text = "Looking forward to the Weekend"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>

OUTPUT:

Knowledge2life

Looking forward to the Weekend