dkjain
dkjain

Reputation: 881

Object variables comparison in Javascript's HTMLCollection

var elem1, elem2;

// document.forms is an HTMLCollection

elem1 = document.forms[0];
elem2 = document.forms.item(0);

alert(elem1 === elem2); // shows: "true"

elem1 = document.forms["myForm"];
elem2 = document.forms.namedItem("myForm");

alert(elem1 === elem2); // shows: "true"

Src: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

In the above code variables elem1 and elem2 both hold same object, i.e. a DOM node

I would like to know, In the statement elem1 === elem2 what is actually being compared so that it evaluates to a TRUE expression. Is it nodeType, nodeValue or nodeName ?

Upvotes: 0

Views: 208

Answers (2)

MaxArt
MaxArt

Reputation: 22637

No property is actually compared. elem1 and elem2 are references to objects, and it happens that both variables point to the same object.

You could have used == too, in this case. === additionally checks for the type of the argument.

Upvotes: 2

SLaks
SLaks

Reputation: 887867

None of the above.

The === operator checks for reference equality.
It will only ever return true if both expressions refer to the same object.

Upvotes: 4

Related Questions