Dane Christian
Dane Christian

Reputation: 9

checking if number is even in JavaScript

For the life of me I don't understand why this doesn't work. It looks similar if not identical to many solutions i've seen. Clearly there is something i'm missing. If anyone would care to explain id appreciate it.

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

};

Upvotes: 0

Views: 4881

Answers (2)

jfriend00
jfriend00

Reputation: 708156

You can fix it and shorten it to this:

function isEven(number) {
    return number % 2 === 0;
}

No need for the if/else. You can just directly return the result of the comparison.

Upvotes: 9

Tyler Davis
Tyler Davis

Reputation: 913

Your isEven function has a value that is a function.

Therefore, when you check inside (isEven % 2 === 0) it ends up always being false because isEven is NaN. Which will always return false.

Instead, using your parameter number is the correct solution.

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

Upvotes: -1

Related Questions