How am I supposed to use isNaN in this code?!


#1

This is completely losing me.

var isEven = function(number) {
if(number%2==0) {
return "This number is even.";
} else if(isNaN(number)==true) {
return "Please enter a number.";
} else {
return "This number is odd."
}
};

I have no idea what to put in the isNan argument. Do I put isEven or number? This, to me, is saying first check if the entered number is cleanly divisible by two. if it is, print this text. If not, run an isNaN check on the entered number. if it returns TRUE (it is not a number) then print this text. If it returns FALSE (it is a number) then move on. If the above two checks are skipped then print this text.

But it's telling me that my function returns true for 3? HOW? I'm saying take a number, divide by 2 and spit out the remainder. If this remainder equals zero then print this text. How can it be returning true to the if check when it will always return FALSE if there is a remainder?!

I've tried everything I can think of, even pasting in code from others on this board who say their code works, and nothing works. Worse than that, I have no idea whatsoever why any of this is or isn't working. I'm learning nothing and I feel like giving up.


#2

I had trouble with that too.

this code worked for me

var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "random string of your choosing";
} else {
return false;
}
};

isEven(6);

sorry if this doesn't help, but it helped me out!


#3

Ok first of all the use of isNaN is pretty simple:

isNaN(x)

is true if x is Not a Number.
is false if x is a number.

The what you want in this case is to check whether your input is a number or not.
The other problem is that the other two cases should have boolean outputs:

true for even
false for odd

Non empty strings are treated as true when used in conditions so if the test function has a line like this:

if(isEven(3))

and the returned value is a string it might be true although it should not be.
Hope this makes it a little clearer.


#4

It works well:relaxed: