for…in vs. for…of Loops In JavaScript: Use Cases

In JavaScript, we often need to go through elements in an object or an array. That’s where and for...of loops come into play. They might seem similar but are used for different purposes. Let’s dive into what makes them different and when you should use each one.

for…in Loop

The loop is great for iterating over object properties. It goes through the keys (property names) of an object.

I. Syntax

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

II. Use Case

When you want to look at or do something with all the keys or properties in an object, use

III. Example

const student = {
  name: "Alex",
  grade: 10,
  subject: "Math"

for (let key in student) {
  console.log(key + ': ' + student[key]);
  // This will log:
  // "name: Alex"
  // "grade: 10"
  // "subject: Math"

Note: Remember, loops through properties, so it’s best for objects.

for…of Loop

The for...of loop is made for iterating over iterable objects like arrays, strings, or other iterable types. It goes through the values of an iterable.

I. Syntax

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

II. Use Case

When you’re interested in the values inside an iterable (like an array or string) and don’t care about the indexes or keys, for...of is your go-to.

III. Example

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

for (let color of colors) {
  // This will log:
  // "red"
  // "green"
  // "blue"

Note: for...of does not work directly with objects since they are not iterable by default.

Key Differences

  • Purpose: is for looping over object properties (keys). for...of is for looping over iterable objects (values).
  • What they loop through: loops through keys of an object. for...of loops through values of an iterable.
  • Use cases: Use for objects when you need keys. Use for...of for arrays, strings, and other iterables when you need values.


Choosing between and for...of depends on what you’re trying to accomplish. If you need to work with the properties of an object, is the way to go. If you’re dealing with the elements in an array or characters in a string, for...of will serve you better. Understanding these differences will help you write clearer and more effective JavaScript code.