Skip to main content

for...in VS for...of in an array

The difference between for...in and for...of in JavaScript is one of those things you need to understand clearly, especially when working with arrays.


In brief:

LoopWhat it iteratesUsed for
for...inKeys / indexes (property names of an object)objects
for...ofValues of elements (from iterable objects)arrays, strings, Set, Map, etc.

Example 1 - array

javascript
const arr = ["a", "b", "c"];

for...in iterates indexes (keys):

javascript
for (const index in arr) { console.log(index); // "0", "1", "2" }
  • Returns string indexes (not numbers!).
  • Suited for objects, not arrays.
  • May pick up extra properties, if added manually.

for...of iterates values:

javascript
for (const value of arr) { console.log(value); // "a", "b", "c" }
  • Works with iterable objects (Array, String, Set, Map...).
  • Returns element values.
  • Ideal for arrays.

Example 2 - the difference in practice:

javascript
const arr = ["x", "y", "z"]; arr.custom = "hello"; // add a property manually for (const key in arr) { console.log(key); // "0", "1", "2", "custom" } for (const value of arr) { console.log(value); // "x", "y", "z" }

for...in walks through all enumerable properties of the object, including manually added ones. for...of visits only the array's elements.


Example 3 - working with a string (an iterable object)

javascript
for (const char of "JS") { console.log(char); // "J", "S" }

for...of works great with strings. for...in on a string returns indexes "0", "1".


In short:

Featurefor...infor...of
Iterateskeys (indexes, properties)values
Works withobjects, arraysiterable objects (array, string, Set, Map)
Returnsstrings, property namesactual values
Ordercan be unpredictablepreserves order
Suited for arraysNoYes
Suited for objectsYesNo

Remember it simply:

for...in → iterates keys (for objects) for...of → iterates values (for arrays and iterable objects)

Short Answer

Interview ready
Premium

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