The ES2016 Guide
By Flavio Copes
Discover the two features added in ES2016 (ES7): Array.prototype.includes for cleanly checking if an array contains a value, and the exponentiation operator.
ES2016, officially known as ECMAScript 2016, was finalized in June 2016.
Compared to ES2015, ES2016 is a tiny release for JavaScript, containing just two features:
- Array.prototype.includes
- Exponentiation Operator
Why so small? ES2016 was the first release of the new yearly process. Instead of waiting years for a huge release like ES2015, TC39 (the committee that evolves JavaScript) now ships whatever is ready, every year. In 2016, two features were ready.
Array.prototype.includes()
This feature introduces a more readable syntax for checking if an array contains an element.
With ES6 and lower, to check if an array contained an element you had to use indexOf, which checks the index in the array, and returns -1 if the element is not there.
Since -1 is evaluated as a true value, you could not do for example
if (![1, 2].indexOf(3)) {
console.log('Not found')
}
indexOf(3) returns -1 here, and !-1 is false, so the check fails silently. You had to write indexOf(3) === -1, which works but doesn’t read well.
With this feature introduced in ES2016 we can do
if (![1, 2].includes(3)) {
console.log('Not found')
}
includes() returns true or false, so it fits naturally into conditions.
It also accepts a second argument, the index to start searching from:
const numbers = [1, 2, 3]
numbers.includes(3, 1) // true
numbers.includes(1, 1) // false
One behavior difference is worth knowing: includes() finds NaN, while indexOf() does not:
const values = [1, NaN]
values.includes(NaN) // true
values.indexOf(NaN) // -1
Exponentiation Operator
The exponentiation operator ** is the equivalent of Math.pow(), but brought into the language instead of being a library function.
Math.pow(4, 2) === 4 ** 2 // true
This feature is a nice addition for math intensive JS applications.
Unlike most operators, ** is right-associative. Chained exponents evaluate from right to left:
2 ** 3 ** 2 // 512, same as 2 ** (3 ** 2)
Be careful with negative bases. Writing -2 ** 2 is a syntax error, because it’s ambiguous. You must add parentheses to say what you mean:
(-2) ** 2 // 4
ES2016 also added the compound assignment version of the operator:
let size = 2
size **= 3 // size is now 8
The ** operator is standardized across many languages including Python, Ruby, MATLAB, Lua, Perl and many others.
Related posts about js: