How could I use a switch statement for this lesson?

I’ve tried to solve this problem using a Switch statement. For those of us who attempted to solve this using switch, this is why its the incorrect approach:
'Yes, this is a very common mistake. You are confusing the usage of the switch statement with the if/else statement.

Please keep in mind that you should only use switch as a conditional for specific values. You cannot test conditions such as (1<3) or anything like that. You cannot use comparative operators in a switch statement, that’s what the if/else statements are for."

3 Likes

It may be non-standard usage, but in truth the expressions can be swapped.

switch (true) {
  case age < 0: age = 141;
  case age < 3: return 'baby';
  case age < 13: return 'child';
  case age < 20: return 'teen';
  case age < 65: return 'adult';
  case age < 75: return 'senior';
  case age < 141: return 'elderly';
  default: return "This is not a valid age."
}

Maybe it is not recommended, but that does not mean we cannot do it.

14 Likes

Something else that someone might say, “We cannot do…”

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';
}
undefined
life_cycle(75)
"elderly"
life_cycle(64)
"adult"

Be that as it may, if we use the language according to syntax rules, we’re half the way to finding interesting and sometimes purposeful ways to do things.

9 Likes

Thank you so much! This saves me hours

2 Likes

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

I am confused and hope somebody could explain it to me… After my switch statement didn’t work, I tried with if/else statement. It works but it shows also the ‘undefined’. After I compared my code with the solution of Codecademy I see that the reason is using console.log() in my return part. Could somebody tell me why is it wrong? This is my code:

const lifePhase = (age) => {
if (age<0 || age>140) {
return console.log(‘This is not a valid age’);
} else if (age<=3) {
return console.log(‘baby’);
} else if (age<=12) {
return console.log(‘child’);
} else if (age<=19) {
return console.log(‘teen’);
} else if (age<=64) {
return console.log(‘adult’);
} else {
return console.log(‘senior citizen’);
}
};

console.log(lifePhase(5)) //prints child and undefined

.log() logs output the console, but the log method doesn’t return anything, so you get undefined (the absence of a return value).

1 Like

A beautifully written solution but I didn’t get why we are calling the switch on some true. What is this true? Why not on age instead?

2 Likes

A switch matches the expression in the argument with the expressions in the cases and follows the branch that fits. The first case expression that proves true is that match.

3 Likes

And this seems to work (albeit you’d need to type out ALOT of cases to cover all the ranges.

const lifePhase = age => {
  switch (age) {
    case 0:
    case 1:
    case 3:
      return 'baby';
    case 4:
    case 5:
      return 'child';
    default:
      return 'This is not a valid age';
  }
}



// Uncomment the line below when you're ready to try out your function
console.log(lifePhase(5)) //should print 'child'


So is it then a good idea to use switch here?

1 Like

switch is one of those things you can safely forget it exists, there’s nothing to miss out on, doesn’t do anything special. pretty sure it only exists in the language by accident (which might not say much since that about sums up the whole language), actual reasons for using a switch aren’t relevant in js

1 Like

■■■■ no. You’d be there forever. I wanted to play around with switch after I’d completed it with if/else.

That’s really useful to know thanks. One of the lessons went into quite a lot of detail about it so I’ve been trying to ensure I look at how it could be used in some of the exercises.

I’ll move down the priority list in my brain now. :+1:

Yes, that’s quite amusing, every tutorial ever does that, even though each one also fails to say what it’s good for.
You will to some degree run into the same thing with classes later, tutorials love making some kind of ritual out of that and yet make no sense whatsoever while using some example that doesn’t solve a problem. Classes are useful though, to some extent. The thing that’s really useful is functions. Functions do uhm. Everything. If you have functions you don’t need much else.

1 Like

The above considerations notwithstanding, we can use expressions in the case branches…

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

Which is not an improvement over if-statements in any way

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