Keyword Declaration

122 views Asked by At

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)
}**
2

There are 2 answers

1
Ganael D On BEST ANSWER

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);
}
0
Quentin On

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

You haven't. You've just started assigning values to it.

To declare a variable you need to use a keyword like const or let (or var, which isn't recommended these days, or a function declaration which wouldn't be appropriate here.)

for (let key in restaurant.staff){

Aside: Your code would probably be better written as:

const staffNames = Object.values(restaurant.staff);