Need explanation if the for…in

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 (let crewMember in spaceship.crew) {
console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`);
}
for (let crewMember in spaceship.crew) {
console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
};



output:

Lily: Computer Engineering

Dan: Aerospace Engineering

Clementine: Physics

Shauna: Conservation Science

captain: Lily

chief officer: Dan

medic: Clementine

translator: Shauna

MY QUESTION: how does crewMember know to take the value of of each crew member’s role? In my JS code I never set crewMember equal to anything and in the ‘for…in’ loop i declare the variable crewMember but I still don’t get how it get’s linked to each crew members role?

ALSO,

when i log it to my console, i’m confused by two things:

Why is the crewMember variable in square brackets?

Again, how is that crewMember associated with each crew member’s role?

I hope this makes sense

for...in is

for(eachKey in someObject)

You give names to things in programming by assigning them to variables, so “eachKey” needs to be assigned to a variable.

The properties are all crew members of a spaceship, so the variable name that was chosen in this case is crewMember.

So for(let crewMember in spaceship.crew) is, in turn, “captain”, “chief officer”, “medic”, “translator”, because those are the keys of the object “spaceship.crew”

Square brackets are how you access values of object properties.

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