Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Array.prototype.includes function compare objects

In ECMA Specs we read that Array.prototype.includes uses SameValueZero algorithm when comparing if an array includes given element. This algorithm, when the element is an Object, it uses SameValueNonNumeric algorithm which basically checks if types of compared elements are matching and finally, in the last point of the algorithm it checks:

If x and y are the same Object value, return true. Otherwise, return false.

My question :

How does SameValueNonNumeric algorithm performs the object comparison step? How does it establish that "x and y are the same Object value"? I couldn't find this in specs.

From this and this question it seems that object comparison is not so straightforward in JS.

like image 723
mtx Avatar asked Oct 18 '25 19:10

mtx


2 Answers

They are "the same Object value" if they refer to the same block of memory, if you will.

The non-straightforward questions and answers you find are all about how to compare object contents in a meaningful manner.

It is very simple to compare objects the "regular" way though, i.e. compare the reference, and that's what includes does here too. I agree that the text in SameValueNonNumber is a bit unclear at that point, other algorithms specify that more clearly such as here at step 1f:

Return true if x and y refer to the same object. Otherwise, return false.

So:

const a = { hello: 'world' }
const b = a
const c = { hello: 'world' }

// Now, a and b refer to the same object, but a/b and c do not.

console.log([a].includes(a)) // true
console.log([a].includes(b)) // true
console.log([a].includes(c)) // false
like image 55
CherryDT Avatar answered Oct 20 '25 09:10

CherryDT


Array.prototype.includes is not supposed to give you correct results for object check and is designed to work for Boolean, String and Number values

For an object it basically just does a reference check, so if the object contains same reference as the one in the array, it returns true else just will return false regardless of the values within the object

var arr = [{x: 1, y: 2}, {x: 2, y: 'as'}, {x: 'in', y: 'po'}];
console.log(arr.includes({x: 2, y: 'as'}));
console.log(arr.includes(arr[1]));

For object existence check you need to make use of Array.prototype.find and check for all values of object

like image 35
Shubham Khatri Avatar answered Oct 20 '25 10:10

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!