JavaScript Array `includes()`

Oct 13, 2020

The Array#includes() method returns true if the array contains a given element, or false otherwise.

const arr = ['a', 'b', 'c'];

arr.includes('b'); // true
arr.includes('z'); // false
arr.includes(1); // false

Equality Comparison

The includes() method uses the "SameValueZero" algorithm for determining if two values are equal. For almost all cases, "SameValueZero" is equivalent to strict equality using ===. In particular, includes() does not do any type coercion.

const arr = ['1', '2', '3'];

arr.includes('1'); // true
arr.includes(1); // false

The includes() only treats two objects as equal if they are the same reference:

const obj1 = { name: 'Jean-Luc Picard' };
const obj2 = { name: 'Jean-Luc Picard' };

const arr = [obj1];

arr.includes(obj1); // true
arr.includes(obj2); // false

The only difference is how SameValueZero handles NaN. In JavaScript, NaN !== NaN. However, includes() can correctly find NaN and Number.NaN in an array.

const arr = [NaN];

arr.includes(NaN); // true
arr.includes(Number.NaN); // true

arr[0] === NaN; // false

Environment Support

The includes() method was introduced in ES2016, which makes it a relatively new feature. In particular, no version Internet Explorer supports includes(). If you expect your JavaScript to run in Internet Explorer or versions of Node.js before 5.0.0, you should use indexOf(), which enjoys better browser support and is equivalent except for NaN.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials