How could I use a switch statement for this lesson?

The switch is inside a function, and each branch uses return which not only leaves the switch body, but also exits the function body.

1 Like

So to conclude, can we or can we not use comparative operators in a switch statement? Or better yet, can we use switch statements for more than only specific value conditions? Thank you!

1 Like

We can use any expressions. The key is finding matching values.

1 Like

Is happening to me as well,i literally paste and copy the code and still not letting me proceed… :face_with_symbols_over_mouth:

This made me see it from a completely other way. I thank you! :bowing_man:

1 Like

Well another way to solve this is using logical operators, it may not be the recommended way to solve it but it’s just possible

const lifePhase = age => (age > 140 || age < 0) && 'This is not a valid age' ||
                          age < 4 && "baby" || age < 13 && "child" ||
                          age < 20 && "teen" || age < 65 && "adult" || 
                          "senior citizen";

Note the parentheses I used here (age > 140 || age < 0) to control operators precedence, cause the && operator has more precedence than the || operator

2 Likes

Although creative, many languages advise against excessive line lengths. Beyond that, readability is of high concern and that line of code would be considered a violation of readability, especially in production code. If you have to jump back and forth on the same line of code like here, then you need to reconsider the flow of control.

1 Like

Yup, it’s doesn’t suit production code.

I will say I love code golf and ternary operators. Great code golf answer.

1 Like

Hi all,

I am not so sure what I am missing.
I actually looked the switch statement up on mozilla docs and did some googling (stack overflow) to validate that i could use switch cases with && / ||.

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;
      default:
        return 'This is not a valid age'
        break;
    }

        
  }

  let e = lifePhase(5)
  console.log(e)

I should get ‘child’ back, but i keep getting the ‘This is not a valid age’ back. Anyone can spot the error i am making?
Thanks in advance!!

2 Likes

An excellent and insightful point - thanks!

1 Like

That example has an error. It should have been corrected a few posts later, as I recall.

1 Like

Haha all good - I’m just running this course to refresh everything. I just really enjoyed seeing some conditional switches (not to mention the nested ternary expressions ) . It’s always good to see these things to remind yourself how one should never stop learning when it comes to coding. Merry Christmas && thanks for contributing :smiley:

1 Like

Would it were that posting such examples didn’t spur on a bunch of copycats. People who post it like it was their own, as if they could have conceived of it at the time. All I can say, if you ever come across a code thief, call them out immediately for what they are. The industry needs creativity and innovation, not plagiarism.

2 Likes

Whilst I agree wholeheartedly with what you’re saying - I do subscribe to the philosophy that there shouldn’t be any secrets in coding. We’ve all been the noob trying to figure out list comprehension or obscure terminal commands, and there are always people who not only want to help, but will happily take time (for free!) to grow the community because someone else took the time when they were learning.

But yes, plagiarism sucks - fortunately it seems the bulk of major contributors will always cite their work.

2 Likes

Help, from where I stand, means genuinely think about their problem and apply whatever intuition will yield the guidance that best works in their situation. It means either coming up with original examples, or citing the examples they present. They’re not helping if they didn’t conceive of the code. It is an unattributed example they stole from somewhere, in an effort to gain credibility and build trust; said trust ill deserved under these circumstances.

Nothing elevates a helpful learner in my esteem than one who is willing to fall on their face expressing their own ideas.

1 Like

In the use of your switch block how would you log the return to the console?

Thank you because of your attempt i was able to work it out on my own and hopefully provide you with some clarity to why you your code is logging undefined

function lifePhase(age) {

switch (true) {

  case age < 0:

    console.log('This is not a valid age');

    break;

  case age <= 3:

    console.log('baby');

    break;

  case age <= 12:

    console.log('child');

    break;

  case age <= 19:

    console.log('teen');

    break;

  case age <= 64:

    console.log('adult');

    break;

  case age <= 140:

    console.log('senior citizen');

    break;

  case age > 140:

     console.log('This is not a valid age');

     break;



}

}

lifePhase(2); // baby

lifePhase(8); // child

lifePhase(15); // teen

lifePhase(26); // adult

lifePhase(80); // senior citizen

lifePhase(-8); //This is not a valid age

lifePhase(188); //This is not a valid age

By learning how to use switch ranges i was able to widen the range on my switch cases perfectly using the = operator as well as set my boundaries by putting the first at the beginning and the next at the last

I was thinking the same thing. I think it has 2 reasons, but im still new so i’m not 100% sure.

  1. If you have an if statement all on one line - I think it can run without {} brackets.
  2. It seems as though if/else means the program exits when it finds a matching condition, whereas if/if/if/if will evaluate each condition even if it meets one already. Second being inefficient, but irrelevant for a small program like this? Got this off stackoverflow here.

Hi thanks to mtf, I learned you cannot put comparative statements unless the switch expression is a boolean. My solution is more verbose and uses the tradition switch, case, break syntax.

// Write your function here:

const lifePhase = (age) =>{

 let phase = "";

 switch (true) {

  case ((age <= 0) || (age > 140) ):

     phase = "This is not a valid age";

    break;

  case (age <= 3):

   phase = "baby";

    break;

  case (age <= 12):

   phase = "child";

    break;

   case (age <= 19):

   phase = "teen";

    break;

      case (age <= 64):

   phase = "adult";

    break;   

   case (age <= 140):

     phase = "senior citizen";

     break;

}

  return phase;

}

// Uncomment the line below when you're ready to try out your function

console.log(lifePhase(-5)) //should print "This is not a valid age"

console.log(lifePhase(0)) //should print "This is not a valid age"

console.log(lifePhase(141)) //should print "This is not a valid age"

console.log(lifePhase(.5)) //should print 'baby'

console.log(lifePhase(12)) //should print 'child'

console.log(lifePhase(19)) //should print 'teen'

console.log(lifePhase(64)) //should print 'adult'

console.log(lifePhase(65)) //should print 'senior citizen'

console.log(lifePhase(140)) //should print 'senior citizen'

// We encourage you to add more function calls of your own to test your code!
1 Like