What’s the difference between for…in and Object.keys
Both for…in and Object.keys() can be used to iterate over Object properties, but there is a difference between them.
for…in
The loop will iterate over all enumerable properties of the object itself and the object properties inherited from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).
A for...in
loop only iterates over enumerable, non-symbol properties. Objects created from built–in constructors like Array
and Object
have inherited non–enumerable properties from Array.prototype
and Object.prototype
, such as Array
's indexOf()
method or Object
's toString()
method, which will not be visited in the for...in
loop.
The for...in
loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.
const obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}// Logs:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
Object.keys
Object.keys()
returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object
. This is the same as iterating with a for...in
loop, except that a for...in
loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys()
is the same as that provided by a for...in
loop.
Object.keys() below iterates over all of the object’s enumerable, non-symbol properties and logs a string of the property names and their values.
const obj = { a: 1, b: 2, c: 3 };
for (let prop of Object.keys(obj)) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Logs:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via Object.defineProperty
and such are not enumerable by default. Most iteration means (such as for...in
loops and Object.keys
) only visit enumerable keys.
Conclusion
Both for…in and Object.keys() are used to iterate over Object keys/ properties, the only difference that the for…in also iterates over the enumerable object properties inherited from its prototype chain, while Object.keys() doesn’t.
I will be posting more topics related to javascript & Front End development, can you support me with subscribe.
References