Logical Order in If Else Statements function orderMyLogic

Logical Order in If Else Statements function orderMyLogic
0.0 0

#1

Tell us what’s happening:

The exercise returns the following:
This is correct:
orderMyLogic(6) should return "Less than 10"
orderMyLogic(11) should return “Greater than or equal to 10”

But this is not:
orderMyLogic(4) should return “Less than 5”

How to solve?

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(20);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:


#2

4 is less than 10, so the first statement is true and your code returns “Less than 10”


#3

Sorry I don’t understand what I’m doing wrong :confused:


#4

A function can return only once. Specifically, it returns at the first return statement it hits.

function func(obj) {
  if (obj.foo) {
    return 'foo';
  }
  if (obj.bar) {
    return 'bar';
  }
}

func({foo: true}); //returns 'foo'
func({bar: true}); //returns 'bar'
func({foo: true, bar: true}); //returns 'foo'

#5

Always start checking for lower values first and go up to higher ones. Your first if check for <10 instead of <5.


#6

If I write:

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

// Change this value to test
orderMyLogic();

I get two errors instead of 1:
Wrong:

  • orderMyLogic(4) should return “Less than 5”
  • orderMyLogic(6) should return “Less than 10”

Right:

  • orderMyLogic(11) should return “Greater than or equal to 10”

What am I doing wrong? :confused:


#7

if <5 then return less then 5 else if <10 return less then 10 else >=10 return grater or = to 10


#8

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


Look very carefully at your code. What d you return if it’s less than 5? What do you return if it’s less than 10?


#9

It worked :slight_smile: thanks!


#10

Glad you solved it. :+1: