Switch keyword and function on CODE CHALLENGES: JAVASCRIPT FUNDAMENTALS (4/15)


#1

I don’t get why my function keeps returning undefined when I right like this, but works when I use if…if else statements! Am I using the switch keyword wrongly? Thanks a lot!

function lifePhase(age) {
  switch (age) {
    case age >= 0 && age<= 3:
      return 'baby'
      break;
    case age >= 4 && age <= 12:
      return 'child'
      break;
    case age >=13 && age <= 19:
      return 'teen'
      break;
    case age >= 20 && age <= 64:
      return 'adult'
      break;
    case age >= 65 && age <= 140:
      return 'senior citizen'
      break;
    case age <= 0 || age >= 140:
      return 'this is not a valid age'
      break;
  }
}
console.log(lifePhase(5))

Is there logic behind this?
#2

Switch statements usually use one check:

function lifePhase(age) {
    switch (age) {
        case age 1:
        break;
        // etc...
    }
}

I did some research and found that, to accomplish what you want to, you can do the following:

function lifePhase(age) {
    switch (true) {
        case age >= 0 && age<= 3:
        return 'baby';
        case age >= 4 && age <= 12:
        return 'child';
        case age >=13 && age <= 19:
        return 'teen';
        case age >= 20 && age <= 64:
        return 'adult';
        case age >= 65 && age <= 140:
        return 'senior citizen';
        default:
        return 'this is not a valid age';
    }
}
console.log(lifePhase(5))

Setting the switch variable to true seems to work.


#3

Interesting… Thank you a lot!!


#4

Given the top down flow of the switch, we can use the same type of order that we would for if..else if..if. and avoid the verbosity of logical expressions.

case age < 0: age = 141;    // set to fail all cases and reach the default
case age < 4: return 'baby';
case age < 13: return 'child';
case age < 20: return 'teen';
case age < 65: return 'adult';
case age < 141: return 'senior';
default: return 'This is not a valid age;

The key is that the value in the case must match or satisfy the value/expression in the switch argument. boolean => boolean; number => number; string => string. Above we use the boolean expression match.