How to iterate through an object with the `for...in` loop?

const user = {
  id: 42,
  name: 'Son Goku',
  email: 'son@goku.db'
}

for(const prop in user) {
  console.log(`${prop}: ${user[prop]}`)
}

/*
output:
'id: 42'
'name: Son Goku'
'email: son@goku.db'
*/
Copy

August 1st, 2021

# for...in - Looping an object

Add to bookmarks

prop isn't a property, but the string representation of the property key. This way we're able to acces the property value by usering the bracket notion user[prop].

This loop can be applied on arrays, because they are literally objects, but it's not recommended. The right order can't be guaranteed.

HomeBookmarks