Below is the code from this exercise.
const lifePhase = age => {
if (age < 0 || age > 140) {
return 'This is not a valid age'
} else if (age < 4) {
return 'baby'
} else if (age < 13) {
return 'child'
} else if (age < 20) {
return 'teen'
} else if (age < 65) {
return 'adult'
} else {
return 'senior citizen'
}
}
I would like to know why when using greater than operator >
, the statements have to be in ascending order in terms of number (age). And descending order with less than operator >
.
When the order of the statements is reversed, the code does not work as intended:
const lifePhase = age => {
if (age < 0 || age > 140) {
return 'This is not a valid age'
} else if (age < 65) {
return 'adult'
} else if (age < 20) {
return 'teen'
} else if (age < 13) {
return 'child'
} else if (age < 4) {
return 'baby'
} else {
return 'senior citizen'
}
}
// Apart from invalid age, result will always be the first option, 'adult'
An example I thought of:
Given x = 22,
x < 20
x < 30 // This statement will be executed. I understand this.
x < 40
x < 50
x < 50 // This statement will be executed. Why is it not at x < 30?
x < 40
x < 30
x < 20