How to iterate through an object with the `` loop?

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

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

'id: 42'
'name: Son Goku'
'email: son@goku.db'

August 1st, 2021

# - 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.