Check if a JS Array Contains a Specific Value
Given a JavaScript array, there are two built-in array methods you can use to determine whether the array contains a given element. Suppose you have a simple array with 3 elements:
const arr = ['A', 'B', 'C'];
To determine whether arr
contains the string 'B'
, you can use Array#includes()
or Array#indexOf()
.
includes()
The Array#includes()
function was introduced in ECMAScript 2016. It takes a parameter valueToFind
, and returns true
if some element in the array is equal to valueToFind
.
const arr = ['A', 'B', 'C'];
arr.includes('B'); // true
arr.includes('D'); // false
The Array#includes()
function checks for equality using the same
semantics as the ===
operator (no type coercion), with the exception
of NaN
. The Array#includes()
function will find NaN
in an array. The technical term for this equality check is sameValueZero
.
// Array contains 1 element, 'NaN'
const arr = [parseInt('foo')];
arr.includes(parseInt('foo')); // true
arr.includes(NaN); // true
arr.includes(Number.NaN); // true
// The `===` operator has some quirks with NaN. `Array#includes()`
// smooths out those rough edges.
arr[0] === NaN; // false
arr[0] === Number.NaN; // false
indexOf()
The Array#indexOf()
function is a common alternative to includes()
. The indexOf()
function returns the first index in the array at which it found valueToFind
, or -1
otherwise.
const arr = ['A', 'B', 'C'];
arr.indexOf('A'); // 0
arr.indexOf('B'); // 1
arr.indexOf('D'); // -1
// To check whether an array contains a given value, you should use the
// below check.
arr.indexOf('D') !== -1; // false
To check whether arr
contains v
, you would use arr.indexOf(v) !== -1
. In
some codebases, you may see ~arr.indexOf(v)
instead, where ~
is the
JavaScript bitwise NOT operator.
Given an integer v
, ~v === -(v + 1)
, so ~v === 0
only if v === -1
. This is a handy trick to avoid having to write out !== -1
.
However, using bitwise NOT is generally bad practice because it sacrifices
readability to save 4 characters.
const arr = ['A', 'B', 'C'];
if (~arr.indexOf('A')) {
// Runs
}
if (~arr.indexOf('D')) {
// Does not run
}
Unlike Array#includes()
, Array#indexOf()
uses the same semantics as the ===
operator to check for equality. In other words, Array#indexOf()
cannot find
NaN
in an array.
// Array contains 1 element, 'NaN'
const arr = [parseInt('foo')];
arr.indexOf(NaN); // -1
arr.indexOf(Number.NaN); // -1
Array#includes()
is generally the better choice, because you don't need to type out !== -1
and because it has slightly better equality semantics. But since Array#includes()
was introduced in ES2016, it is not supported in any version of Internet Explorer or Node.js versions before 6.0.0. If you use Array#includes()
, make sure you add a polyfill for older browsers.