Basic JavaScript: Logical Order in If Else Statements

Tell us what’s happening:

Your code so far


function orderMyLogic(val) {
  if (val < 10) {
    return "Less than 10";
  } else if (val < 5) {
    return "Less than 5";
  } else {
    return "Greater than or equal to 10";
  }
}

// Change this value to test
orderMyLogic(11);
orderMyLogic(4);
orderMyLogic(6);

// running tests

orderMyLogic(4) should return “Less than 5”

// tests completed

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements

Code goes line by line, when it encounters val < 10 it will pass for anything below 10, which means val < 5 is never evaluated.

The tests wants your function to return “Less than 5” when it pass the argument 4 for example, but your code returns “Less than 10”.

why?
i use operator else if… and else first if(val < 10) not true,then this will be executed (val <5).
not true?

Correctly, but when (val < 10) is not true? When val is equal or bigger than 10, which means it is also bigger than 5. Thus, (val < 5) will never be true.

1 Like


It must be true …?

i can’t understand =(

The code goes line by line. Let’s do that:

function orderMyLogic(val) { // START - val is 4 for example
  if (val < 10) { // ok first we evaluate this, val < 10 ? yes! enter the conditional
    return "Less than 10"; // END - return "Less than 10"
  } else if (val < 5) { // the code doesn't even reach here because we already returned from the function
    return "Less than 5";
  } else {
    return "Greater than or equal to 10";
  }
}