Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JavaScript issue, if else related!

Here's the code.

function numSize (number) {

  if (number >= 1000) {
    return That is a big number!
  }

  if (number >= 500) {
    return That is a medium number!
  }

  if (number <= 500) {
    return That is a small number!
  }

  if (number <= 3) {
    return That is a very small number!
  }

}

It works fine up until I need it to produce the "Very small number" string. It only goes up to "Small number". How can I work around this, I'm new to JS and still figuring things out!

What andren said is fully true.

Also, just simply another valid way of doing it (not necessarily better, just a different one) is using the else if and else. Like this:

function numSize(number) {

  if (number >= 1000) {
    console.log("That is a big number!");
  } else if (number >= 500) {
    console.log("That is a medium number!");
  } else if (number >= 4) {
    console.log("That is a small number!");
  } else {
    console.log("That is a very small number!");
  }

}

numSize(3);

If you want to, you can change the console.log() to return as you need.

2 Answers

The problem is with the logic of your statements. Let's say the number 1 is passed to your function. That number is less than 3, but it is also less than 500. Since the less than 500 check happens first that is what runs. And once you return from a function it stops running. So the last if statement is never evaluated.

You could fix this in a number of ways. You could simply change the order of the if statements for one, so that the less than or equal to 3 check happens first. Or you could change the condition of the third if. Make it be greater or equal to 4 for example, which would result in the same logic that you are trying to achieve without having to reorder the code.

Like this:

function numSize (number) {

  if (number >= 1000) {
    return "That is a big number!";
  }

  if (number >= 500) {
    return "That is a medium number!";
  }

  if (number >= 4) {
    return "That is a small number!";
  }

  if (number <= 3) {
    return "That is a very small number!";
  }

}

I also added quote marks around your strings and semicolons, which was missing in the code you pasted.

You could also put the if <=3 ahead of if <=500