2

I had always wondered why this :

var a = [[0, 1]];
a[0] == [0, 1];

would return false. It seems like these 2 arrays, a[0] and [0, 1], despite not being the same instance of Array, ARE actually the same object, in so far as all their properties are the same. This is not the case in JS though and I don't know why.

Which test applied to these two arrays, and to much more complicated objects, would return true ? (answers from jQuery and D3.js are accepted, I don't plan on using any other)

Edit: wrapping the objects with JSON.stringify seems to work; are there any caveats I should be aware of though?

5

2 Answers 2

2

[Equal Operator] "If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory."

See: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators

So, even:

[0, 1] == [0, 1]

Will returns false, because they are different objects, even if with the same content.

If it's confuse you using the array literals, notice that the code above is exactly the same of the follow:

new Array(0, 1) == new Array(0, 1);
Sign up to request clarification or add additional context in comments.

Comments

0

The two objects have the same value but are not the same object, for example if you push a new element to one the other will not get that new pushed element.

var a = [[0, 1]];
var b = [0, 1];
a[0].push(42);
alert(a[0].length);   // now it's 3
alert(b.length);      // still 2

Note also that the syntax [0, 1] is not representing an array object, but it's an array object "builder" that will produce a new fresh array each time it's evaluated:

function mkarr() {
    return [0, 1];
}

var a = mkarr();
var b = mkarr();
a.push(42);
alert(a.length);        // 3
alert(b.length);        // still 2
alert(mkarr().length);  // still 2 too

For numbers and strings instead equality matches because the referenced objects are immutable (i.e. you can make your variable to point to another number, but you cannot change the number itself).

Calling JSON.stringify on an object you get a string representation of the object, not the object... and the representations can indeed match equal for different objects (because they're just strings).

Note that the string representation doesn't really capture the object, and you can have substantially different objects with the same identical string representation... for example:

var a = [0, 1];
var b = [a, a];
var c = [[0, 1], [0, 1]];
alert(JSON.stringify(b) == JSON.stringify(c)); // true
b[0].push(42);
c[0].push(42);
alert(JSON.stringify(b)); // "[[0,1,42],[0,1,42]]"
alert(JSON.stringify(c)); // "[[0,1,42],[0,1]]"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.