You can not compare complex structures like arrays and objects because the equality checking is actually looking at specific memory locations. Every time you create a new object or array, that variable is pointing to a new, unique place in memory. You would have to iterate through the keys/indices that hold primitive values and check each one for equality with your other structure.
Extra credit: the square and curly braces are called Array literals and Object literals. They are essentially syntactic sugar for new Array
or new Object
.
Additionally, the reason you can check equality on strings, booleans, and numbers is because each value of each type (true, false, 7, 'hello world', 'blue', 42
), actually points to a unique place in memory. For example: when you write
var str = 'yellow'
the variable str
is now pointing to a place in memory that is associated with the six characters that comprise the word ‘yellow’. This is the actual reason that equality checking is possible.
var str2 = 'yel' + 'low'
Results in the same combination of characters, which results in a reference to the same memory address as what str
’s valueOf function points to. Therefore:
str === str2 // true
I hope that helps. There’s much more down this rabbit hole, but this should get you started.