Array.indexOf() are both array methods used to search for an element within an array, but they have some differences in functionality and usage. Here are the key differences between them:
1. Return value:
Array.includes() returns a boolean value (true or
false) indicating whether the array includes the specified element.
Array.indexOf() returns the index of the first occurrence of the specified element in the array, or
-1 if the element is not found.
Array.includes() is primarily used to check if an array contains a specific element. It provides a simple and concise way to perform this check.
Array.indexOf() is more versatile and can be used to check if an element is present in an array and retrieve its index if it exists.
3. Strict equality comparison:
Array.includes() uses strict equality (===) to compare the elements. It checks for the presence of the specified element based on its value and type.
Array.indexOf() also uses strict equality (===) by default, but it allows you to provide a second parameter to specify a starting index for the search.
4. Support for NaN:
Array.includes() handles the
NaN value correctly. It can detect the presence of
NaN in an array.
Array.indexOf() does not handle
NaN correctly. It cannot reliably identify the index of
NaN within an array.
5. Return behavior:
Array.includes() immediately returns
true as soon as it finds a match. It does not continue searching for additional occurrences.
Array.indexOf() returns the index of the first occurrence found. If you need to find all occurrences, you can use a loop or other techniques.
Here are some examples that demonstrate the differences:
1 2 3 4 5 6 7 8 9 10
const array = [1, 2, 3, NaN, 'hello']; console.log(array.includes(2)); // Output: true console.log(array.includes(4)); // Output: false console.log(array.includes(NaN)); // Output: true console.log(array.indexOf(2)); // Output: 1 console.log(array.indexOf(4)); // Output: -1 console.log(array.indexOf(NaN)); // Output: -1
In this example,
true because the element
2 is present in the array.
4 is not present.
NaN is considered to be present in the array.
1 as the index of the first occurrence of
4 is not found.
array.indexOf(NaN) also returns
indexOf() cannot correctly identify the index of
Choose the appropriate method based on your specific use case. If you only need to check if an element exists in an array,
Array.includes() provides a simpler and more expressive syntax. If you require the index of the element or need to handle special cases like
Array.indexOf() is more suitable.