I am new to the typescript, and trying to learn the language
Below I have 2 objects I want to understand what is difference between them, they are definitely different as nothing is printed on console.
Code
let some = {'flag' : {copy : 'true'}};
let other = {'flag' : {"copy" : 'true'}};
if(some === other)
console.log("Same")
(Other variable have copy in quotes)
Also if I hover on to the "copy" attribute, IDE is showing string property in both cases.
CodePudding user response:
let some = {'flag' : {copy : 'true'}};
let other = {'flag' : {"copy" : 'true'}};
Your two objects, some
and other
are basically the same, but object comparison in JS will always return false. This is because the variables are not storing the objects, it's storing a reference to the object. This means that even if the objects have the same structure and the same values for every key, any equality comparison with both ==
and ===
will be false. The exception is when you're comparing the same object to itself, ie some === some
is true(as it should be).
You can read more about it here
As for your question about quotes around keys, that is the proper syntax for JSON objects. By that I mean, if you're writing something that will be parsed as JSON, then you should use double quotes around all your keys. If it's in JS, you can omit the quotes, in fact, prettier will usually remove the quotes even if you type them. In JS, both the objects above are functionally exactly the same.
One place you will need to use quotes is when your object keys have symbols like -
,
, spaces, etc.
const obj = {
"key with spaces": "value",
"Jan-Dec": "123"
}