JavaScript For In
The for...in loop walks the property names of an object one by one. Each name arrives as a string.
Names and values
The loop hands over each key. Bracket notation reads the matching value from the object.
const person = { name: "Ana", age: 9 };
for (const key in person) {
console.log(key, person[key]);
}Indexes of an array
Over an array, for...in visits the indexes. The values themselves never appear.
const fruits = ["apple", "banana"];
for (const key in fruits) {
console.log(key);
}Keys are strings
The typeof check proves the key type. Even a plain object key arrives as a string.
const person = { name: "Ana" };
for (const key in person) {
console.log(typeof key);
}Example
const car = { brand: "Ford", year: 2020, color: "red" };
let count = 0;
for (const key in car) {
count++;
}
console.log(count);Key points
- A property name is also called a key.
- Bracket notation reads the value stored under a key.
- person[key] reads the value for the current key.
- Keys arrive as strings, even when the loop walks an array.
In this example, the loop visits each property name of the car object. The counter grows by one on every turn. The object has three properties, so the log shows 3.
Note
Use for...of for arrays. Save for...in for objects.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which loop walks the property names of an object?