MakeW3web

JavaScript For..of and for..in loops

JavaScript provides two additional loop constructs, `for..in` and `for..of`, which are specifically designed for iterating over objects and iterable data structures, respectively.

  1. `for..in` loop:

The `for..in` loop is used to iterate over the enumerable properties of an object. It is mostly used with objects, as it allows you to access both property names and their corresponding values.

Syntax:

for (variable in object) {
  // code to be executed
}

Example:

const person = {
  name: "John",
  age: 30,
  city: "New York",
};

for (const property in person) {
  console.log(`${property}: ${person[property]}`);
}
// Output:
// name: John
// age: 30
// city: New York

In this example, the `for..in` loop iterates over the properties of the `person` object, and property takes on the value of each `property` name.

  1. `for..of` loop:

The `for..of` loop is used to iterate over iterable data structures such as arrays, strings, sets, and maps. It allows you to access the values directly, without needing to use an index or key.

Syntax:

for (variable of iterable) {
  // code to be executed
}

Example:

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

for (const number of numbers) {
  console.log(number);
}
// Output:
// 1
// 2
// 3
// 4
// 5

In this example, the `for..of` loop iterates over the values in the `numbers` array, and `number` takes on the value of each array element.

It is important to note that the `for..in` loop is generally not recommended for iterating over arrays, as it may yield unexpected results due to the inclusion of enumerable properties that are not array elements. The `for..of` loop is specifically designed for iterating over iterable data structures and should be used in such cases.

Using the `for..in` and `for..of` loops appropriately can help make your code more readable and efficient when working with objects and iterable data structures in JavaScript.

Was this page helpful?