How to find exponent power of a number in JavaScript
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:
- Math.pow(), and
- 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)
| 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.
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
JavaScript - Show and hide div on button click using JavaScript
This post is about how to show and hide a div on button click using JavaScript. We will change the CSS property of the element using JavaScript to hide and show the content.
How to read text file in JavaScript (line by line)
This article is about how to read text file in JavaScript line-by-line from local computer using Html input field.
Get user location from browser using JavaScript
Tutorial on how to get user location like latitude and longitude from our browser using geolocation() function in JavaScript.
How to Get the ID of a Clicked Button or Element in JavaScript
Find out how to get the id of a button when clicked in JavaScript using onclick event listener and passing on the this.id or this.target.id.
