function lifePhase(age) {
if (age >= 0 && 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
return ‘This is not a valid age’;
Here is your code but run through a formatter to make it easier to see why you didn’t need the curly braces {} in this case:
function lifePhase(age) {
if (age >= 0 && 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 return 'This is not a valid age';
}
Since you aren’t running more than one line of code after each condition, the curly braces to tell JavaScript which lines are part of the code block weren’t required.
To make it a little clearer, here is your code reformatted, but then one condition where we are logging something too. Now the curly braces {} were required
function lifePhase(age) {
if (age >= 0 && 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) {
console.log('The person is an adult.');
return 'adult';
} else if (age >= 65 && age <= 140) return 'senior citizen';
else return 'This is not a valid age';
}
Someone once told me, “messy is missy,” and it took me a minute to grasp the meaning. Later I recognized it was, excess of logic leads to excess of exclusions.
Moral of the story is to leave the door open to floats, and if needs be, narrow it to integers. We cannot go the other way.
if (x < 0 || x > 140) return "This is not a valid age";
if (x < 3) return 'baby'
if (x < 13) return 'child'
if (x < 20) return 'teen'
if (x < 65) return 'adult'
return 'senior citizen'
The above is what I call, progressiveness over betweenness.
Think of the simplified logic. If it is not less than 3 then what is it? Greater or equal, by default. If it is not less than 13 then what is it? Greater or equal, again by default. &c.