The order of > and < statements

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

Because 22 < 50 is true? Given x = 22, then x < 20 is false, so it moves on to the next conditional

he exercise is very cleverly relying on the ascending order, we can go for a descending order but then we need to flip the conditional as well:

age >= 65
age >= 20
age >= 13
age >= 4

or we would need to introduce two conditionals (checking both the upper and lower bounds)

Thanks stetim94. Very straightforward indeed. Easily get stuck when working with conditionals… :skull:

1 Like