Search code examples
javascriptfor-in-loop

Keyword Declaration


Asked to:

'Iterate through the staff nested inside the restaurant object, and add their names to the staffNames array.'

My solution keeps getting rejected with this error:

'Use a declaration keyword when declaring your key variable'

Feel like I'm going mad as I've definitely declared the variable.

Code below, what I added is in bold; the rest is the original code.

const restaurant = {
  tables: 32,
  staff: {
    chef: "Andy",
    waiter: "Bob",
    manager: "Charlie"
  },
  cuisine: "Italian",
  isOpen: true
};

const staffNames = []

**for (key in restaurant.staff){
  const value = restaurant.staff[key]
  staffNames.push(value)
}**

Solution

  • You need to declare the variable key in your for loop. Try this:

    const restaurant = {
      tables: 32,
      staff: {
        chef: "Andy",
        waiter: "Bob",
        manager: "Charlie"
      },
      cuisine: "Italian",
      isOpen: true
    };
    
    const staffNames = [];
    
    for (let key in restaurant.staff) {
      const name = restaurant.staff[key];
      staffNames.push(name);
    }