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
- MDN Web Docs: Math.pow
- MDN Web Docs: Exponentiation **
- w3schools: JS Assignment
- 2ality: Exponentiation Operator
- ExploringJS: Exponentiation operator
- TC39: Exponentiation Operator
- The Exponentiation Operator in JavaScript
- Exponentiation Operator
- Wikipedia: Infix Notation
Thanks for reading β€
Say Hello! Instagram | Twitter | Facebook | Medium | Blog
Top comments (0)