If the key you need is a noun without spaces, you can use either method to call it. If there is a space, you can only use [] to access it. The advantage of using [] is that you can also use variables and expressions to generate the key name:
console.log("These are the same:")
console.log(foo.word); // "string"
console.log(foo["word"]); // "string"
console.log(foo["wo" + "rd"]); // "string"
const w = "word";
console.log(foo[w]); // "string"
If the key is a number, then you can only use [] to access it:
console.log("And these are the same:")
console.log(foo[5]); // "number"
console.log(foo[2 + 3]); // "number"
const n = 13 - 8;
console.log(foo[n]) // "number"
If you call foo.user.name, it will look for an object called āuserā inside āfooā, then look for a variable called ānameā inside that object, and return the associated value. If you call foo[user.name], it will first find the value of āuser.nameā for some object called āuserā, then look for a variable inside āfooā with that name:
console.log("But these are different:")
const user = {
name: "Bob"
};
console.log(foo.user.name); // "Frank"
console.log(foo[user.name]); // foo["Bob"]=="A palindrome"
Thanks a lot for explaining it clearly!
I need sometime to digest it, but so far based on my understanding with your example above is that foo.user.name isnāt equal to foo[user.name] yeah?
Thatās right. When you use foo.user.name, it first looks for something inside foo called user, then it looks for something inside foo.user that is called name. In my example, foo.user.name is āFrankā. When you use foo[user.name], it looks for an object outside of foo called user, then it returns the variable called name inside it. In my example, user.name is āBobā. Once it has āBobā, it looks for foo["Bob"], which is the same as foo.Bob. In other words, it returns the variable called Bob inside foo. In my example, that is āA palindromeā.
Consider another example in which the object we are trying to read does not contain any objects named user:
const friends = {
Sam: "My best friend.",
Max: "Mostly okay."
};
const user = {
name: "Sam",
age: 27
};
console.log(friends["Sam"]);
console.log(friends.Sam);
console.log(friends[user.name]);
console.log(friends.user.name);
The first three lines in the console will be the same: āMy best friend.ā The last line will be an error, because friends.user does not exist, so it is impossible to read the variable name from it.