I don't understand for...in fully. Can someone explain?

https://www.codecademy.com/courses/introduction-to-javascript/lessons/objects/exercises/for-in
My code:

for (let crewMember in spaceship.crew){
  console.log(`${crewMember} : ${spaceship.crew[crewMember].name}`)
}
for (let crewMember in spaceship.crew){
  console.log(`${spaceship.crew[crewMember].name} : ${spaceship.crew[crewMember].degree}`)
}

Why does this code output this:

captain : Lily
chief officer : Dan
medic : Clementine
translator : Shauna
Lily : Computer Engineering
Dan : Aerospace Engineering
Clementine : Physics
Shauna : Conservation Science

What does crewMember represent, and how was it used in the code above?

Not seeing the list the for loop is iterating through, it appears the list is something like,

spaceship.crew = [captain, chief officer, medic, translator]

Think of the for (let crewMember in spaceship.crew) as a for each crewMember in the list spaceship.crew. The for loop iterates through each element in the list and executes the appropriate function as directed ā€“ in this case, logging the corresponding name and degree to the console.

Here is the code Iā€™m iterating through:

let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

for..in enumerates an object by keys. crewMember is a key of the crew object.

crew = spaceship.crew
for (let crewMember in crew){
  console.log(`${crewMember}: ${crew[crewMember].name}, ${crew[crewMember].degree}`)
}

So each iteration crewMember becomes one of the 4 main keys in crew: [captain, chief officer, medic, translator], and so this code means: ${spaceship.crew[crewMember].name})
that it will go into crew, then crewMember will equal one of the 4 keys, and then you call .name on crewMember, so when you call this code:

for (let crewMember in spaceship.crew){
  console.log(`${crewMember} : ${spaceship.crew[crewMember].name}`)
}

It will print out

captain : Lily
chief officer : Dan
medic : Clementine
translator : Shauna

I think I get it now.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.