What are the differences between JavaScript's Array.includes() and Array.indexOf() methods when searching for values in arrays?
Richard W
TheArray.includes() andArray.indexOf() methods in JavaScript serve similar purposes, but there are some key differences between them.
1. Return Value:
-Array.includes() returns a boolean value (true orfalse) indicating whether the array contains the specified value.
-Array.indexOf() returns the index of the first occurrence of the specified value in the array. If the value is not found, it returns -1.
2. Usage:
-Array.includes() is primarily used to check if an array contains a specific value. It provides a concise and readable way to perform this check.
-Array.indexOf() is used to find the index of a specific value in an array. It can also be used to check if an array contains a value by checking if the returned index is greater than or equal to 0.
3. Comparison:
-Array.includes() performs a strict equality (===) comparison to check for the presence of a value in the array.
-Array.indexOf() performs a strict equality comparison (===) for most cases. However, if the value being searched for is an object, it uses theSameValueZero algorithm, which compares object references instead of the object's contents.
4. Search from a specific index:
-Array.includes() does not provide an option to specify the starting index for the search. It always searches the entire array.
-Array.indexOf() accepts an optional second parameter that specifies the starting index for the search. It allows you to search for a value starting from a specific position within the array.
5. Support in Older Browsers:
-Array.includes() was introduced in ECMAScript 2016 and may not be supported in older browsers. If you need to support older environments, you may need to use a polyfill or an alternative approach.
-Array.indexOf() has been available since the early versions of JavaScript and is widely supported in all major browsers.
Here's an example that demonstrates the differences betweenArray.includes() andArray.indexOf():
In the above example,numbers is an array of numbers.Array.includes() is used to check if the array contains the values 3 and 6. It returnstrue for 3 since it is present in the array, andfalse for 6 since it is not present.Array.indexOf() is used to find the index of the values 3 and 6. It returns 2 for 3 since it is found at index 2, and -1 for 6 since it is not found in the array.
In general, if you need to simply check if an array contains a value,Array.includes() is a concise and straightforward choice. If you need to find the index of a value or if you require more control over the search process,Array.indexOf() is more suitable.