DEV Community

Samantha Ming
Samantha Ming

Posted on

11 2

Exponentiation Operator in JavaScript

Code Tidbit by SamanthaMing.com

I always found the old way of writing an exponentiation expression a bit awkward. Luckily, the exponentiation operator was introduced. This syntax also makes it more similar to other languages (ie. Ruby, Python). Cool πŸ‘

// Old way
const old = Math.pow(3, 7);
// 2187

// βœ… ES7 way 
const es7 = 3 ** 7;
// 2187

Infix Notation

The use of ** is called infix notation. It is characterized by the placement of operators between operands. Other popular infix notations include: + or -.

The reason this syntax was introduced is because:

Infix notation is more succinct than function notation, which makes it more preferable

Exponentiation in Other Languages

Also, you will notice this syntax is very similar to other languages:

// Python
a ** b

// Ruby
a ** b

// Perl
a ** b

// F#
a ** b

I actually like that it's similar to other languages. Because it makes picking up JavaScript a lot of easier for those folks and they can be up and running very quickly.

Assignment Operator

You must have seen arithmetic operator combined with the assignment operator. For example +=:

a += b

// Same as
// a = a + b

Well, similarly, this can also be done with the exponentiation operator. **=:

a **= b

// Same as
// a = a ** b

Negative Base

There's one bit of a gotcha. When you have a negative base, you will have to wrap it around parenthesis.

// ❌ Syntax Error
const wrong = -3 ** 7;

// βœ…
const correct = (-3) ** 7;

However, this isn't an issue if you use the older function way.

const works = Math.pow(-3, 7);

Resources


Thanks for reading ❀
Say Hello! Instagram | Twitter | Facebook | Medium | Blog

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more