In this lesson it seems intuitive to just use crewMember.name to reference the name of each crewMember. However it results in undefined, why doesn’t this work?
Solution
When using a for..in loop, the iterator is a type string (you can verify this with typeof) so they do not have the name property. For example as it iterates through the captain, crewMember = 'captain'.
Since this is a string on its own, you can log it as such. That is why `${crewMember} works correctly. However when you then want to use it to reference, the format doesn’t work using dot notation.
object.propertyName
Dot notation requires the propertyName not as a string. To use it as a string, we can utilize it in associative array notation (with square brackets). object['propertyName'].
So in our lesson, this is why you need to format it as ${spaceship.crew[crewMember].name} This way it checks spaceship and then in crew finds the crewmember and returns the name property of that crewmember.
Hope this helps, please discuss and ask further questions below.
This code was used in the example in this exercise: for (let crewMember in spaceship.crew) {
console.log(${crewMember}: ${spaceship.crew[crewMember].name})
};
My question is, why do you use a bracket around crewMember in the last line? It is not a two-word string, nor does it have special characters or a space.??
for the dot nation (object notation if you like), we must use the same of the property, for the associative array notation, the key needs to be string.
when using a for ... in loop, the iterator (crewMember in your case) is of type string (you could use typeof to verify this), in which case we have to use the associative array notation
I still don’t understand. Practically it crewMate.name does ouputs undefined but why? If crewMate is already a variable then crewMate.name should be working.
for (let crewMember in spaceship.crew) {
console.log(${crewMember}: ${spaceship.crew[crewMember].name})
}
In the above code, why can we call ${crewMember} without needed to specify spaceship.crew[crewMember]? Why can we not use ${crewMember.name} in the second part of the console.log() string?
for (let position in spaceship.crew){
console.log(position + ': ’ + spaceship.crew[position][name]);
};
Supposedly we can write the keys in bracket notation, right?
This one also returned error, but as far as I know, if the keys don’t have special characters, we can write them through dot notation:
for (let position in spaceship.crew){
console.log(position + ': ’ + spaceship.crew .position.name);
};
I thought that the loop had something to do but I didn’t know what. So just to be clear, then: variables on the for in loop are treated as strings, right?