In this article, we will discuss the new features added as standards to the ECMAScript in June 2016 in the version ECMAScript 2016. This time only 2 simple new features were added, which made this release a very small update as developers were doing just fine even without the new features.
So let's see what these new features are:
To find out whether an element exists in an array or not, what would you do? As of now, we used to use
.indexOf() function, which returns the index of the element in the array if present, else it returns -1.
// using indexOf() to find the index at which an element exists ['i', 'love', 'optimus', 'prime'].indexOf('love') // 1
To find out if an element exists in an array or not, the ideal way should be to have a function which returns True if the element exists and False if the element doesn't but as of now we were using
.indexOf() for this purpose, but not anymore.
.includes() function returns True if an element exists in an array, and returns False otherwise.
var coolCities = ['New York', 'New Delhi', 'Sydney'] coolCities.includes('Sydney') // true coolCities.includes('Karachi') // false, no offence
Array.prototype.includes( searchElement [ , fromIndex ] )
searchElement - The element that you want to search.
fromIndex (optional) - the index from where you want to search for the element in the array
.includes() method has some good enhancements over the
.indexOf() method, here are a few with code examples:
[NaN].indexOf(NaN) // -1 , this does not work [NaN].includes(NaN) // true, works just fine [1, , 3].indexOf(undefined) // -1, this too does not work [1, , 3].includes(undefined) // true, includes understands undefined
One more important fact about the .includes() method is that it searches in the ascending order, i.e. it starts from the beginning of the array.
This one is quite similar to the already popular ** operator in languages like Python etc, used for exponential operations. This operator works exactly like Math.pow()
x**y will return the result of x raised to the power y, for example:
2**2 // 4 2**'string' //NaN
And that's it, you now have upgraded your skill as per the latest ES7 release. In our next article, we will cover the ES8 features which were released in June 2017.