DEV Community

Cover image for Exponentiation in JavaScript: A Beginner’s Guide

Exponentiation in JavaScript: A Beginner’s Guide

Mohamed Mayallo on June 24, 2023

Introduction Exponentiation refers to a mathematical process of multiplying a number by itself, raised to the power of another number. ...
Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • • Edited

There is one big difference between them. Math.pow only works for regular numbers. ** also works for BigInts.

To quote the MDN page on **:

The ** operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt exponentiation if both operands becomes BigInts; otherwise, it performs number exponentiation. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • • Edited

Actually, there are no big differences between Math.pow() and the ** operator.

You're wrong, there is one big difference Math.pow() works only on number but ** operator works also for BigInt.

Image description

Collapse
 
mayallo profile image
Mohamed Mayallo •

Yes you are right, I meant a big difference for the daily basis work.
Anyway, I am going to add this tip.

Collapse
 
pchol22 profile image
Pierre Chollet •

Nice!

Also good to know, contrary to what some people may think, the ^ operator isn't exponentiation at all (it is sometimes used as such, for example in the google calculator), its a XOR operator and will yield totally different results!

Collapse
 
mayallo profile image
Mohamed Mayallo •

Thanks, good tip!

Collapse
 
not-ethan profile image
Ethan •

Never knew they added a Math function for exponents. IMO using ** is better since its like that in other langues like Python, Ruby and probably others. Though Math.pow() is also used in Java and they dont have **

Collapse
 
mayallo profile image
Mohamed Mayallo •

Agree with you, ** is better and easier.

Collapse
 
ant_f_dev profile image
Anthony Fung •

Thanks for sharing - I knew about Math.pow(), but not about **.

Collapse
 
mayallo profile image
Mohamed Mayallo •

Glad to know it helps!

Collapse
 
ryencode profile image
Ryan Brown •

Also of note would be that performance wise these two methods seem to be equal (within a small margin)

Math.pow vs ** vs *

Collapse
 
philipjohnbasile profile image
Philip John Basile •

Neat!