Object property iteration

suggest change

Use Object.entries() when both the keys and values of an object's own enumerable string-keyed properties are needed:

const object = { first: 1, second: 2 };

for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Object.keys() returns keys, while Object.values() returns values. All three methods exclude inherited and non-enumerable properties.

When a for...in loop is appropriate, filter inherited properties with Object.hasOwn(). Do not call object.hasOwnProperty() directly because the object may override that method or have a null prototype.

for (const key in object) {
  if (Object.hasOwn(object, key)) {
    console.log(key, object[key]);
  }
}

Use Reflect.ownKeys() when non-enumerable and symbol keys must also be included.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents