Skip to content Skip to sidebar Skip to footer

Weird Behavior Of Comparison Operator Javascript When Using Empty Array

Can you explain this weird JavaScript behavior? First : [] === [] false [] == [] false Why false? The object are identical, thus it should return true. Second : [] !== []

Solution 1:

They're not identical. Object identity is defined by both operands pointing to the same instance.

var a = [],
    b = [];
a == b; //false
a == a; //true

Two literals always evaluate to two different instances, which are not considered equal. If you are looking for structural equivalence, see How to compare arrays in JavaScript?.

Solution 2:

Objects are not identical. In this case you compare the references to the objects. Easily speaking you compare the addresses in memory where these objects are located. This rule doesn't relate to primitives where you compare the actual values.

Post a Comment for "Weird Behavior Of Comparison Operator Javascript When Using Empty Array"