for...in
Loops over the property names of an object.
Available since: ES1
Syntax
for (const key in object) { … }Examples
The keys and values of an object:
const prices = { tea: 3, coffee: 5 };
for (const key in prices) {
console.log(key, prices[key]);
}Output:
tea 3
coffee 5With an array you get string indexes, not values:
for (const i in ['a', 'b']) {
console.log(i, typeof i);
}Output:
0 string
1 stringNotes
For arrays use for...of. for...in also visits inherited enumerable properties, so for objects Object.keys() or Object.entries() with for...of are safer.
See also
- for...of — Loops over the values of arrays, strings, Maps, Sets and other iterables.
- Object.keys — Returns an array of an object's property names.
- Object.entries — Returns an array of property name and value pairs.
In the tutorial
- Loops — The while, for and for...of loops in JavaScript — the counter, the step, looping over a string and accumulating a result.