2

How does === operator work for objects in JavaScript? I want to know this because I want to know what is the cost of doing (ObjectA === ObjectB)? Since array.indexOf() uses === to compare objects and return index does it become a costly operation? (Here array is an array of objects.) I read this but couldn't understand much.

Achyut Rastogi
  • 1,335
  • 2
  • 11
  • 15
  • 6
    Objects in Javascript are compared by reference, not by value, so it's not expensive in terms of lookup. The `===` operator improves on the `==` operator in only one regard, namely it prevents type conversion before checking for equality. Not sure what else you want to know, exactly. – Akshat Mahajan Apr 05 '16 at 07:48
  • 2
    and two different object can't be equal `{} === {} // false`. – Jai Apr 05 '16 at 07:50
  • This might help: http://stackoverflow.com/questions/1068834/object-comparison-in-javascript – Rajesh Apr 05 '16 at 07:51
  • The cost of array.indexOf is not in the comparison, but in the scan/search. – MarcoL Apr 05 '16 at 08:35

3 Answers3

1

I want to know what is the cost of doing (ObjectA === ObjectB)

It's approximately the same as the cost of doing 1 === 1.

Even if this were an expensive operation, which it's not (at all), what else would you do? If you want to compare, you have to compare.

1

The cost in terms of complexity is certainly O(1), as it might be critical at some point. Array.indexOf is O(n), but don't worry, you won't get a quadratic complexity for comparing n times some objects.

On the other hand, you have to keep in mind that using n times Array.indexOf is actually quadratic.

As a guideline, I generally forbid myself using Array.indexOf in a loop, and find a way to use a hash instead.

axelduch
  • 10,769
  • 2
  • 31
  • 50
0

From MDN

Strict equal (===) Returns true if the operands are equal and of the same type. See also Object.is and sameness in JS.

From Tests

There is no way to say exactly what the complexity of the operation itself is without looking at the implementation, but as a general norm its taken as O(1) (until someone proves otherwise).

If you are looking to see if two objects are equal, i.e. are both reference to the same object === is the fastest when objects are same. I have the tests done here and here. enter image description here

So ObjectA === ObjectB takes as much time as d = 1 + 1. So I think its safe to say that its a O(1) complexity operation and happens by the comparison of the respective objectIDs of the objects in question.enter image description here

Achyut Rastogi
  • 1,335
  • 2
  • 11
  • 15