Question:
In what scenarios should one use if..else statements and in what scenarios should one switch statements in JavaScript?
Any help will be appreciated.
Happy Coding
For further actions, you may consider blocking this person and/or reporting abuse
Mike Young -
Ashish prajapati -
Vaibhav Dwivedi -
Mike Young -
Top comments (1)
By it's nature switch only compares the value of a single variable.
Generally a switch works best when comparing the value/state of a single variable against a known set of possibilities. Think of incoming keystroke and you want to act differently depending on what key is pressed. A switch here makes much more sense than multiple if/else.
If you are comparing different variables - rather than one single, maybe also using functions as conditions, a switch statement would not be appropriate at all - if even possible.
Sample pseudo code for a login to validate username and password.
I generally consider a lot of trailing
if else
as bad practice and try to solve things with a different approach, depending on situation. I think it is pain to maintain, can be hard to follow and bug prone. A switch statement however are usually pretty straight forward, just avoid magic numbers/strings and use constants, enums or similar instead.Happy coding!