0

Lets take two arrays

var apple = [1,2,3];
var bracket = [1,2,3];

and a string cat here with the same contents as the initial 2 arrays with no difference except comma (,)

var cat = "1,2,3";

Now lets test the equality between the 2 arrays with the following code.

 if(apple == bracket){
        console.log("Both are equal");
    }
    else{
        console.log("Both are not equal");
 }

Everyone including me would have guessed it would print Both are equal.But the opposite is true.It prints Both are not equal.How is this possible.

Here is more surprice

if(apple == cat){
    console.log("Both are equal");
}
else{
    console.log("Both are not equal");
}

Here also the otherway the output comes,it would print Both are equal.

SaiKiran
  • 6,244
  • 11
  • 43
  • 76
  • FYI, the reason your second comparison seemed to work is that when you compare a *string* with an *array*, the array is coerced to a string. When you coerce an array to a string, each of its elements is coerced to string and then they're joined up into one string with `,` in-between. So `[1, 2, 3] == "1,2,3"` is true because `String([1, 2, 3])` gives you `"1,2,3"`. Note that `[1, 2, 3] === "1,2,3"` would be false, because `===` doesn't do type coercion. – T.J. Crowder Jun 26 '16 at 18:00
  • `==` where the operands are arrays doesn't check if the elements are the same, but if the reference (the object) is the same. – pushkin Jun 26 '16 at 18:01
  • _If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.[Ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators)_ – Rayon Jun 26 '16 at 18:09
  • The arrays might be *similar*, but they're not the *same*. The `==` equality operator checks for the latter on objects. – Bergi Jun 26 '16 at 20:42

0 Answers0