How could I use a switch statement for this lesson?

Not everyone is in agreement about the use of ternary expressions, favoring instead if..else if..else for its literalness. The jury is still out for me, but I don’t work in a production environment or collaboratively. There is good reason to have and to follow an organization’s style guide since it promotes uniformity and consistency.

There’s always an exception to every rule, so don’t rule this approach out, entirely, just know how to keep in step with your fellow collaborators.

Thanks for the clarification. I try to use both so as to get familiar with them, but it’s often confusing to learn this way.


If you change the expression on case age < 0 to:

case age < 0: return “This is not a valid age.”;

It will function as expected and keeps on its elegance.


Sure, while it still adds the 140 limit to the code load down the road.

Great piece of code. I love it, thanks for sharing.

1 Like

I made something similar:

function lifePhase(age) {

if (age < 0 || age > 140) {

return "This is not a valid age.";


return age < 4 ? ‘baby’ :

     age < 13 ? 'child' :

     age < 20 ? 'teen' :

     age < 65 ? 'adult' :

     64 < age < 141 > 'senior citizen';



I see In mentioned case we are able to do both switch and if/else statement but who is better? there must be some way to find out which program is lighter to run?

One cannot say which method benchmarks better. switch is useful when there are several cases, though if..else if..else is more the norm. ‘Better’ is a subjective term.

I compare a switch to an object where each case is a key and its value is the assignment action. The object does all the heavy lifting without using any conditional logic.

Bottom line, be comfortable with both forms of control flow and know how to use them. Eventually you will arrive at what is a best fit for you.


Why aren’t you using “breaks” in this example? I’m generally confused what it’s purpose is and when it’s necessary or not.

My assumption was that you SHOULD use “breaks” to make sure the other cases wouldn’t run and thus give you several results if the age was say 64… in order to prevent your console from printing: “teen adult senior elderly”

Because we use return which is the same thing. break exits the switch body. return exits the function body.

FTR that example is flawed. See further down the topic for the revised, corrected version.

16 posts were split to a new topic: How could I use a switch statement for this lesson?