Exponents in JavaScript

Harshit Jindal Oct 12, 2023
  1. Math.pow() to Get Exponent in JavaScript
  2. Exponentiation Operator ** in JavaScript
Exponents in JavaScript

This tutorial teaches how to get the exponents of a number in JavaScript. JavaScript provides us two ways to achieve this. We can use either the Math.pow() function or the exponentiation operator **.

Math.pow() to Get Exponent in JavaScript

The Math.pow() function is used to calculate the power of a number i.e., calculate the base to the power of exponent (baseexponent). It returns NaN if the base is negative and the exponent is not an integer. It is a static function and always used as Math.pow() and not as an object of the Math class.

Syntax of Math.pow()

Math.pow(base, exponent)

Math.pow() Parameters

  • base: It is the base number that is to be raised.
  • exponent: It is the value used to raise the base.

Return Value of Math.pow()

The Math.pow() method returns (baseexponent).

Example of Using Math.pow()

console.log(Math.pow(7, 2));
console.log(Math.pow(4, 0.5)));
console.log(Math.pow(7, -2));
console.log(Math.pow(-7, 2));
console.log(Math.pow(-7, 1 / 3));

Output:

49
2
0.020408163265306124
49
NaN

All the major browsers support this method.

Exponentiation Operator ** in JavaScript

The exponentiation operator (**) returns the result of raising the base to the power of the exponent i.e. (baseexponent). It is a right-associative operator and hence a ** b ** c is the same as a ** (b ** c).

Example

2 ** 3    // 8
NaN ** 2  // NaN
3 ** 2.5  // 15.588457268119896
10 ** -1  // 0.1

Its advantage is that it also supports Big Integers, but at the same time, it has the disadvantage that we have to keep negative bases in parenthesis.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - JavaScript Math