Can't find error in my code (always return 'child') no matter what i fill VScode

const lifePhase= age =>{
if (age <= 3){
  return 'baby'
} else if (age >=4 || age <=12) {
  return 'child'
}else if (age >=13 || age <=19) {
  return 'teen'
}else if (age >=20 || age <=64) {
  return 'adult'
}else if (age >=65 || age <=140) {
  return 'senior citizen'
} else if (age > 140 || age < 0){
  return 'This is not a valid age'
}
};
console.log(lifePhase(22)) // Return 'child'
console.log(lifePhase(140)); Return 'child'

Practice JavaScript Syntax: Variables, Data Types, Conditionals, Functions | Codecademy

In your if statements you have used the or || boolean operator. Writing this out in plain english, this means that it’s checking, for child:

“if age is greater than or equal to 4, or less than or equal to 12”

which thinking about it, isn’t quite right. Technically this encompasses every possible integer that could be entered, as only one or the other needs be true, therefore unless it triggers at the first statement for baby, it will always be child. This needs to be the and && operator and you want only those ages within that bracket.

There is also another way this can be done. If you think about it, if the code reaches the “child” section, it’s already implied that age must be bigger than 3, therefore you don’t need to check this again. Likewise for the higher ones too, so instead you could have:

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

And this would accomplish the same thing! Just an alternative to consider which would avoid the above issue.

1 Like

Hello, thanks for the answer I understood between || and &&!
there is still a problem, if you try -1 -2 -any on your code it return baby is because

 else if (age > 140 || age < 0){
 return 'This is not a valid age'

has to be up if (age <= 3) ?
and what if i try to use
if (age <= 3 && !age < 0)
(over 140 it still works)

Yes that’s a good point! You would generally want your validation checks to be first so as not to get erroneous messages or waste people’s time running a calculation on an invalid input. So I would make the valid age check the main if statement, and change baby to an else if.

1 Like