3

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 ?

9

3 Answers 3

5

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.

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

Comments

3

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.

Comments

3
  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.

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.