Difference Between

for..in and for..of

for..in

Purpose

Iterating over the enumerable properties of an object. This includes properties on the object itself and properties inherited through its prototype chain.

Syntax

for (let key in object) {
    console.log(key, object[key]); // Access property key and value
}

When to use

  • You need to work with the property names (keys) of an object.
  • The order of iteration is not critically important.

for..of

Purpose

Iterating directly over the values of an iterable object. Iterables include:

  • Arrays
  • Strings
  • Maps
  • Sets
  • NodeList
  • Some other built-in objects

Syntax

for (let value of iterable) {
    console.log(value); // Access the value directly
}

When to use

  • You want to work directly with the values of an array, string, or other iterable.
  • The order of iteration matters.

Key Points and Considerations

  • Enumerability: for...in loops over enumerable properties. A property is enumerable if it shows up when iterating over the object's properties.
  • Iterables: for...of is specifically designed for iterable objects—objects that implement the iterable protocol.
  • Performance: for...of is often slightly faster than for...in especially in modern JavaScript engines, as it doesn't need to perform property lookups on each iteration.
  • Don't Modify During for...in: Avoid modifying the object you're iterating over within a for...in loop, as it can lead to unexpected behavior due to how enumerable properties are determined.

Example

const myObject = { name: 'Alice', age: 30, city: 'New York' };
const myArray = ['apple', 'banana', 'orange'];
 
// for...in (object properties)
for (let prop in myObject) {
    console.log(`Property: ${prop}, Value: ${myObject[prop]}`);
}
 
// for...of (array values)
for (let fruit of myArray) {
    console.log(`I like to eat ${fruit}`);
}

To Summarize

  • for...in: Object properties (best for plain objects)
  • for...of: Values in arrays, strings, and other iterables.
Last Update: 14:51 - 14 April 2024

On this page