I want to know when can use switch() instead of else if


#1

Hello, everyone,

I have a question, when I am doing the “code challenges”, lifePhase(), Can I use switch() instead of else if? I tried, but didn’t work out , didn’t know that if it didn’t work out or something I did wrong? thank you.

const lifePhase = age => {
if (age < 0 || age > 140) {
return ‘This is not a valid age’
} else if (age < 4) {
return ‘baby’
} else if (age < 13) {
return ‘child’
} else if (age < 20) {
return ‘teen’
} else if (age < 65) {
return ‘adult’
} else {
return ‘senior citizen’
}
}


#2

When I first see your question, I said “oh, yes, of course you can use switch statement”. However, it was not that easy, I think you found a very good question. Here is what I have found:

You can use switch statement for this, but you should change the syntax a little bit to make it work. First of all, here is a discussion on using return keyword : return keyword in switch statement

Second of all, to be able to use logical operators in switch statement, you should change the syntax, which was not in the Codecademy lessons, I think… And thanks for making me find this out. Thankfully, the answer was already provided in Codecademy website, here : logical operators in switch statement

And, lastly, here is the workin version of your code in switch statement:

let lifePhase = 20
switch (true) {
  case (lifePhase < 0):
    console.log('This is not a valid age');
    break;
  case (lifePhase > 140):
    console.log ('This is not a valid age');
    break;
  case (lifePhase < 4):
    console.log ('baby');
    break;
  case (lifePhase < 13):
    console.log ('child');
    break;
  case (lifePhase < 20):
    console.log ('teen');
    break;
  case (lifePhase < 65):
    console.log ('adult');
    break;
  case (lifePhase > 65):
    console.log ('senior citizen');
    break;  
  default :
    console.log ('Error')
}

// expected result is 'adult' printed on console

Note: if you want to use return keyword to get the result returned instead of logged into console, check the first link I have given about return keyword.