Back to all posts

for…in and for…of in JavaScript


In JavaScript, both the for...in and for...of statements are used to loop over elements in different types of collections. However they have distinct purposes and behaviors:

for…in statement:

The for...in statement is used to iterate over the enumerable properties of an object. It works with objects and iterates over the keys of an object,

Note: generally not recommended to use it with arrays, as it may have unexpected result due to array properties and inherited properties.

Syntax

for (const key in object) {
  // Code to be executed for each property
}

Example:

const person = {
  name: 'John',
  age: 30,
  occupation: 'Engineer'
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

Output:

name: John
age: 30
occupation: Engineer

for…of statement:

The for...of statement is used to iterate over the iterable objects in JavaScript, such as arrays, strings, maps sets, etc.

It provides a simple and concise syntax to loop through the elements of a collection directly, without dealing with keys or indices.

Syntax:

for (const element of iterable) {
  // Code to be executed for each element
}

Example (With an array):

const numbers = [1, 2, 3, 4, 5];

for (const num of numbers) {
  console.log(num);
}

Output:

1
2
3
4
5

Example (With a string):

const message = 'Hello';

for (const char of message) {
  console.log(char);
}

Output

H
e
l
l
o

The for...of statement simplifies the process of iterating over elements and is preferred when dealing with arrays or other iterable collections. On the other hand, the for...in statement is more suitable when you specifically need to work with the keys of an object.