How to check if an array includes a value in JavaScript

Posted on

To check if an array includes a specific value in JavaScript, you can use several methods provided by the language’s array handling capabilities. One of the most straightforward methods is using the includes() method available on arrays since ES2016. This method checks whether a certain value exists within the array and returns true if found, otherwise false. It is useful for quickly determining the presence of a value without needing to iterate through the array manually. This approach is efficient and works well for arrays containing primitive values like strings or numbers.

Using the includes() Method

1. Basic Usage:
The includes() method checks whether an array includes a certain element, returning true or false. Here’s how you can use it:

   const array = [1, 2, 3, 4, 5];

   console.log(array.includes(3)); // Output: true
   console.log(array.includes(6)); // Output: false

In this example, array.includes(3) checks if the array array contains the value 3. Since 3 is present in the array, the method returns true. Conversely, array.includes(6) checks for the presence of 6, which is not in the array, so the method returns false.

2. Strict Equality Comparison:
By default, includes() uses strict equality (===) to check for the presence of the value. This means it not only checks for the value itself but also for the type. For example:

   const array = [1, '2', true];

   console.log(array.includes('2')); // Output: true
   console.log(array.includes(2));   // Output: false

In this case, array.includes('2') returns true because the array contains the string '2', even though the array also contains the number 1. array.includes(2), however, returns false because the array does not contain the number 2 (without quotes).

3. Checking for NaN:
includes() can also handle checking for NaN values, although NaN is a unique case due to its behavior in JavaScript:

   const array = [1, NaN, 3];

   console.log(array.includes(NaN)); // Output: true

Despite the fact that NaN is not strictly equal to itself (NaN !== NaN), includes() correctly identifies its presence in the array array.

Using indexOf() Method

1. Basic Usage of indexOf():
Before ES2016, the common way to check for the presence of a value in an array was using the indexOf() method, which returns the index of the first occurrence of a value within the array, or -1 if the value is not found:

   const array = ['apple', 'banana', 'cherry'];

   console.log(array.indexOf('banana')); // Output: 1
   console.log(array.indexOf('orange')); // Output: -1

In this example, array.indexOf('banana') returns 1 because 'banana' is located at index 1 in the array array. If the value 'orange' were checked instead, array.indexOf('orange') would return -1 indicating that 'orange' is not present in the array.

2. Checking from a Specific Index:
You can specify a starting index for the search within the array using indexOf(). This is useful when you want to find if a value exists after a certain position:

   const array = ['apple', 'banana', 'cherry', 'banana'];

   console.log(array.indexOf('banana', 2)); // Output: 3

Here, array.indexOf('banana', 2) starts searching for 'banana' from index 2, and finds it at index 3.

3. Using includes() with indexOf() for Older Browsers:
If you need to support older browsers that do not support includes(), you can combine indexOf() with a conditional check to achieve similar functionality:

   const array = ['apple', 'banana', 'cherry'];

   if (array.indexOf('banana') !== -1) {
       console.log('Array includes "banana"');
   } else {
       console.log('Array does not include "banana"');
   }

This approach checks if 'banana' exists in array by verifying if array.indexOf('banana') returns a value other than -1, indicating its presence in the array.

Using Array.prototype.some()

1. Array.some() Method:
Another alternative to check if an array includes a value is using the some() method, which tests whether at least one element in the array passes the test implemented by the provided function:

   const array = [10, 20, 30];

   const includesAbove20 = array.some(item => item > 20);
   console.log(includesAbove20); // Output: true

In this example, array.some(item => item > 20) checks if any element in array is greater than 20. Since 30 meets this condition, includesAbove20 is true.

2. Custom Condition with some():
some() allows you to define custom conditions based on specific criteria. For instance, to check for the presence of a substring in an array of strings:

   const array = ['apple', 'banana', 'cherry'];

   const includesSubstring = array.some(item => item.includes('an'));
   console.log(includesSubstring); // Output: true

Here, array.some(item => item.includes('an')) checks if any string in array includes the substring 'an'. Since both 'banana' and 'cherry' contain 'an', includesSubstring is true.

Using ES6 Set for Uniqueness

1. Using Set for Unique Values:
If the presence of unique values is critical, using Set can simplify the task of checking for their existence:

   const array = [1, 2, 3, 2, 1];

   const uniqueValues = new Set(array);
   console.log(uniqueValues.has(3)); // Output: true
   console.log(uniqueValues.has(4)); // Output: false

In this case, new Set(array) creates a set from array, ensuring all duplicate values are removed. The has() method then checks if 3 exists in the set, returning true, whereas 4 does not exist in the set, returning false.

Considerations and Best Practices

1. Performance Considerations:
When checking for the presence of a value in large arrays, consider the performance implications of different methods. Methods like includes() and some() offer efficient ways to search arrays compared to manual iterations or older methods like indexOf().

2. Type and Strict Equality:
Be mindful of JavaScript’s handling of types and strict equality (===) when using includes() and similar methods. Understand how they treat different data types, such as strings, numbers, and objects, to ensure accurate checks.

3. Browser Compatibility:
Ensure compatibility with target browsers and environments, especially when using newer methods like includes() that may not be supported in older browser versions. Consider polyfills or alternative approaches for broader compatibility.

4. Handling Edge Cases:
Account for edge cases such as NaN, empty arrays, or arrays containing undefined or null. Test edge cases to ensure your code behaves as expected and handles such scenarios gracefully.

5. Functional Programming Paradigm:
Methods like some() provide opportunities for functional programming paradigms by enabling concise and expressive code for array operations. Embrace these paradigms where appropriate to enhance code readability and maintainability.

By leveraging these methods and considerations, you can effectively determine if an array includes a specific value in JavaScript, accommodating various use cases and optimizing performance based on your application’s requirements and constraints.

👎 Dislike