Using a for..of or forEach to access the item’s index

Using a for…of

const people = [
  {
    name: "Bob",
    occupation: "Software Engineer"
  },
  {
    name: "Kim",
    occupation: "Architect"
  }
]

console.log("Using for...of:")
for(const [index, person] of people.entries()) {
  console.log(`${person.occupation} at index ${index}`) 
}

/*
Using for...of:
Software Engineer at index 0
Architect at index 1
*/

Using a forEach

const people = [
  {
    name: "Bob",
    occupation: "Software Engineer"
  },
  {
    name: "Kim",
    occupation: "Architect"
  }
]

console.log("Using forEach:")
people.forEach((person, index) => {
  console.log(`${person.occupation} at index ${index}`)
})

/*
Using forEach:
Software Engineer at index 0
Architect at index 1
*/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s