Understanding for...in vs for...of statements in Javascript

Overview

  • Differences
    1. Definition
    2. Syntax
    3. When to use for...in or for...of?
    4. Examples
  • Further Reading

Differences

1. Definition

for...in:

The for...in loop statement iterates over the enumerable properties of an object including the inherited enumerable properties in an arbitrary order except the keys that are of type Symbol. Enumerable properties are those properties whose internal enumerable flag is set to true. The following properties a,b,c are enumerable by default:

const obj1 = {a:1, b:2};
obj1.c = 3;

The property defined using Object.defineProperty by default are not enumerable:

const obj2 = {};
Object.defineProperty(obj2, 'a', {
  value: 42
});

for...of:

The for...of loop statement iterates over the values that the iterable object defines to be iterated over like Array, String. etc. Some built in types such as Array and Map have a default iteration behaviour while Object does not.

2. Syntax

for...in:

for (variable in object) {
  statement
}

for...of:

for (variable in iterable) {
  statement
}

3. When to use for...in or for...of?

for...in:

  • for...in can used in scenarios where you want to iterate over properties of an Object to check the keys and their corresponding values.
  • Since for...in loop statement iterates over enumerable properties of an object in an arbitrary order it is not recommended to use for..in with an Array where index order is important. It is because there is no guarantee that for...in will return indexes in any particular order.
  • If you want to loop over values of an array consider using for with numeric index, Array.prototype.forEach, for...of.

for...of:

  • To be used to iterate over iterable objects.
  • for...of can be iterated over String, Array, TypedArray, Map, Set, arguments object of a function, DOM Collection, generators, other iterable objects.

2. Example

image image image

Further Reading:

Following are the list of resources for further deep exploration:

S.NoLink
1for...in [MDN Docs]
2for...of [MDN Docs]
3[What is the difference between ( for… in ) and ( for… of )