How could I convert this code to a switch?

Activity Link: https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/code-challenge-javascript-fundamentals/lessons/javascript-fundamentals-code-challenge/exercises/life-phase

Here’s the code I made as a bunch of if statements, but originally wanted to make it a switch. Can anyone help on how I would do so? See code below.

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

i wouldn’t convert this to switch

what i would do is: first check that input is valid (age < 0 || age > 140 and possible if its an integer? )

then a bunch of else if statement check age is lesser then. No need to do the greater then you currently have.

Okay, thanks. What was the primary reason that you would not recommend this as a switch?

Also, wouldn’t the ‘less than age’ create the possibilities of multiple age ID’s? In other words someone who is 18 could qualify as a ‘teen’, and ‘adult’. Still a noob, so not sure if I am missing an order of operations thing here.

Thanks for taking time to answer my question.

-bahr322

switch is useful when you have a few options, here there are a lot of options (139 cases)

no, if you do:

else if (age <= 19){return 'teen'}
else if (age <= 64){return 'adult'}

someone is 18 will always give teen. Two reasons, once a condition evaluates to true, the remaining conditions are skipped

furthermore, by default a function return None at the end of the function (implicit), if we want to return something else at the end of the function, we can use the return keyword. So once the return is reached, the function ends

so things like age >= 4 are pretty redundant.

Thanks, you rock. I did know that, but forgot that it would terminate once true. Thanks for the help!!