Does JavaScript Array.includes() Do Strict Comparison?

Find out how Array.includes() compares values

You could technically say that the JavaScript Array.prototype.includes() method does a strict equality comparison of values. However, in a stricter sense, the "strict equality comparison" differs from the (Same-Value-Zero) algorithm Array.prototype.includes() method uses under the hood in terms of NaN equality. For example:

// ES7+
console.log([NaN].includes(NaN)); // true

console.log(NaN === NaN); // false

Other than that one exception, Same-Value-Zero algorithm and strict equality actually yield the same result. This means, for example, that a numeric string won't equal its integer counterpart:

// ES7+
console.log([1].includes('1')); // false
console.log(['1'].includes(1)); // false

This is the same as it would happen in a strict equals (===) comparison:

console.log(1 === '1'); // false

Similarly, in the following cases, Array.prototype.includes() does a "strict equality comparison":

// ES7+
console.log([1, 2, 3].includes(2)); // true
console.log([1, 2, 3].includes(4)); // false

console.log([1, 2, -0].includes(+0)); // true
console.log([1, 2, +0].includes(-0)); // true

console.log(['foo', 'bar', 'baz'].includes('foo')); // true
console.log(['foo', 'bar', 'baz'].includes('Foo')); // false
console.log(['foo', 'bar', 'baz'].includes('fo')); // false

Hope you found this post useful. It was published . Please show your love and support by sharing this post.