I am writing a minigame about javascript thruthiness and I found something strange.
eval('{}=={}') // error
{}=={} // false in the console but is an error in a source file
eval('[]==[]') // no error => false
eval('{}') // no error => undefined
eval('({})') // no error => Object
eval('[]') // no error => Array
Why is eval('{}=={}') an error and why is evaling things containing {} so inconsistent?
Well, within JavaScript, every Object
is different. Anytime an object comes into play, it will never ==
/===
another object. Even if they are identical
{}=={} // false
[]==[] // false
[1][0]==[1][0] // true
{id: 1}.id=={id: 1}.id // true
One way is to use JSON.stringify
to get the string value of whatever argument is given
// Option 1
JSON.stringify({}) == JSON.stringify({}) // true
JSON.stringify([]) == JSON.stringify([]) // true
Another way is to use this function I created that compares two objects/arrays/strings/etc
// Option 2
Object.prototype.forEach = function forEach(callback) {
for (i in this) {
if (!this.hasOwnProperty(i)) continue;
callback(i, this[i])
}
}
Object.equals = function equals(obj1,obj2) {
var match = true;
if (typeof obj1 !== typeof obj2) {
return false;
} else if (typeof obj1 !== "object" && typeof obj2 !== "object") {
return obj1 === obj2;
} else if (JSON.stringify(obj1) == JSON.stringify(obj2)) {
return true;
}
obj1.forEach((value,key) => {
console.log(key, value)
if (obj2[key] !== value) {
match = false;
return;
}
})
return match;
}
Object.equals({},{}) // true
Object.equals("hello","goodbye") // false
Object.equals([],{}) // true because both of these different items are empty instances of objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With