ECMA2016: Array.prototype.includes

One of the features, proposed as part of ECMAScript2016 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.

[10, 20, 30].indexOf(30) >= 0	//returns true

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

[10, 20, 30].includes(30)		//returns true

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:

[10, 20, 30].includes(30) 	 		//returns true
[10, 20, 30].includes(30, 1) 			// returns true
[10, 20, 30].includes(0)			//return false
[10, 20, 30].includes(30,3) 			//returns false
[10, 20, 30].includes(3,3) 			//returns false

But there are few differences from indexOf, for example:

NaN can be searched using includes

[10, 20, NaN].includes(NaN)	//returns true
[10, 20, NaN].indexOf(NaN)	        //return false

Left out values are treated as undefined by includes

[10,,].includes(undefined)	//returns true
[10,,].indexOf(undefined)	//returns false 

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.

[{'a':1},{'a':2},{'a':3}].includes({'a':1}) 	//returns false
[[10],[20],[30]].includes([2]) 			//returns false

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.

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

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

Advertisements