Course contentsShow
← JavaScript
Lesson 359 of 2,72310. LoopsFree lesson

For...of vs For...in: Key Differences

Compare for...of (values) and for...in (keys) to choose the right loop.

For...of vs For...in: Key Differences

You'll learn how to choose between for...of (which iterates over values) and for...in (which iterates over keys) based on what you need from your loop.

The Core Distinction

Think of for...of and for...in as two different ways to explore a collection:

  • for...of asks: "What values are inside this collection?"
  • for...in asks: "What keys (or property names) does this collection have?"

When to Use For...of

Use for...of when you care about the actual data in an iterable:

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color); // 'red', 'green', 'blue'
}

Perfect for arrays, strings, Sets, and Maps where you want the contents.

When to Use For...in

Use for...in when you need the property names of an object:

const user = { name: 'Alice', age: 30, city: 'NYC' };

for (const key in user) {
  if (user.hasOwnProperty(key)) {
    console.log(key); // 'name', 'age', 'city'
    console.log(user[key]); // Access the value if needed
  }
}

Best suited for plain objects when you need to know what properties exist.

Quick Decision Guide

  • Iterating an array? Use for...of to get each element directly
  • Exploring object properties? Use for...in to get each key name
  • Need both index and value in an array? Use a regular for loop or for...of with array methods (once you learn those)
  • Avoid: for...in on arrays (gives you string indices, includes inherited properties)

Key Takeaway: Choose for...of to loop through values in iterables like arrays; choose for...in to loop through property keys in objects. Matching the loop type to your data structure prevents confusion and bugs.