While solving Mathematical problems in JavaScript, finding the power of a number is a common task. You can calculate the exponent of the small numbers easily, but for the large numbers, it is a bit difficult. In JavaScript, you can use different approaches, such as predefined methods or operators.
This article will illustrate the different ways to get the exponent of a number in JavaScript.
How to Get/Find the Exponent of a Number in JavaScript?
To get the exponent of a number, use the following approaches:
Method 1: Get the Exponent of a Number Using “**” Operator
To get the exponent or a power of a number use the “**” operator. It returns the result of multiplying the first operand by the second operand’s power. It’s the same as Math.pow().
Syntax
Utilize the following syntax for the “**” operator:
Example
Create two variables, “base” and “exponents”, and store numbers “9” and” 3” respectively:
var exponent = 3;
Use the ** operator with base and exponent variables and store the resultant value in variable “power”:
Finally, print the result on the console:
[cc lang="javascript" width="100%" height="100%" escaped="true" theme="blackboard" nowrap="0"]
console.log(power);
It can be seen that the 9^3 is 729 as 9 multiply by three times:
Method 2: Get the Exponent of a Number Using “Math.pow()” Method
Use the “Math.pow()” method for getting the exponent of a number in JavaScript. It is a predefined method of the Math object used to find the power of a number n^n.
Syntax
Follow the given syntax for the Math.pow() method:
Example
Invoke the Math.pow() method by passing variables base and exponent as arguments and print the resultant value on the console:
console.log(power);
Output
Method 3: Get the Exponent of a Number Using “for” Loop
You can also use the “for” loop for getting the exponent of a number without using any predefined JavaScript method.
Example
Define a function named “exponentOfNumber()” that takes two parameters, “base” and “exponent”. Create the variable “power” and set the value to 1. Use the for loop and multiply the base with power up to exponent and return back to the function:
power = 1;
for(var i=0; i<exponent; i++){
power = power * base;
}
return power;
}
Call the function by passing “9” and “3” as arguments:
The output displays “729” which is the 9^3:
That’s all about the getting exponent of a number in JavaScript.
Conclusion
To get the exponent of a number in JavaScript, use the “**” operator, “Math.pow()” method, or the “for” loop. Math.pow() is the most common method to be used for getting the exponent of a number in JavaScript. This article illustrated the different ways to find the exponent of a number in JavaScript.