JavaScript: Test if a number is a power of 2
JavaScript Math: Exercise-13 with Solution
Write a JavaScript function to test if a number is a power of 2.
Test Data:
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256));
Output:
true
false
true
Pictorial Presentation:
Sample Solution-1:
JavaScript Code:
function power_of_2(n) {
if (typeof n !== 'number')
return 'Not a number';
return n && (n & (n - 1)) === 0;
}
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256));
Sample Output:
true false true
Flowchart:

Sample Solution-2:
JavaScript Code:
const power_of_2 = n => !!n && (n & (n - 1)) == 0;
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256));
Sample Output:
true false true
Live Demo:
See the Pen javascript-math-exercise-13 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript function to find out if a number is a natural number or not.
Next: Write a JavaScript function to round a number to a given decimal places.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join