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

For the life of me I don't understand why this doesn't work. It looks similar if not identica

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742354869a4428229.html

相关推荐

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

    For the life of me I don't understand why this doesn't work. It looks similar if not identica

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信