The for in loop
for...in: iterates over the keys (property names) of an object or an array's indexes
This loop goes over the enumerable properties of an object (or an array's indexes, if it is an array).
Example with an object:
javascript
const user = { name: 'Oleh', age: 25, city: 'Kyiv' };
for (const key in user) {
console.log(key, user[key]);
}Result:
javascript
name Oleh
age 25
city KyivHere key is a string ("name", "age", "city"): the property name.
With arrays, for...in gives you indexes, not values:
javascript
const arr = ['a', 'b', 'c'];
for (const i in arr) {
console.log(i); // 0, 1, 2
console.log(arr[i]); // 'a', 'b', 'c'
}But for...in is not recommended for arrays,
because it can pick up extra properties of the array, if any were added manually.
for...of: iterates over the values of iterable structures
It works with iterable objects:
Array, String, Map, Set, NodeList, arguments, and so on.
Example:
javascript
const arr = ['a', 'b', 'c'];
for (const value of arr) {
console.log(value);
}Result:
javascript
a
b
cHere value is the value, not the index.
Comparing for...in and for...of
| Feature | for...in | for...of |
|---|---|---|
| What it iterates over | Keys (property names or indexes) | Values |
Works with objects ({}) | Yes | No (an error) |
Works with arrays ([]) | Yes, but not recommended | Yes |
Works with strings ("abc") | Yes (indexes) | Yes (characters) |
| Works with Map, Set | No | Yes |
| Returned value | The key (a string) | The element itself |
| Type of data used | Enumerable properties | Iterable values |
Examples of the difference
An object:
javascript
const user = { name: 'Oleh', age: 25 };
for (const key in user) {
console.log(key); // name, age
}
// for (const value of user) ErrorAn array:
javascript
const arr = ['a', 'b', 'c'];
// for...in -> indexes
for (const i in arr) {
console.log(i); // 0, 1, 2
}
// for...of -> values
for (const val of arr) {
console.log(val); // a, b, c
}A string:
javascript
for (const i in "Hi") {
console.log(i); // 0, 1
}
for (const ch of "Hi") {
console.log(ch); // H, i
}The short way to remember it:
for...in: iterates over keysfor...of: iterates over values
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.