Niraj Chauhan

Niraj Chauhan

#father #husband #SoftwareCraftsman #foodie #gamer #OnePiece #naruto

[] == [] is false, why? | JavaScript

Posted by on

I love javascript and its mystery, if you had to compare a set of two identical arrays the first thing in your mind would come is to compare using == operator. But in javascript the result will be different.

Just try it in your console a normal comparison of two identical arrays.

var x = [1, 2, 3];
var y = [1, 2, 3];
console.log(x == y);
console.log([] == []);
console.log([null] == [null]);

Above example will return false, now if you try this in ruby or any different server side language it will return true.

Now why is this happening, the way JavaScript works is different. JavaScript has two types of values Primitives and Objects. All Numbers, Strings, Boolean and Undefineds are primitives. Remaining are objects, array is a part of it. When you create an array, what you get is the instance of an Array class, so now when you compare the two arrays, instances are compared and not their values.

Arrays comparison might turn out to be slow if the array is deep, this might be the reason javascript doesn’t supports.

So to compare two identical arrays you can use lodash or a simple way would be to convert arrays into string and then check.

var x = [1, 2, 3];
var y = [1, 2, 3];
console.log(JSON.stringify(x) == JSON.stringify(y));