Implementing Math function and return m^n in JavaScript

We are required to write a JavaScript function that takes in two numbers say m and n. Then function should calculate and return m^n.

For example ? For m = 4, n = 3, then

power(4, 3) = 4^3 = 4 * 4 * 4 = 64
power(6, 3) = 216

Using Built-in Math.pow() Method

JavaScript provides the built-in Math.pow() method for calculating powers:

console.log(Math.pow(4, 3));  // 4^3
console.log(Math.pow(6, 3));  // 6^3
console.log(Math.pow(2, -2)); // 2^(-2) = 1/4
64
216
0.25

Custom Implementation Using Recursion

Here's a custom recursive implementation that handles positive, negative, and zero exponents:

const power = (m, n) => {
    if(n < 0 && m !== 0){
        return power(1/m, n*-1);
    };
    if(n === 0){
        return 1;
    }
    if(n === 1){
        return m;
    };
    if (n % 2 === 0){
        const res = power(m, n / 2);
        return res * res;
    }else{
        return power(m, n - 1) * m;
    };
};

console.log(power(4, 3));
console.log(power(6, 3));
console.log(power(2, 0));
console.log(power(5, -2));
64
216
1
0.04

How the Algorithm Works

The recursive algorithm uses these optimization strategies:

  • Negative exponents: Convert to positive by using reciprocal (1/m)
  • Base cases: n=0 returns 1, n=1 returns m
  • Even exponents: Use m^n = (m^(n/2))^2 to reduce calculations
  • Odd exponents: Use m^n = m^(n-1) * m

Simple Iterative Approach

For basic understanding, here's a simple iterative version:

const simplePower = (m, n) => {
    if (n === 0) return 1;
    if (n < 0) return 1 / simplePower(m, -n);
    
    let result = 1;
    for (let i = 0; i < n; i++) {
        result *= m;
    }
    return result;
};

console.log(simplePower(3, 4));  // 3^4
console.log(simplePower(2, -3)); // 2^(-3)
81
0.125

Comparison

Method Time Complexity Best For
Math.pow() O(1) Production use
Recursive (optimized) O(log n) Learning algorithms
Simple iterative O(n) Understanding concept

Conclusion

Use Math.pow() for production code. The recursive approach demonstrates efficient algorithm design using divide-and-conquer strategy.

Updated on: 2026-03-15T23:19:00+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements