Corresponding 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's going on behind the scenes? does anyone know this?

+3


source to share


3 answers


An array versus another array is not the same because they point to different memory addresses.

But array versus string for equality ( b == c

), passes array to string; effectively, it does something similar to:



b.toString() === c

      

But with identity matching ( ===

) it will also check the type of both variables, in which case it b === c

will render as false

.

+3


source


Obviously, arrays are passed in comma-delimited strings compared to strings. [UPDATE: As Sawant correctly points out, it invokes an array method toString()

.] But arrays are simply arrays compared to 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 arrays with the elements they contain, use a function isEqual

from the lodash library.

+5


source


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

    a==b // false
    
          

  • Comparison of two strings, because an array versus a string will be passed to a string.

    b==c // true
    
          

  • Same as 2.

    c==a // true
    
          

When you compare with ==

, the interpreter will try to make the left and right sides the same type.

First it will format it to string -> number -> boolean

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

.

  • ![] == []

  • false == []

  • false == ""

  • false == false

These are the steps the interpreter must follow in order to come up with:

  ![] == [] // true

      

Because of all this, just use the operator ===

and it will be much faster.

+3


source







All Articles