One of the features, proposed as part of ECMAScript2016 specifications is, Array.prototype.includes  method. This method searches the passed element, inside the array. This was highly requested by developers, as, without that, the solution used was to use, Array.prototype.indexOf . The primary purpose of indexOf is to get the index value of first occurrence of the element and return the index value. To deduce whether the element is present in array or not, the returned value is then compared to some integer, resulting in indirect approach to achieve that.

Array.prototype.includes , provides the direct result for element’s presence.

This method takes two arguments the element to search and the starting index of the array from where the search begins. It works similar to indexOf in almost all the cases, for example:

But there are few differences from indexOf, for example:

NaN can be searched using includes

Left out values are treated as undefined by includes

The more logical name for this method could have been “contains” or “has”. But apparently, inside lots of other libraries, the name “contains” as already been defined in Array.prototype so using same name would conflict with existing definition. The “has” method is mostly used with respect to keys (in object and sets) and includes method searches value not the key.

Array.prototype.includes  works only with primitive values and not with objects.

This seems little different from String.prototype.includes , proposed in ECMAScript 2015, which takes the search element as string as well and not only as chars. The difference can be justified with their indexOf counterparts i.e. String.prototype.includes  is related to Array.prototype.includes  in similar way as String.prototype.indexOf  to Array.prototype.indexOf .

The more examples can be tried out from the polyfills present here. I have created following pen, using that polyfill.

See the Pen Array.prototype.includes by Pankaj Kumar (@pankajkumar005) on CodePen.0

References:
https://github.com/tc39/Array.prototype.includes/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Published originally at:
https://pankajkumar005.wordpress.com/2016/05/11/ecma2016-array-prototype-includes/

Similar reads:
http://www.2ality.com/2016/02/array-prototype-includes.html