zpcjfg
Last Updated: November 29, 2017
·
482
· angelathewebdev
03ba33ccbb0ef8b3849096c1fe8f48e6

`isOdd` function in JavaScript

If you're asked to write a isOdd function in JavaScript, you might be tempted to write something like the following

function isOdd(num) { return num % 2 === 1; }

Assuming that num is an integer.

However, you might be surprised by the result of isOdd(-3).

Don't believe me? Try it yourself.

Yes, the result is false because JavaScript modulo operator takes the sign of the first operand, which means -3 % 2 yields -1, not 1. So...with that in mind, now you should know how to write an isOdd function in JavaScript.

Say Thanks

2 Responses
Add your response

28181
12003957 10206752435102297 2524621803006121539 n

Javascript can be so weird ;)
confused

over 1 year ago ·
28193
3f63761a027c73df64c08cbb40b81005

If you're interested in a signed alternative, consider a simple example using bitwise operators:

function isOdd(num) {
  if (num === 0) return false;

  return (num & -num) === 1;
}

isOdd(-4);   // false
isOdd(-3);  // true
isOdd(0);   // false
isOdd(3);   // true
isOdd(4);   // false
over 1 year ago ·