gauravmehla
gauravmehla

Reputation: 706

Matching array in JavaScript

I was playing with javaScript and found something confusing..

var a = [1,2,3];
var b = [1,2,3];
var c = '1,2,3';

a==b // false
b==c // true
c==a // true

What is happening behind the scenes ? anybody know that ?

Upvotes: 3

Views: 149

Answers (3)

webdeb
webdeb

Reputation: 13211

  1. Comparing two objects (array), they are not the same!

    a==b // false
    
  2. Comparing two strings, because an array compared to a string, will be casted to a string.

    b==c // true
    
  3. The same as 2.

    c==a // true
    

When you compare with == the interpreter will try to make left-hand-side and right-hand-side the same type.

It will first format it to a string -> number -> boolean

So for example, comparing ![] == [].

  1. ![] == []
  2. false == []
  3. false == ""
  4. false == false

This are the steps the interpreter has to perform to come up with:

  ![] == [] // true

Because of all this, just use always the === operator, and it will be also much faster.

Upvotes: 3

Sawant
Sawant

Reputation: 4526

Array compared to another array is not the same because they are pointing at different memory addresses.

But an array compared to a string for equality (b == c), casts the array to a string; effectively, it's doing something similar to:

b.toString() === c

But with an identity comparison (===), it will also check the type of both variables, in which case b === c will render as false.

Upvotes: 3

David L. Walsh
David L. Walsh

Reputation: 24818

Evidently arrays get cast to comma delimited strings when compared to strings. [UPDATE: as Sawant correctly states, it's calling the array's toString() method.] But arrays compared to arrays simply remain as arrays, and only the same instance will be equal to itself.

This is a good reason why you should always use === and never use ==.

If you need to compare the arrays by the elements they contain, use the isEqual function from the lodash library.

Upvotes: 5

Related Questions