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.


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.

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.


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.