1.) When defining objects, sometimes people put quotations around the key and sometimes they don't. What significance does this have? If
there are no quotations around the key value is it still considered a
string?
2.) When accessing properties of objects, sometimes people put quotations around the key and sometimes not. What is the significance
of this?
All valid keys are interpreted by the system as strings regardless of whether they are in quotes or not and regardless of what the key actually is. Even a key of 1
would be processed as "1"
and you can see this in your browser's debugger, so it's not about making the key a string or not. It's simply about whether the key name is valid syntax without them. For example, most people would say that a property (key) name can't contain spaces:
let obj = {
my property : "foo"
};
But, that's not true. It's just the un-quoted key names that contain a space is invalid syntax. You can do it with quotes:
let obj = {
"my property" : "foo"
};
// Then, you access the property through array-like syntax
console.log(obj["my property"]);
3.) What practical differences are there between myObj[key] and myObj.key? There have been a few scenarios in which one is necessary
over the other but I'm not sure why.
Syntax. In the above example, it would be invalid syntax to try either of these:
obj.my property
obj."my property"
But, if you access keys using array-like syntax, you would have to pass in the index and in that case strings are legal syntax:
obj["my property"]
4.) Why doesn't this work:
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
Without quotes around the index values, the system believes that what you are passing are variables, so it attempts to get the values out of the variables. It would work if the values you are passing in were declared variables that have values and those values mapped to existing keys in the object.
let myObj = {
full : null,
first : "Scott",
last : "Marcus"
};
let fullName = "full";
let firstName = "first";
let lastName = "last";
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
console.log(myObj[fullName]);