2

a = [1,2,3];

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

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

Thank you

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
user2393426
  • 165
  • 1
  • 10
  • 1
    Because JS compares objects not by values, but by references. If you used http://google.com with "javascript compare arrays" query you would find a lot of useful info – zerkms Dec 10 '13 at 02: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()`](http://underscorejs.org/#isEqual) function. – sbking Dec 10 '13 at 02:04
  • http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript. Really good answer. – Yogesh Dec 10 '13 at 02:08
  • @Yogesh: which one? Your link points to a question – zerkms Dec 10 '13 at 02:11
  • http://stackoverflow.com/a/14853974/933132. This one. – Yogesh Dec 10 '13 at 02:30

1 Answers1

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.

zerkms
  • 249,484
  • 69
  • 436
  • 539