Skip to main content

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 Kyiv

Here 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 c

Here value is the value, not the index.


Comparing for...in and for...of

Featurefor...infor...of
What it iterates overKeys (property names or indexes)Values
Works with objects ({})YesNo (an error)
Works with arrays ([])Yes, but not recommendedYes
Works with strings ("abc")Yes (indexes)Yes (characters)
Works with Map, SetNoYes
Returned valueThe key (a string)The element itself
Type of data usedEnumerable propertiesIterable 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) Error

An 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 keys for...of: iterates over values

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.