How can I console log the functions in an object? [solved]

Question, why does it return undefined between running the functions?

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

when i run this loop:

for(let members in spaceship.crew) {
console.log(spaceship.crew[members].cheerTeam())

why does this return
Undefined by each pass ?

You got this!
undefined
WhooHaa
undefined
BEEER
undefined
what the ■■■■
undefined

Ah, I got it, because i am running a console.log on a console.log …

That’s it. Have your methods return then log the returns.

1 Like

I really would like to figure out how to console.log the name and function correlated to each name ???

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

I’m still not understanding how you got the answer. Would you please explain it a little more in detail?

If you are referring to the different methods included in each crew member’s properties ie. cheerTeam(), agree(), etc., you can just console.log(spaceship.crew.translator.powerFuel()); for an individual crew memeber. There are several ways to loop through the crew members, and invoke each members method. Here’s one way:

for (let crewMember in spaceship.crew) {
  //shorten spaceship.crew[crewMember] to ref for convenience
  const ref = spaceship.crew[crewMember];
  const name = ref.name;
  //function to determine which method to invoke
  const myFunction = memberName => {
    switch (memberName) {
      case 'Lily':
        return ref.cheerTeam();
      case 'Dan':
        return ref.agree();
      case 'Clementine':
        return ref.announce();
      case 'Shauna':
        return ref.powerFuel();
      default:
        return 'Hello World!';
    }
  }

  console.log(`${name}: ${myFunction(name)}`);
}

Output:

Lily: You got this!
Dan: I agree, captain!
Clementine: Jets on!
Shauna: The tank is full!

Hope this helps!

3 Likes

It did thank you! I was on the right track but you definetly cleared it up for me!

1 Like