Introduction
Numbers are important, and within JavaScript, there are different ways to work with them. Interestingly, there are two data types - Number
and BigInt
- that we can make use of when working with numbers. Different calculations can be made within JavaScript from additions to divisions and even to complex operations such as logarithmic operations.
However, our focus is exponentiation, where we raise a number to the power of another number. How do we execute math power operations in JavaScript? That’s what this article intends to explain.
Different methods to execute Math Power in JavaScript
JavaScript makes provision for two approaches to execute exponentiation operations. These approaches are the **
operator and the pow
method namely.
Method-1: The **
operator
The ** operator accepts both Number
and BigInt
datatype operands, and allows us to infuse it within typical JavaScript statements and assignments. Let’s illustrate ways to use the **
operator in different ways and contexts.
const power = 3;
const number = 4;
console.log(number ** power);
Output
64
But what’s beautiful about this is that we can use the operator with the assignment operator. In the example below, we raise the value of the num
binding to the power of 2 using the exponentiation assignment operator, **=
.
let num = 5;
num **= 2;
console.log(num);
Output
25
Also, it works with BigInt
.
let num = BigInt(23456121);
num **= BigInt(2);
console.log(num);
Output
550189612366641n
Method-2: The pow
method
JavaScript has a Math object that contains static properties and methods, and the pow
method is one of the many. To perform math power operations, the Math.pow()
method returns the value of a base raised to a power, but what’s important is that it only works with the Number
data type.
Let’s play with the pow
method by raising the number 4 to the power of 3.
const power = 3;
const number = 4;
console.log(Math.pow(number, power));
Output
64
Summary
To perform math power operations in JavaScript, we can make use of the **
operator and the pow
method, however, only the **
operator works with the Number
and BigInt
data type.
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation
Math.pow() - JavaScript | MDN (mozilla.org)