for...in loop
suggest changeWarning:
for...initerates enumerable string keys, including inherited ones. It is intended for object properties, not array values. Preferfor...offor arrays and other iterables. Non-enumerable and symbol-keyed properties are not visited.
const object = { a: 'foo', b: 'bar', c: 'baz' };
Object.defineProperty(object, 'a', {
enumerable: false,
});
for (const key in object) {
if (Object.hasOwn(object, key)) {
console.log(`object.${key}, ${object[key]}`);
}
}
Expected output:
object.b, bar
object.c, baz
When inherited properties are not wanted, Object.keys(), Object.values(), or Object.entries() is usually simpler because those methods return only own enumerable properties.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents