


The incudes() method doesn't work in IE and is only available in modern browsers. includes ( 29n ) // true // Symbolīoth includes() and indexOf() behave differently with NaN ("Not-a-Number") property: const arr = // ✅ includes ( undefined ) // true // boolean includes ( '🍊', 4 ) // falseīeside strings, the includes() method also works great with other primitive types: const symbol = Symbol ( '🌟' ) const types = // strings But you can also pass in a starting index as a second parameter to start the search from a different position: fruits. const fruits = īy default, the includes() method searches the entire array. The includes() method is perfect for finding whether the element exists or not as a simple boolean value. This method returns true if the element exists in the array, and false if not. The includes method is part of ES6 that can also be used to determine whether an array contains a specified item.

lastIndexOf ( '🍋', 4 ) // 1 (false)īoth indexOf() and lastIndexOf() perform a case-sensitive search and work in all browsers, including IE9 and up. You can also specify a second parameter to exclude items at the end. The lastIndexOf() starts searching the array from the end and stops at the beginning of the array. As the name suggests, it returns the position of the last occurrence of the items in an array. JavaScript provides us an alternate array method called lastIndexOf(). Note that if the item is present more than once, the indexOf() method returns the position of the first occurrence. But you can pass in a position as a second argument to skip the starting elements to be included in the search: fruits. indexOf ( '🍌' ) // -1 (false)īy default, the indexOf() method starts searching from the beginning of the array, and stops at the end of the array. This method searches the array for the given item and returns its index. The simplest and fastest way to check if an item is present in an array is by using the Array.indexOf() method. You can always use the for loop or Array.indexOf() method, but ES6 has added plenty of more useful methods to search through an array and find what you are looking for with ease. In JavaScript, there are multiple ways to check if an array includes an item.
