EN
JavaScript - check if number is power of 2
4 points
In this short article, we would like to show how to check if number is power of 2 using JavaScript.
Quick solution:
xxxxxxxxxx
1
const isPower = (value) => value > 0 && (value & (value - 1)) === 0;
2
3
4
// Usage example:
5
6
console.log(isPower(0)); // false
7
8
console.log(isPower(1)); // true
9
console.log(isPower(2)); // true
10
console.log(isPower(4)); // true
11
console.log(isPower(8)); // true
12
console.log(isPower(16)); // true
13
console.log(isPower(32)); // true
14
console.log(isPower(64)); // true
15
console.log(isPower(128)); // true
16
console.log(isPower(256)); // true
17
console.log(isPower(512)); // true
18
console.log(isPower(1024)); // true
19
20
console.log(isPower(10)); // false
21
console.log(isPower(20)); // false
22
console.log(isPower(30)); // false
23
console.log(isPower(40)); // false
24
console.log(isPower(50)); // false