Codecademy Forums

FAQ: Code Challenges: JavaScript Fundamentals - lifePhase()

Thank you so much! This saves me hours

1 Like

I’m late to the party, but thank you for this example! I’d been pulling out my hair over why my switch statement wouldn’t work – I was putting the age variable in the parentheses instead of comparing each statement to true.

1 Like

Could you explain how this code works? From my understanding because you have the ‘if’ statement first stating that the ‘invalid’ message should be returned if the input value is < 0 or > 140 but I don’t quite understand the rest. Is there an implicit ‘else if’ statement? What do the question marks do?

I also tried this code and it works but code academy didn’t seem to like it as a solution and kept telling me that there should be an invalid message when the value was < 0. I did get the invalid message but for some reason it still wasn’t working!

function life_cycle(age) {
  if (age < 0 || age > 140) {
    return "This is not a valid age.";
  }
  return age < 3  ? 'baby' :
         age < 13 ? 'child' :
         age < 20 ? 'teen' :
         age < 65 ? 'adult' :
         age < 75 ? 'senior' : 'elderly';
}

The above is known as a multiple condition ternary expression, much like an if..else if..else statement.

condition ? value when true : default value
          ^                 ^
       operator         separator

compared to,

if condition:
    # value when true
else:
    # default value

Note that in the above multiple ternary there is a value in the true place, and another condition in the default place. This is called nesting, or chaining.

It’s a tricky technique to master and most teachers will advise against it for reading and maintaining, but it bears demonstrating, all the same. There is good reason why the SCT won’t accept the solution… It may not have been taught yet, and most teachers would say it is too complex.

1 Like

Not to beleaguer the point, but to draw it out…

if (age < 3) { return 'baby' }
else if (age < 13) { return 'child' }
else if (age < 20) { return 'teen' }
else if (age < 65) { return 'adult' }
else if (age < 75) { return 'senior' }
else  { return 'elderly' }

My position would be to favor the expression over the control flow construct. It is readable, and it is maintainable. The language gives us the abstraction to use, not to shy away from.

  return age < 3  ? 'baby' :
         age < 13 ? 'child' :
         age < 20 ? 'teen' :
         age < 65 ? 'adult' :
         age < 75 ? 'senior' : 'elderly';

says it all.