Last Updated: September 30, 2021
·
8.604K
· 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.

2 Responses
Add your response

Javascript can be so weird ;)
confused

over 1 year ago ·

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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside