Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test reference equality in Javascript?

Tags:

javascript

I have an array containing references to various objects.
The only guarantee I have is that the array does not contain multiple references to the same object.
Specifically, I am not guaranteed that the objects' contents are different.

There is another piece of code which gives me a reference to some object, obj.
I need to test if obj is the last item in my array, and if this is true, and obj satisfies some additional requirements, I want to call pop on my array.

How do I test if obj was the last item in my array?

like image 322
user541686 Avatar asked Aug 03 '13 21:08

user541686


1 Answers

In JavaScript, === (and, actually, ==) with object references tests reference equality (e.g., that they refer to the same object).

So to handle the requirement

There is another piece of code which gives me a reference to some object, obj. I need to test if obj is the last item in my array

...then:

if (obj === array[array.length-1]) {
    // It's the same object
}
like image 107
T.J. Crowder Avatar answered Sep 19 '22 01:09

T.J. Crowder