
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Nearest power 2 of a number - JavaScript
We are required to write a JavaScript function that takes in a number and returns a number that can be represented as a power of 2 which is nearest to the input number.
For example −
If the input number if 365, then the output should be 256, because 256 is the nearest such number to 365 which can be represented as 2^n for some whole number value of n.
Example
Let’s write the code for this function −
const num = 365; const nearestPowerOfTwo = num => { // dealing only with non-negative numbers if(num < 0){ num *= -1; } let base = 1; while(base < num){ if(num - base < Math.floor(base / 2)){ return base; }; base *= 2; }; return base; }; console.log(nearestPowerOfTwo(num));
Output
The output in the console: −
256
- Related Articles
- Round number down to nearest power of 10 JavaScript
- Nearest Prime to a number - JavaScript
- Rounding off numbers to some nearest power in JavaScript
- Finding nearest Gapful number in JavaScript
- Finding nearest prime to a specified number in JavaScript
- How to find a nearest higher number from a specific set of numbers: JavaScript ?
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Check if given number is a power of d where d is a power of 2 in Python
- Compute modulus division by a power-of-2-number in C#
- Number of pairs whose sum is a power of 2 in C++
- How to get the exponent power of a number in JavaScript?
- Checking if a number is some power of the other JavaScript
- Checking if a number is a valid power of 4 in JavaScript
- Checking power of 2 using bitwise operations in JavaScript
- How to check if a number is a power of 2 in C#?

Advertisements