How to find exponent power of a number in JavaScript

featured Image

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.

62 = 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 xy value.

It takes two arguments: base and exponent.

Syntax:

Math.pow(base, exponent)
argument description
base The base number.
exponent the 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.

62 = 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

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more