zpcjfg
Last Updated: August 25, 2018
·
1.655K
· angelathewebdev

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

5 Responses
Add your response

28181

Javascript can be so weird ;)
confused

over 1 year ago ·
28193

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 ·
29697

thens

8 months ago ·
30207

Friends with out sync folder facing the many problem,like that your internet not properly working,so friends read the basic information for this sync setting http://syncsettingswindows10.com microsoft developed 5 month ago this features in window 10,are you sure you want to get this sync folders,so update your window.

3 months ago ·
30478

It's worth checking sds, the string handling library from coderwall, that's completely standalone and very nice to use.
http://www.aoneassignment.com

about 2 months ago ·