`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 ;)
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
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#