JavaScript multiple if statements not Good | Alternative Switch Case

Using multiple if statements or if else statements, look very bulky in JavaScript or other programming languages.

Multiple if statements and then else JavaScript Example

If condition matches then inside code execute of if and else. But if the condition matched the last if statement then else will not be executed.

<!DOCTYPE html>
<html>
<head>
    <body>

        <script type="text/javascript">

            var a = 0;

            if (a == 0) {
                console.log("Green");
            }
            if (a == 1) {
                console.log("Yellow");
            }
            if (a == 2) {
                console.log("Red");
            }
            if (a == 3 ) {
                console.log("Blue");
            } else {
                console.log("None");
            }

        </script>
    </body>
</html>

Output:

An alternative to multiple if-else statements in JavaScript?

if-else Multiple

A much better solution is if-else compare to if multiple and last else condition statement. Else will be executed only if all conditions false.

<!DOCTYPE html>
<html>
<head>
    <body>

        <script type="text/javascript">

            var a = 0;

            if (a == 0) {
                console.log("Green");
            }
            else if (a == 1) {
                console.log("Yellow");
            }
            else if (a == 2) {
                console.log("Red");
            }
            else if (a == 3 ) {
                console.log("Blue");
            } else {
                console.log("None");
            }

        </script>
    </body>
</html>

Output: This time output only “Green”.

multiple if-else statements in JavaScript

Switch Case (Alternative)

Switch statements are the most obvious substitute for if statements.

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

<!DOCTYPE html>
<html>
<head>
    <body>

        <script type="text/javascript">
            var a = 1;
            switch (a) {
              case 0 :
              console.log("Green");
              break;
              case 1:
              console.log("Yellow");
              break;
              case 2:
              console.log("Red");
              break;
              case 3:
              console.log("Blue");
              break;
              default:
              console.log("None");
              break;
          }

      </script>
  </body>
  </html>

Output:

Switch alternative of multiple if-else statements in JavaScript

Do comment if you have any doubts and suggestion on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

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