2. If / else if / else ; question


#1

Hi! Thanks at first.
I am getting this error message with my code "Oops, try again. Your function returns true for 3!".
Could someone tell me what I am doing wrong?
Thanks again.

var isEven = function(number) {
    if (number % 2 === 0) {
      return "something";
      }
    else if (isNaN(number)) {
         return "Not a number mah boy";
          
          }
    else {
     return "some other thing";
      }
};
isEven("s");

#2

In your code you are returning strings. Any string aside from the empty string "" will be treated as true.

To be sure you return the appropriate true or false value, consider actually returning true or false.

I don't remember the exercise well but I don't remember it asking you to check for isNaN. It would be considered good function design if your functions returned predictable types. Even though JavaScript allows you to return any kind of value its still not a great idea to do so unless you have a good reason.

If your function either returned true or false then you could use your function predictably:

var isEven = function(number) {
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
};

if (isEven(31)) {
  // do something cool
}

By checking for isNaN in your isEven code, by returning a string you are effectively returning true. Thus calling isEven("sandwich"); will return an incorrect result.


#3

Thanks for your reply. That's what the lesson wants me to do:
Add an else if branch to your existing if/else statement. If the number put into the function is not a number at all, instead of return true; or return false;, the function should return a string that tells the user that their input isn't a number. (This string can say whatever you like.)

I don't think it asked me to return false if it was an odd number. BUT I followed your advice and made the "else" return false, like that:

var isEven = function(number) {
    if (number % 2 === 0) {
      return "something";
      }
    else if (isNaN(number)) {
         return "Not a number mah boy";
          
          }
    else {
     return  false;
      }
};
isEven("s");

Now it works.
Thank you so much for your explanation.


#4

Good job, and thanks for letting me know. What you'll often see on a 'type' test is a call to 'console.error()' or to actually 'throw' an error.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.