Problem:
I cannot understand that why in this lesson my solution is not working with bracket notation but working with dot notation. Can u help me understand this in easy wording??? solutions is given below.
MY Solution:
function addFriend(userObj, friend) {
// change code below this line
userObj[data][friends].push(friend);
return userObj[data][friends];
// change code above this line
}
REAL Solution:
function addFriend(userObj, friend) {
// change code below this line
userObj.data.friends.push(friend);
return userObj.data.friends;
// change code above this line
}
You use brackets when you refer to a property in an object using a variable (the value in the brackets is a variable).
userObj[data][friends].push(friend);
This means that data is a variable that has been set to a value and that value is the name of a property in userObj. But here are no variables named data or friends in your function. When you run your code, look at the error messages produced in the console below the editor:
ReferenceError: data is not defined
This means that there is no variable named data.
You use dot notation when you are referring directly to a property name without using a variable.
userObj.data.friends.push(friend);
This means that userObj has a property named data and that property is an object which has a property named friends.
Remember, whenever we use bracket notation, we use with quotes for property names which have spaces between them (although we can use it for single word names). If it’s variable, we simply write it without using quotes.
What you’ve written above says it’s variable so make it a property name by using quotes.
Now try using below code :
function addFriend(userObj, friend) {
// Only change code below this line
userObj["data"]["friends"].push(friend);
return userObj["data"]["friends"];
// Only change code above this line
}
And also remember, we use dot notation for single word properties only and not even for variables.
Yes, this is a good point, you can also use names in brackets, I just wanted to keep it simple so I didn’t mention this. My experience is that most people would use dot notation with names though, not brackets.
Ok…
I was having good knowledge about diff btw dot & bracket notation but couldn’t notice that I am using the bracket notation without quotes which is causing an error and I was passing strings(properties) with the syntax of variables.
Glad to get supported.