Understanding JavaScript Loops: for...in vs for...of

Understanding JavaScript Loops: for...in vs for...of

·

7 min read

What are Loops?

Imagine you’re playing a game where you must say the name of each fruit in a basket. If there are many fruits, it would be tiring to do this one by one, right? In programming, when we want to do something repeatedly, we use a loop. It’s like the magic basket that automatically names each fruit for us!

The for...in Loop

The for...in loop is like a detective. It loves to explore every detail (property) of an object. Let’s say we have an object named seasons:

const seasons = {
  "Nov-Feb": "❄️",
  "Mar-April": "🌸",
  "Jun-Aug": "☀️",
  "Sep-Oct": "🍂",
};

In this object, seasons, we have properties like "Nov-Feb", "Mar-April", "Jun-Aug", and "Sep-Oct". Each property is associated with a symbol that represents a season.

for (let details in seasons) {
  console.log(details, seasons[details]);
}
//output
Nov-Feb ❄️
Mar-April 🌸
Jun-Aug ☀️
Sep-Oct 🍂

The for...of Loop

The for...of loop is like a storyteller. It loves to tell stories about each item in a list. But wait, our seasons is an object, not a list. No worries! We can turn the properties of our seasons object into a list using Object.keys(seasons), and then our storyteller can do its job:

for (let prop of Object.keys(seasons)) {
  console.log(prop + ":", seasons[prop]);
}
//output
Nov-Feb: ❄️
Mar-April: 🌸
Jun-Aug: ☀️
Sep-Oct: 🍂

In JavaScript, a for...of loop can only be used on iterable objects, like arrays or strings. A standard JavaScript object, like the seasons object, is not iterable by default. However, you can convert the object into an iterable, such as an array, and then use a for...of loop on it.

for (let season of Object.values(seasons)) {
  console.log(season);
}
//output
❄️
🌸
☀️
🍂

Modifying Our Seasons with seasons2

Now, what if we want to change one of our seasons? For example, let’s say that instead of being sunny in "Jun-Aug", it’s actually rainy. We can create a new object that inherits from our original seasons object, and then change the "Jun-Aug" property:

const seasons2 = Object.create(seasons);
seasons2["Jun-Aug"] = "🌧️";

In this code, Object.create(seasons) creates a new object seasons2 that inherits all the properties from seasons. Then, seasons2["Jun-Aug"] = "🌧️" changes the "Jun-Aug" property to "🌧️", representing rain.

Now, if we use our for...in and for...of loops on seasons2, they will show that it’s rainy in "Jun-Aug":

for (let season in seasons2) {
  console.log(season, seasons2[season]);
}
//output
Jun-Aug 🌧️
Nov-Feb ❄️
Mar-April 🌸
Sep-Oct 🍂

seasons2object inherits the Jun-Aug: property from its prototype, you might be surprised to see it appear in the output of the for...in loop. This could lead to unexpected results in your code.

for (let prop of Object.keys(seasons2)) {
  console.log(prop + ":", seasons[prop]);
}
//output
Jun-Aug: 🌧️

The for...of loop, on the other hand, only iterates over the enumerable properties of an object. This makes it more reliable than the for...in loop, because it is less likely to iterate over unexpected properties.

In general, it is best to use the for...of loop to iterate over the properties of an object, and to only use the for...in loop when you need to iterate over all of the properties of an object, including non-enumerable properties and properties that have been inherited from the object's prototype.

The for...in and for...of loops in JavaScript are used for different purposes:

  1. for...in Loop: This loop is used to iterate over the enumerable properties of an object. It provides access to the property names of the object, not the actual values. Here’s an example:

     let obj = { a: 1, b: 2, c: 3 };
     for (let prop in obj) {
       console.log(prop); // Logs 'a', 'b', 'c'
       console.log(obj[prop]); // Logs 1, 2, 3
     }
    

    In this example, prop is the property name, not the value. If you want to access the value, you would use obj[prop].

  2. for...of Loop: This loop is used to iterate over iterable objects like arrays, strings, maps, etc. It provides access to the values of the iterable, not the indices or keys. Here’s an example:

     let arr = ['a', 'b', 'c'];
     for (let value of arr) {
       console.log(value); // Logs 'a', 'b', 'c'
     }
    

    In this example, value is the actual value of each element in the array, not the index.

In summary, use a for...in loop when you want to iterate over the properties of an object, and use a for...of loop when you want to iterate over the values of an iterable object.

What is the difference between for in and for of loop in arrays?

When it comes to arrays in JavaScript, the for...in and for...of loops behave differently:

  1. for...in Loop: This loop is used to iterate over the enumerable properties of an object. In the case of an array, these properties are the indices of the array. Here’s an example:

     let arr = ['a', 'b', 'c'];
     for (let index in arr) {
       console.log(index); // Logs '0', '1', '2'
     }
    

    In this example, index is the index of each element in the array, not the actual value. If you want to access the value, you would use arr[index].

  2. for...of Loop: This loop is used to iterate over iterable objects like arrays, strings, maps, etc. In the case of an array, it provides access to the values of the array, not the indices. Here’s an example:

     let arr = ['a', 'b', 'c'];
     for (let value of arr) {
       console.log(value); // Logs 'a', 'b', 'c'
     }
    

    In this example, value is the actual value of each element in the array, not the index.

In summary, use a for...in loop with an array when you want to iterate over the indices of the array, and use a for...of loop when you want to iterate over the values of the array.

What is the difference between for in and for of loop in objects

When it comes to objects in JavaScript, the for...in and for...of loops behave differently:

  1. for...in Loop: This loop is used to iterate over the enumerable properties of an object. It provides access to the property names of the object, not the actual values. Here’s an example:

    JavaScript

     let obj = {a: 1, b: 2, c: 3};
     for (let prop in obj) {
       console.log(prop); // Logs 'a', 'b', 'c'
     }
    

    In this example, prop is the property name, not the value. If you want to access the value, you would use obj[prop].

  2. for...of Loop: This loop is used to iterate over iterable objects like arrays, strings, maps, etc. However, a standard JavaScript object is not iterable by default, so if you try to use a for...of loop with an object, you will get an error:

    JavaScript

     let obj = {a: 1, b: 2, c: 3};
     for (let value of obj) { // TypeError: obj is not iterable
       console.log(value);
     }
    

    If you want to iterate over the values of an object, you would need to provide an iterable representation of the object, such as an array of its values or entries.

What is the difference between for in and for of loop in strings

When it comes to strings in JavaScript, the for...in and for...of loops behave differently:

  1. for...in Loop: This loop is used to iterate over the enumerable properties of an object. In the case of a string, these properties are the indices of the string. Here’s an example"

     let str = 'abc';
     for (let index in str) {
       console.log(index); // Logs '0', '1', '2'
     }
    

    In this example, index is the index of each character in the string, not the actual character. If you want to access the character, you would use str[index].

  2. for...of Loop: This loop is used to iterate over iterable objects like arrays, strings, maps, etc. In the case of a string, it provides access to the characters of the string, not the indices. Here’s an example:

     let str = 'abc';
     for (let char of str) {
       console.log(char); // Logs 'a', 'b', 'c'
     }
    

    In this example, char is the actual character at each position in the string, not the index.

When to Use Which Loop?

The for...of loop is generally the better choice for iterating over objects. It is more reliable than the for...in loop because it only iterates over the enumerable properties of an object. This means that it will not iterate over non-enumerable properties or properties that have been inherited from the object's prototype.

The for...in loop can be useful in some cases, such as when you need to iterate over all of the properties of an object, including non-enumerable properties and properties that have been inherited from the object's prototype.

Wrapping Up

Loops are a fundamental part of programming in JavaScript. They allow us to perform tasks repeatedly and efficiently. Whether you’re using a for...in loop to explore an object or a for...of loop to iterate through an iterable, understanding these loops will make you a better JavaScript programmer.

Try creating your objects and arrays and use for...in and for...of loops to explore them. Happy Javascripting! 😊

Did you find this article valuable?

Support Subhro Kr by becoming a sponsor. Any amount is appreciated!