Javascript Quick Tips - the double negation trick
Imagine you just crafted this new nifty function to test whether a given number is odd or not. In the process, you had used the modulo operator %, like so:
function isOdd(num) {
return num % 2;
}
isOdd(2) // returns the integer '0'
isOdd(3) // returns the integer '1'
As the integer 0 is evaluated to false and any other number is evaluated to true, the following will return the expected result:
if (isOdd(num)) alert(num + ' is odd!);
else alert(num + ' is even!);
In order to obtain a result more in line with the name of the function (i.e. returning either true or false rather than 1 or 0), you could resort to use the bulky Boolean() object:
function isOdd(num) {
return new Boolean(num % 2);
}
isEven(2) // returns 'false'
isEven(3) // returns 'true'
Resort no longer! You can save a few kb and impress your peers by applying the double negation trick:
function isOdd(num) {
return !!(num % 2);
}
isOdd(2) // returns 'false'
isOdd(3) // returns 'true'
I would be pretty curious to know which of new Boolean() and !! is actually the fastest, or if the difference is even measurable. Any benchmarkers around?
Comments
-
What’s wrong with the following? return (num % 2) != 0;
Sat, August 26 at 13:04 PM