What's the Math.pow() Alternative for BigInt Values in JavaScript?

The JavaScript Math.pow() method only works on the number primitive values, and not on the bigint primitive values. Therefore, to calculate the power of a bigint value, you can use the exponentiation operator (**) instead:

// ES10+
const pow = (base, exponent) => base ** exponent;

console.log(pow(2n, 10n)); // 1024n
console.log(pow(12345679n, 2n)); // 152415789971041n
console.log(pow(18014398509481982n, 2n)); // 324518553658426654725561982648324n

The "n" at the end of a number merely suggests that the number is a bigint primitive.

You cannot mix the number primitive and bigint primitive together as it will throw an error.

For example, mixing number and bigint together throws an error like the following:

// ES10+
const pow = (base, exponent) => base ** exponent;

// TypeError: Cannot mix BigInt and other types, use explicit conversions
console.log(pow(2n, 10));

That being said, you may use number primitives with the exponentiation operator (**) as long as both, the base and the exponent, are of the same type:

// ES7+
// ...
console.log(pow(2, 10)); // 1024

The minimum requirement of ES7 in this case is because the exponentiation operator was released with ES7.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.