Skip to content

Switch case with if condition in JavaScript | Example code

  • by

The switch statement evaluated value of the switch expression is compared to the evaluated values of the cases. You can nest if condition with the Switch case in JavaScript.

switch(foo) {
    case 'bar':
    if(raz == 'something') {
        // execute
    } else {
        // do something else
    }
    break;
    ...
    default:
    // yada yada
}

The expression inside the switch case statement

switch (true) {
  case (amount >= 7500 && amount < 10000):
    // Code
    break;
  case (amount >= 10000 && amount < 15000):
    // Code
    break;
  // etc.
}

Switch case with if condition in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var foo = "bar"
    var raz = "Hello"

    switch(foo) {

      case 'bar':
      if(raz == 'Hello') {
       console.log("Result");
     } else {
      console.log("nothing");
    }
    break;

    default:
    console.log("XYZ");
  }

</script>

</body>
</html
>

Output:

Switch case with if condition in JavaScript

switch case with conditions?

var cnt = $("#div1 p").length;
alert(cnt);

switch (cnt) {
  case (cnt >= 10 && cnt <= 20):
    alert('10');
    break;
  case (cnt >= 21 && cnt <= 30):
    alert('21');
    break;
  case (cnt >= 31 && cnt <= 40):
    alert('31');
    break;
  default:
    alert('>41');
}

You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;

alert(cnt);

if (cnt >= 10 && cnt <= 20)
{
   alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
   alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
   alert('31');
}
else 
{
   alert('>41');
}

Do comment if you have any doubts or suggestions on this JS switch case topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.