Next: for…of Statement, Up: Iterators---For--Of [Index]
The for...in
statement iterates over all enumerable properties of an object
that are keyed by strings (ignoring ones keyed by Symbols), including inherited
enumerable properties. A for...in
loop iterates over the properties of an
object in an arbitrary order. for...in
should not be used to iterate over an
Array where the index order is important.
If you only want to consider properties attached to the object itself, and not its prototypes,
getOwnPropertyNames()
or
hasOwnProperty()
check
propertyIsEnumerable()
can also be used
Given that for...in
is built for iterating object properties, not recommended
for use with arrays, and options like Array.prototype.forEach()
and
for...of
exist, what might be the use of for...in
at all?
It may be most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise).
Although arrays are often more practical for storing data, in situations where a key-value pair is preferred for working with data (with properties acting as the "key"), there may be instances where you want to check if any of those keys hold a particular value.
var obj = {a: 1, b: 2, c: 3}; for (const prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); } // Output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3"