FAQ: Objects - Looping Through Objects

This community-built FAQ covers the “Looping Through Objects” exercise from the lesson “Objects”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Looping Through Objects

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

3 posts were merged into an existing topic: What does this ${} syntax do?

47 posts were merged into an existing topic: Why can’t I use crewMember.name?

3 posts were merged into an existing topic: Why can’t I use crewMember.name?

6 posts were split to a new topic: How can I console log the functions in an object? [solved]

4 posts were split to a new topic: Typo [solved]

What’s wrong with this code? I don’t get any Error, but empty console:

list=[]
crewmembercount=0
for (let crewmember in spaceship.crew){
  list.push(`${crewmember}: ${spaceship.crew[`${crewmember}`].name}`)
  crewmembercount++;
 if(crewmembercount===spaceship.crew.length){
   consol.log(list);
 }
}

It said a LIST, so I printed an array…

list=[]
for (let crewmember in spaceship.crew){
  list.push(`${crewmember}: ${spaceship.crew[`${crewmember}`].name}`)
}console.log(list)

How frustrating! Finally got it, though. Hooray me

As I understand the instructions we just need to log inside the loop.

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

If we create a list the output will be an array, meaning it would have to be iterated to get the below output.

Lily: Computer Engineering
Dan: Aerospace Engineering
Clementine: Physics
Shauna: Conservation Science
7 Likes

The right code should look like this:
(I created peoplesRole here, the role is not degree btw)

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

//And the output looks like this:

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

In this exercise you use ‘let’ to introduce the for…in parameter: for (let crewMember in spaceship.crew)…
I checked around and din’t find a documentation telling that ‘let’ is necessary for…in a syntax, nor I see why we should declare the parameter since it will always be only a string and not an assignable variable. Actually it works just fine without ‘let’ here.
Is using “let” in that expression best practice? If it is so, why?

1 Like

Not necessary and best practice are two different things. Its then crucial to understand what let does.

let makes the variable block scoped, which means we can’t access the variable outside the loop:

for (let crewMember in spaceship.crew){

}

console.log(crewMember) // gives error

not even using var, but nothing at all, is risky. You might overwrite an existing variable:

let crewMember = 'profe of concept'
for (let crewMember in spaceship.crew){

}

console.log(crewMember) // last element from the loop

the variable now leaked outside its scope (the for loop) and has overwritten our global variable.

5 Likes

From a scope point of view, so to say, reason to use ‘let’ becomes clear. And after posting my question I kept looking around. It appeared to me that it was not proper coding not to declare the iterating variable in any case. I won’t do it again, I promise. :wink:

3 Likes

Hi guys;
my problem is very basic, I completely confused. the answer was:
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})
};

But I want to know:
why we repeatedly use “crewMenber”. what’s its job. Why sometimes it came in {} and sometimes in . Why we use $ at those particular positions?Why we don’t directly write: spaceship.crew.name… Why we have to add [crewMember] between them…
I think “for…in” need more explanations.
gratefully

4 Likes

as it was explained above is that ‘for’ doesn’t return an object but a string. so if you think about the computer going through the repetitions of the code and you put a string where ${} and are maybe you will see what it is doing.

Hi, something is nagging me in this exercise.

Why doesn’t the following syntax work?


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

Why does crewMember have to be in brackets, like so:


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

It does not have any special character, so surely both should be usable, right?

Thanks.
N.

2 Likes

except the loop gives you a string, when accessing an object property as string, you have to use associative array notation.

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

why this doesn’t work? it only work when I assign spaceship.crew into another variable.

within the body of the loop. doing spaceship.crew will use the loop iterator (crew) not the crew property of spaceship object. Variable name conflict.

1 Like

it’s okay now. if found the issue (additional space behind the string).
I removed that and it work

Hi everbody,

can somebody explain to me, from where “crewMember” is coming?
And why i need. I already know i can be changed to different word but also why

Thanks alot!

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!') } 
        }
    }
}; 

// Write your code below
for (let crewMember in spaceship.crew ){
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
}```
1 Like