DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Discussion on: 7 Killer JavaScript One-Liners that you must know

Collapse
prakhart111 profile image
Prakhar Tandon

Want to add a "Killer" trick.

A function to check if a given positive integer is a power of 2

function isPowerofTwo(num){
     if( num & (num-1) == 0 ) return true;
return false;
}
Enter fullscreen mode Exit fullscreen mode

& used here is the Bitwise AND.

Collapse
jchlu profile image
Johnny C-L

This is what the modulus operator % is for. By negating the check, you return 1 (true) or 0 (false) with:
console.log(!num % 2)

Collapse
prakhart111 profile image
Prakhar Tandon

Modulus checks if the number is divisible by a number or not, It doesn't checks for exponent.