How to find exponent power of a number in JavaScript

javascript2 min read

Find out how to get the exponent power of a number with and without using the Math.pow() method in JavaScript.

In this article, we will learn how to find the power of a number in JavaScript.

Here is a small example of getting the exponent power of a number.

6<sup>2</sup> = 6 * 6 , the value is 36.

Here, 6 is the base number and 2 is the exponent.

JavaScript provides us with a handy function, Math.pow() to perform the above calculation easily.

However, in this article, we will perform the calculation in two different ways using:

  1. Math.pow(), and
  2. for loop

Let's check each method with an example.

Using Math.pow() to find the power of a number

The Math.pow() in JavaScript returns the base to the exponent power i.e x<sup>y</sup> value.

It takes two arguments: base and exponent.

Syntax:

Math.pow(base, exponent)
argumentdescription
baseThe base number.
exponentthe value used to raise the base number.

Let's use the function to raise the base number in JavaScript.

const b = 5; const e = 2; console.log(Math.pow(5,2)) // 25

This is the easy way to raise a number to a power in Javascript.

However, if you don't want to use the Math.pow() function, you can code the function manually using for loop.

Using for loop to find the power of a number in Javascript

First, let's understand how we will code the loop JavaScript function.

Let's see an example of calculating power of a number.

6<sup>2</sup> = 6 * 6 , the value is 36 (6 is the base and 2 is the exponent)

So, to perform this using for loop, we have to loop exponent times and multiple the base number on each loop.

Example:

function powOfNum(b,e){ pow = 1; for(var i=0; i<e; i++){ pow = pow*b; } return pow; } console.log(powOfNum(5,2)) // 25

In the above code, we have created a function powOfNum() , which will take two arguments (b, e) i.e base and exponent.

It then loops the exponent number of times and the multiplied base value is stored in pow , which is returned once the condition (i<e) turns false .

Related Posts