Why is [crewMember] appended as “spaceship.crew[crewMember].name”, rather than “spaceship.crew.name[crewMember]”?
I thought that since we are looping through and printing the strings attached to “name” (for example, name: '‘Lily’), we would be appending the array/variable to “name”.
Same question goes for degree. Why “spaceship.crew[crewMember].degree” instead of “spaceship.crew.degree[crewMember]”? We are looping through and printing the degree, not the name of the crew member’s title.
Hi. I’m struggling to understand why the syntax below doesn’t work:
for (let crewMember in spaceship.crew) {
console.log(`${crewMember}: ${[crewMember].name}`)
}
I was expecting to see
Captain: Lily
etc instead I got:
Captain: undefined
If we console.logcrewMember it gives Captain, Chief Officer etc so I assume the variable crewMember is accessing spaceship.crew as per the first line of code in the for...in loop.
So if crewMember is accessing that ‘branch’ of the object can we not just use crewMember.name or [crewMember].name to access each crew member’s name?
Why must we go back and use spaceship.crew[crewMember].name? Are we not repeating ourselves?
Simple answer, no, it is not okay. It leaks the variable into global scope. Declaration of variables is a big thing in JS, as is protection of block scope and prevention of leakage.
Why is crewMemb.name insufficient for accessing the name property of each crew member? It logs:
If the standalone reference to crewMemb retrieves each nested object(seen above), why doesn’t crewMemb.name access the name property inside that same object?
ie. why will spaceship.crew[crewMemb].name be necessary in the second half of that string, when crewMemb alone is seemingly already being read as spaceship.crew[crewMemb] by the program?
Ah brilliant; got tripped up by being so used to reading keys as shorthand for whole properties. Presumed the forest and missed the trees here. Thanks!
the announce method does not return anything, yet when you call this method you also attempt to log the returned result. remove the console.log when calling the announce method
I’m not referring to the for in loop itself, I’m referring to how in the lesson I linked, we are able to chain properties to get nested values. The lesson explanation confirms this
spaceship.nanoelectronics['back-up'].battery; // Returns 'Lithium'
In the preceding code:
* First the computer evaluates `spaceship.nanoelectronics`, which results in an object containing the `back-up` and `computer` objects.
* We accessed the `back-up` object by appending `['back-up']`.
* The `back-up` object has a `battery` property, accessed with `.battery` which returned the value stored there: 'Lithium'
So even if member is a key, we should still be able to access it’s associated value according to the above, that’s my thought process. Let me know where I’m going wrong