JavaScript Math.pow() Method

MD Niaz Rahman Khan Jan 30, 2023
  1. Syntax of Math.pow()
  2. Example 1: Use the Math.pow() Method in JavaScript
  3. Example 2: Use the Math.pow() Method With Exception
  4. Example 3: Create Your Own Math.pow() Function
JavaScript Math.pow() Method

The Math.pow() method only deals with the integers. It accepts base and exponent as two parameters and calculates the base’s power with the exponent.

Syntax of Math.pow()

Math.pow(base, exponent)

Parameters

base The parameter base refers to a numeric value. It is required.
exponent The parameter exponent refers to a numeric value. It is required.

Return

The Math.pow() method returns the power of a number. This method returns NaN if the base or exponent does not contain an integer value.

Example 1: Use the Math.pow() Method in JavaScript

const result1 = Math.pow(2, 5)
const result2 = Math.pow(-5, 2)

console.log(result1)
console.log(result2)

Output:

32
25

First, we take 2 as the base and 5 as the exponent. This method returns 32 as a result.

Second, we calculate -5 to power 2. It returns a positive number even though we are computing it with a negative number.

A simple mathematical reason is that a square always returns a positive number.

Example 2: Use the Math.pow() Method With Exception

const result1 = Math.pow(11)
const result2 = Math.pow(5, 'five')
const result3 = Math.pow()

console.log(result1)
console.log(result2)
console.log(result3)

Output:

NaN
NaN
NaN

This method returns NaN if one parameter is missing, or not a number provides, or no value is passed in the parameter.

Example 3: Create Your Own Math.pow() Function

function myPowfunction (base, exponent){
    return base ** exponent
}

console.log(myPowfunction(2,5))
console.log(myPowfunction(-5,2))

Output:

32
25

We have created our power function and named it myPowfunction. Our created function behaves exactly like the Math.pow() method.

The purpose is to realize that there is no rocket science behind this. One with basic JavaScript knowledge may be able to understand what’s happening behind the scene.

MD Niaz Rahman Khan avatar MD Niaz Rahman Khan avatar

Niaz is a professional full-stack developer as well as a thinker, problem-solver, and writer. He loves to share his experience with his writings.

LinkedIn

Related Article - JavaScript Math