Why my code outputs an undefined

function lifePhase(age) {

switch(age) {

case age < 3: return ‘baby’;

break;

case age < 12: return ‘child’;

break;

case age < 19: return ‘teen’;

break;

case age < 64: return ‘adult’;

break;

case age < 140: return ‘senior citizen’;

break;

case age < 0:

return ‘This is not a valid age’;

break;

case age > 140:

return ‘This is not a valid age’;

break;

}

}

console.log(lifePhase(5));

You’ll need to make a few changes to your switch statement for this to work.

Things to keep in mind:

  • A switch statement requires a default case
  • There’s no need for break; if you’re using a return. Nothing after return will be reached.

Then, you’re getting undefined because your switch condition, age, is a number. The switch won’t be able to compare a number against a comparison statement (e.g. age < 3).

It would work if you did

function lifePhase(age) {
  switch(age) {
    case 3:
      return 'baby';
    default:
      return 'error';
  }
}

console.log(lifePhase(3)); // outputs baby

One way to solve this is to use a truthy boolean for the switch condition. true would work.