`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.
Written by Angela
Related protips
2 Responses
Javascript can be so weird ;)

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); // falseHave a fresh tip? Share with Coderwall community!
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