HappyCoding HappyCoding - 3 months ago 13
Javascript Question

Comparison 2 objects if property is undefined



"use strict";
let obj1 = {
key: undefined
};

let obj2 = {
key: Symbol('')
};

// THIS SHOULD RETURN false
console.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // true





I've read the doc, they said: there is another way to compare 2 objects like that case exactly by using the replacer parameter. Just like:

let replacer = function (key, value) {
if (value === undefined) {
// do stuff...
} else if (value['__proto__'].constructor.name === 'Symbol') {
// do stuff...
} else {
// do stuff...
}

return value;
};


My question: is there another way that faster than using
replacer
like I just mention? I don't want to use that way cause of handling many things.

For example: if I have 20 functions like:
Symbol1()
,
Symbol2()
,
Symbol3()
...
Symbol20()
, I would re-use
if-else
statements many times.

rD. rD.
Answer

First, just see the documentation:

Description
To create a new primitive symbol, you write Symbol() with an optional string as its description:

var sym1 = Symbol();
var sym2 = Symbol("foo");
var sym3 = Symbol("foo");

The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time:

 

Symbols and JSON.stringify()

Symbol-keyed properties will be completely ignored when using JSON.stringify():

JSON.stringify({[Symbol("foo")]: "foo"});                 
// '{}'

Unlike conventional objects., your Symbol('AnyTextHere') won't return any text so that JSON.stringify could convert it into one. Nothing is being returned and so JSON.Stringify returns empty String for both the cases and so your answer is true everytime.


EDIT

Coming to your question, the Symbol() will always return a new symbol everytime, and so NO TWO SYMBOLS WILL BE EVER SAME, EVEN IF YOU PASS SAME PARAMETER.

And so I think there's no need to compare the entire Object, just compare the key with Symbol()

"use strict";
let obj1 = {
    key: undefined
};

let obj2 = {
    key: Symbol('')
};

let obj3 = {
    key: Symbol('')
};

// THIS SHOULD RETURN false
console.log(obj1.key === obj2.key); 
// false because Symbol() doesn't match undefined

console.log(obj2.key === obj2.key); 
// true because obj2.key is being compared with self

console.log(obj2.key === obj3.key); 
// false - NOTE that although the structure of obj2 and obj3 are same (COPIED AND PASTED)
// but since NO two Symbol() are same, and so the result is false