Skip to content

Alternative of multiple if else in JavaScript | Code

  • by

Use an object as a map or Switch statement Alternative of multiple if else in JavaScript.

Switch alternative of multiple if else in JavaScript

Simple example code using object as a map:.

<!DOCTYPE html>
<html>
<body>
  <script>
   function getCode(input) {
    var inputMap = {
      "Corporation": "534",
      "LLC": "535",
      "LLP": "536",
      "Partnership": "537",
      "Sole Proprietorship": "538",
      "Limited Partnership": "539"
    };

    var defaultCode = "540";
    
    return inputMap[input] || defaultCode;
  }

  console.log(getCode("LLP"));
  console.log(getCode("Lorem Ipsum"));

</script>

</body>
</html>

Output:

Alternative of multiple if else in JavaScript

Use the switch statement, which is better for times when there is a single variable you want to check against multiple possible values:

<script>
   function fruitColor(fruit) {

    switch(fruit) {

      case "apple" :
      return 'green';
      break;

      case "banana" :
      return 'yellow';
      break;

      case "kiwi" :
      return 'green'
      break;

      case "plum" :
      return 'red';
      break;
    }
  }

  var result = fruitColor("plum");
  console.log(result);

</script>

A switch combined with if/else

word = 'd';
switch (res.distance) {
    case 0:
        word = 'a';
        break;
    case 1:
        if (res.difference > 3) {
            word = 'b';
        }
        break;
    case 2:
        if (res.difference > 5 && String(res.key).length > 5) {
            word = 'c';
        }
        break;
}

Do comment if you have any doubts or suggestions on this JS if-else 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading