NeuroAgent

JavaScript Array Contains: Check if Array Includes Value

Learn the most efficient ways to check if a JavaScript array contains a value. Discover Array.includes(), indexOf(), and some() methods with examples and performance comparisons.

Question

How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value?

This is the only way I know to do it:

javascript
function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question which addresses finding objects in an array using indexOf.

NeuroAgent

The most concise and efficient way to check if a JavaScript array includes a value is to use the Array.includes() method, which returns true if the array contains the specified value and false otherwise. This modern ES6+ method provides a clean, readable syntax that’s more efficient than manual loops and handles edge cases like NaN values correctly. For better browser compatibility, you can also use Array.indexOf() with an inequality check.

Contents

Using Array.includes() - The Modern Approach

The Array.includes() method is the most straightforward way to check if an array contains a value. It was introduced in ECMAScript 2016 (ES7) and provides a clean, readable syntax.

javascript
const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.includes('banana'); // true
const hasGrape = fruits.includes('grape');   // false

Key characteristics of includes():

  • Returns a boolean value (true or false)
  • Case-sensitive comparison
  • Uses strict equality (===) for comparison
  • Handles NaN values correctly
  • Works with sparse arrays

As Mozilla Developer Network explains, “The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.”

Using Array.indexOf() - Legacy Method

Before includes() was introduced, developers commonly used indexOf() to check for array membership. This method returns the index of the first occurrence of the specified value, or -1 if the value is not found.

javascript
const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.indexOf('banana') !== -1; // true
const hasGrape = fruits.indexOf('grape') !== -1;   // false

According to the official JavaScript documentation, “The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.”

Important limitation: indexOf() cannot detect NaN values because NaN !== NaN in JavaScript. This is a key difference from includes().

Using Array.some() for Complex Conditions

When you need to check for more complex conditions than simple equality, Array.some() is the perfect choice. This method tests whether at least one element in the array passes the test implemented by the provided function.

javascript
// Check if any number is greater than 10
const numbers = [4, 8, 15, 16, 23, 42];
const hasGreaterThan10 = numbers.some(num => num > 10); // true

// Check if array contains an object with specific property
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
];
const hasAdult = users.some(user => user.age >= 18); // true

As Stack Overflow demonstrates, “For checking if an array includes an object with a certain property, you can use some() with a callback function.”

Comparing Performance and Efficiency

When it comes to performance, different methods have different characteristics:

Method Performance Best For
includes() Fast, optimized Simple value checking (modern browsers)
indexOf() Fast, optimized Simple value checking (legacy support)
some() Slightly slower Complex conditions with callbacks
Custom loop Variable Very large arrays with early optimization

For most use cases, the built-in methods are highly optimized and will perform better than manual loops. The performance difference is usually negligible for small to medium arrays, but can matter for very large arrays.

According to Built In, “The performance differences between these methods are generally minimal for small arrays, but can become significant with large datasets.”


Handling Edge Cases

NaN Values

javascript
const arr = [1, 2, NaN, 4];
console.log(arr.includes(NaN)); // true
console.log(arr.indexOf(NaN));  // -1 (incorrect!)

Objects and References

javascript
const arr = [1, 2, { name: 'test' }];
const obj = { name: 'test' };
console.log(arr.includes(obj)); // false (different object references)
console.log(arr.some(item => item.name === 'test')); // true

Sparse Arrays

As MDN documentation notes, “When used on sparse arrays, the includes() method iterates empty slots as if they have the value undefined.”

javascript
const sparse = [1, , 3];
console.log(sparse.includes(undefined)); // true (empty slot treated as undefined)

Browser Compatibility and Polyfills

While includes() is widely supported in modern browsers, you may need polyfills for older environments:

javascript
// Polyfill for Array.includes()
if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement, fromIndex) {
    'use strict';
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    
    var o = Object(this);
    var len = o.length >>> 0;
    
    if (len === 0) {
      return false;
    }
    
    var n = fromIndex | 0;
    var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    
    while (k < len) {
      if (o[k] === searchElement) {
        return true;
      }
      k++;
    }
    
    return false;
  };
}

Best Practices and Recommendations

  1. Use includes() for simple value checking - It’s the most readable and modern approach
  2. Use indexOf() for legacy code - When you need maximum browser compatibility
  3. Use some() for complex conditions - When you need to match object properties or custom logic
  4. Avoid manual loops - Built-in methods are more efficient and readable
  5. Consider edge cases - Remember that indexOf() fails with NaN and objects

As Mastering JS summarizes, “For checking if an array contains a primitive value, use includes(). For checking if an array contains an object that matches a certain condition, use some().”

Sources

  1. JavaScript Array includes() Method - W3Schools
  2. How do I check if an array includes a value in JavaScript? - Stack Overflow
  3. Array.prototype.includes() - JavaScript | MDN
  4. JavaScript Array Contains: 6 Methods to Find a Value | Built In
  5. How do I check if an array includes a value in JavaScript? | Sentry
  6. Check if a JS Array Contains a Specific Value - Mastering JS
  7. JavaScript: Check if Array Contains a Value/Element - Stack Abuse
  8. How to check if array includes a value in JavaScript? | SamanthaMing.com

Conclusion

  • The Array.includes() method is the most concise and efficient way to check if an array contains a value in modern JavaScript
  • For browser compatibility, Array.indexOf() with !== -1 check is a reliable alternative
  • Use Array.some() when you need complex matching conditions or object property checks
  • Built-in methods are generally more efficient and readable than manual loops
  • Be aware of edge cases like NaN values and object references when choosing your method

Your custom function works perfectly fine, but the built-in methods provide better readability, performance, and consistency across different codebases. For most modern JavaScript development, includes() should be your default choice for simple value checking.