DEV Community

Cover image for JAVASCRIPT FUNDAMENTALS
Winnie Magoma
Winnie Magoma

Posted on

JAVASCRIPT FUNDAMENTALS

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

Top comments (1)

Collapse
 
sebring profile image
J. G. Sebring • Edited

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.

switch(key.value) {
 case 'a':
  // do something...
  break
 case 'b':
  // do something else...
  break
 // etc
}

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.

signup(username, password) {
 let errorMessage = ''
 if (username.length < 3 && username.length > 12)
  errorMessage = `Username must be at least 4 chars long but no longer than 12.`
 else if (isUsernameTaken(username)) 
  errorMessage = `Username is already taken.`
 else if (isPasswordTooWeak(password))
  errorMessage = `Password must bla bla`

 if (errorMessage)
  alert(errorMessage)
 else
  createUser(user, 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!