I would like to clarify something. When it comes to accessing properties through a loop, how is come it isn’t corrent to use a counter variable in a chain of nested objects?
E.i.: contacts.i.firstname or contacts(i).firstname?
So I was wondering why contacts.i.firstname wasn’t an acceptable answer in the challenge.
Are there any other defined uses of these characters, notations and variables that I may be missing out?
I hope you understand what I’m talking about. I’d appreciate anything that will help me out of this confusion.
When you are accessing properties on objects, you can chain the property keys together to dive deeper into the object. In the example of contacts.i.firstname then the program would end up looking for something literally called i instead of the variable i.
You, as the programmer, know that i refers to a variable, but the engine does not know you are trying to use i as a variable unless you use the bracket notation. I hope that helps.
The difference between . and [] is a subtle one but it’s important to understand.
When accessing a property with dot, it literally looks for the property specified; so in your first example.
contacts.i.firstname
It would look for the i property of the contacts object, which doesn’t exist in this case.
When using [], it ‘computes’ the value inside the brackets then uses that value to lookup a property on the object.
So if you were to write your example like:
contacts[i].firstname
It would compute the value of i, say 0 for the first iteration of the loop and then use that value to look for a property on the contacts object, so it would end up doing something like:
contacts.0.firstname
Note: The above won’t work if you wrote it because numbers aren’t allowed at the beginning of property keys, that’s why we use arr[0] when access array elements.
var myObj = {someKey: 'pink', 42: 'yellow',
'string containing spaces': 'blue'}
var someKey = 42;
myObj.someKey; // pink
// Explanation: treats `someKey` as a literal key name
myObj[someKey]; // yellow
// Explanation: treats `someKey` as a variable, which
// we set to 42 earlier
myObj['someKey']; // pink
// Explanation: treats `someKey` as a literal key name,
// due to being enclosed in quotes
myObj.string containing spaces; // syntax error
myObj.'string containing spaces'; // syntax error
myObj['string containing spaces']; // blue
// Explanation: This is the only way to reference a key
// that contains characters that aren't allowed in
// JavaScript identifiers