JavaScript Program to Find Power of Number
You can find the power of a number in JavaScript using
Math.pow(base, exponent) or the exponentiation operator base ** exponent.Examples
Inputbase = 2, exponent = 3
Output8
Inputbase = 5, exponent = 0
Output1
Inputbase = 3, exponent = 4
Output81
How to Think About It
To find the power of a number, think of multiplying the base by itself as many times as the exponent says. For example, 2 to the power 3 means 2 × 2 × 2. We can use JavaScript's built-in power function or multiply in a loop.
Algorithm
1
Get the base number and the exponent number as input.2
If using built-in method, directly calculate power using Math.pow or ** operator.3
If using loop, start with result = 1.4
Multiply result by base repeatedly exponent times.5
Return the final result.Code
javascript
const base = 2; const exponent = 3; const power = Math.pow(base, exponent); console.log(power);
Output
8
Dry Run
Let's trace the example base=2 and exponent=3 through the code using Math.pow.
1
Input values
base = 2, exponent = 3
2
Calculate power
Math.pow(2, 3) calculates 2 × 2 × 2
3
Output result
Result is 8
| Step | Operation | Result |
|---|---|---|
| 1 | Start with base=2 and exponent=3 | N/A |
| 2 | Calculate 2 × 2 × 2 | 8 |
| 3 | Return result | 8 |
Why This Works
Step 1: Using Math.pow
The Math.pow(base, exponent) function multiplies the base by itself exponent times internally.
Step 2: Using exponentiation operator
The base ** exponent operator is a shorter way to do the same calculation.
Step 3: Loop method
Multiplying base repeatedly in a loop simulates the power calculation manually.
Alternative Approaches
Using exponentiation operator
javascript
const base = 2; const exponent = 3; const power = base ** exponent; console.log(power);
This is shorter and more modern syntax supported in ES6+.
Using loop multiplication
javascript
const base = 2; const exponent = 3; let power = 1; for(let i = 0; i < exponent; i++) { power *= base; } console.log(power);
This method shows the manual process and works without built-in functions.
Complexity: O(n) time, O(1) space
Time Complexity
Using Math.pow or ** operator is optimized internally and runs in constant time, but manual loop multiplication takes O(n) time where n is the exponent.
Space Complexity
All methods use constant extra space O(1) as they only store a few variables.
Which Approach is Fastest?
Built-in methods like Math.pow and ** are fastest and recommended for simplicity and performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Math.pow | O(1) | O(1) | Simple and fast calculations |
| Exponentiation operator (**) | O(1) | O(1) | Modern, concise syntax |
| Loop multiplication | O(n) | O(1) | Learning and manual calculation |
Use
base ** exponent for clean and modern power calculations in JavaScript.Beginners often forget that any number to the power 0 is 1, which is a special case.