Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is eval('{}=={}') an error when eval('[]==[]') is not?

Tags:

javascript

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?

like image 895
Samuel Danielson Avatar asked Aug 04 '16 16:08

Samuel Danielson


1 Answers

Overview

Well, within JavaScript, every Object is different. Anytime an object comes into play, it will never ==/=== another object. Even if they are identical

Examples

{}=={} // false

[]==[] // false

[1][0]==[1][0] // true

{id: 1}.id=={id: 1}.id // true

Ways to get around this

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.
like image 112
awesomemaker3000 Avatar answered Sep 29 '22 13:09

awesomemaker3000