2

a = [1,2,3];

b = [[1,2,3],[4,5,6]];

Why is that in javascript a== b[0] return false?

Thank you

5
  • 1
    Because JS compares objects not by values, but by references. If you used google.com with "javascript compare arrays" query you would find a lot of useful info Commented Dec 10, 2013 at 2:02
  • 1
    Consider that [] == [] also returns false, because the arrays are different objects. There are plenty of ways to implement an array/object comparison function, you can use google for that. You could just use underscore and its _.isEqual() function. Commented Dec 10, 2013 at 2:04
  • stackoverflow.com/questions/7837456/…. Really good answer. Commented Dec 10, 2013 at 2:08
  • @Yogesh: which one? Your link points to a question Commented Dec 10, 2013 at 2:11
  • stackoverflow.com/a/14853974/933132. This one. Commented Dec 10, 2013 at 2:30

1 Answer 1

1

In javascript objects are compared by references.

That said: a references to objects are compared, not the objects' contents.

Thus, One object {} will never be equal to another {} even though their contents are equal.

var a = {},
    b = {}; // not equal

Whereas if you create a variable by assigning another reference to it like:

var a = {},
    b = a; // equal

then both variables would hold the same reference and would be equal.

Sign up to request clarification or add additional context in comments.

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.