It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 80 – JavaScript for...of vs for...in Loops

Understanding the difference between for...of and for...in is essential when working with JavaScript collections such as arrays and objects.


for...in Loop

The for...in loop iterates over enumerable property keys of an object (including inherited ones).

Syntax

for (let key in object) {
  // code to execute
}

Example

const user = {
  name: "Alice",
  age: 30,
  isMember: true
};

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

Notes

  • Use with objects.
  • May include inherited properties – use hasOwnProperty() to filter.
  • Order of keys is not guaranteed.

for...of Loop

The for...of loop iterates over iterable values like arrays, strings, sets, maps, etc.

Syntax

for (let value of iterable) {
  // code to execute
}

Example

const fruits = ["apple", "banana", "cherry"];

for (let fruit of fruits) {
  console.log(fruit);
}

Notes

  • Use with iterable data structures.
  • Does not work directly with objects (non-iterable).

Key Differences

Feature for...in for...of
Iterates over Property keys (strings) Values of iterable objects
Suitable for Objects Arrays, Strings, Maps, Sets
Works with objects (OK) (NO) (unless using Object.entries)
Use case example Loop through object keys Loop through array values

Try Your Hand

Exercise

Create a function describeObject(obj) that uses a for...in loop to print all keys and values of an object, and a for...of loop to print the values from Object.values(obj).

function describeObject(obj) {
  console.log("Using for...in:");
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      console.log(`${key}: ${obj[key]}`);
    }
  }

  console.log("\nUsing for...of:");
  for (let value of Object.values(obj)) {
    console.log(value);
  }
}

describeObject({ name: "John", age: 25, city: "Accra" });

Summary

  • Use for...in for objects and when you need keys.
  • Use for...of for iterables when you need values.
  • Always understand the type of data you're iterating over to choose the right loop.