最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if statement - checking if number is even in JavaScript - Stack Overflow

programmeradmin0浏览0评论

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;
}

};

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;
}

};

Share Improve this question asked Mar 4, 2016 at 1:28 Dane ChristianDane Christian 92 silver badges4 bronze badges 3
  • 4 Inside your function you should use number, not isEven. – visola Commented Mar 4, 2016 at 1:30
  • thank you, that makes a lot of sense.. fixed – Dane Christian Commented Mar 4, 2016 at 1:42
  • I suggest you learn how to debug your programs. For instance, in the first line of the function, you could output isEven % 2 to see what its value is. You could alert it, or console.log it. Or you could put a breakpoint there and examine the value of isEven % 2 in the debugger. In either case, you would see the value was NaN. To figure out why, you could then examine the value of isEven itself, and see that it was a function. That would point you to the problem that you are taking the modulus of the function, rather than the parameter number. – user663031 Commented Mar 4, 2016 at 3:28
Add a ment  | 

2 Answers 2

Reset to default 9

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 parison.

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;
  }
}
发布评论

评论列表(0)

  1. 暂无评论