DEV Community

loading...
Cover image for Understanding for...in vs for...of statements in Javascript

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

Shivaansh Agarwal
Frontend Developer | Javascript Enthusiast | ReactJS | Tailwind CSS | Learning MERN Stack
・2 min read

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;
Enter fullscreen mode Exit fullscreen mode

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

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

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
}
Enter fullscreen mode Exit fullscreen mode

for...of:

for (variable in iterable) {
  statement
}
Enter fullscreen mode Exit fullscreen mode

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:

Discussion (0)