Does JavaScript Array.includes() Do Strict Comparison?

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.