Switch Case Statement in JavaScript

January 29, 2025 1 Comment » Hits : 435





Switch Case Statement in JavaScript

  1. We can use conditional statements to execute different block of statements based on condition.
  2. Switch Case statement is used for selection of cases based on user input or current situation.
  3. Switch Case Syntax is similar to that of “Java/C/C++“.
switch(num)
{
case 1:
  Execute This Code Block 1
  break;
case 2:
  Execute This Code Block 2
  break;
default:
  Execute This Code Block if num!=1 and num!=2
}

Explanation :

  1. Let’s Assume user have assigned “1″ to variable num , then JS will compare num with Case number .
  2. If case number and value of Variable are equal then Code inside block will be executed.
  3. break statement is used to take control outside switch case. (in short break statement terminates switch case).
  4. Use break to prevent the code from running into the next case automatically.
  5. If variable is not equal to first case then it will compare value with next case number.
  6. If none of the case

Live Example :

<html>
<body>
<script type="text/javascript">
var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 5:
  document.write("<b>Finally Friday</b>");
  break;
case 6:
  document.write("<b>Super Saturday</b>");
  break;
case 0:
  document.write("<b>Weekend Sunday</b>");
  break;
default:
  document.write("<b>Again work !!!</b>");
}
</script>
</body>
</html>

Output

Weekend Sunday

Some Pretty Rules of Switch Case Statements

Rule 1 : Use of Comma Operator

switch (theDay)
{
case 5,1,4:
  document.write("<b>Finally Friday</b>");
  break;
case 1,2,6:
  document.write("<b>Super Saturday</b>");
  break;
case 4,5,0:
  document.write("<b>Weekend Sunday</b>");
  break;
default:
  document.write("<b>Again work !!!</b>");
}

Output :

Weekend Sunday

Explanation :

  1. Comma Operator returns rightmost value.
  2. Means case 1,2,3 is equivalent to case 3.

Rule 2 : Single Block is used for different Cases

switch (theDay)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
  document.write("<b>Weekdays</b>");
  break;
case 0:
  document.write("<b>Sunday</b>");
  break;
default:
  document.write("<b>Default</b>");
}

As break is not written after cases , Value of “theDay” if falls between 1-6 then “Weekdays” gets printed.

Incoming search terms:

  • http://learnwebdevelopment.info Coder

    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles.you can refer here to know more about .