6.4 Array Methods

Add/Remove Items

Searching In A Array

indexOf/lastIndexOf and includes:

arr.includes(item, from) - looks for item starting from index from, returns true if found.

Example

let arr = [1, 0, false];

alert( arr.indexOf(0) ); // 1
alert( arr.indexOf(false) ); // 2
alert( arr.indexOf(null) ); // -1
alert( arr.includes(1) ); // true

<aside> 💡 Note that the methods use === comparison. So, if we look for false, it finds exactly false and not zero.

</aside>


If we want to check for inclusion, and don’t want to know the exact index, then arr.includes() is preferred.

Also, a very minor difference of includes is that it correctly handles NaN, unlike indexOf/lastIndexOf: