Faster, better AI-powered code reviews. Start your free trial!  
Faster, better AI-powered code reviews.
Start your free trial!

Get high quality AI code reviews

Javascript: each vs in

70

Table of Contents

JavaScript is a powerful and versatile programming language that has become ubiquitous in web development. As developers, we often need to iterate over arrays and objects to perform various operations, and there are two popular ways to do it: “for…each” and “for…in” loops.

While they might seem similar, there are subtle differences between these two methods that can significantly impact your code’s performance and functionality.

In this article, we will explore the differences between “for…each” and “for…in” loops in JavaScript and when to use each one to write more efficient and effective code. So, whether you’re a seasoned JavaScript developer or just starting, keep reading to improve your coding skills and enhance your understanding of these crucial programming concepts.

Overview of the differences between each and in

In JavaScript, “for…each” and “for…in” are both used to iterate over arrays and objects, but they have some fundamental differences that developers should be aware of.

The “for…each” loop is used to iterate over the values of an array or iterable object, executing the loop body for each value. It’s a more modern way of iterating and was introduced in ECMAScript 5. Unlike “for…in” loops, “for…each” doesn’t iterate over object properties, but only works with arrays and iterable objects.

On the other hand, the “for…in” loop is used to iterate over the properties of an object. It executes the loop body for each property in the object, including the inherited properties from the object’s prototype. This loop is useful when working with objects but not recommended when iterating over arrays as it may produce unexpected results.

To better understand the differences between “for…each” and “for…in” loops in JavaScript, let’s explore some examples.

Example 1: “for…each” loop

const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
  console.log(number);
});

In this example, we create an array of numbers and use the “forEach” method to iterate over each value in the array. The loop body is a callback function that prints each number to the console. Since we are only interested in the array values, “for…each” loop is the appropriate method to use.

Example 2: “for…in” loop

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

In this example, we create an object “person” with three properties, and we use a “for…in” loop to iterate over each property in the object. The loop body uses bracket notation to access the value of each property and print it to the console. “for…in” is the appropriate method to use when working with objects.

Example 3: “for…each” vs “for…in” with arrays

const numbers = [1, 2, 3, 4, 5];
numbers.test = 'test';
numbers.foo = function() { console.log('foo'); };
console.log('for...each:');
numbers.forEach((number) => {
  console.log(number);
});
console.log('for...in:');
for (const key in numbers) {
  console.log(`${key}: ${numbers[key]}`);
}

In this example, we add two properties to the “numbers” array, “test” and “foo”, and use both “for…each” and “for…in” loops to iterate over the array. The loop body in “for…each” prints only the array values, while the loop body in “for…in” prints all properties of the array, including the “test” and “foo” properties. This is because “for…in” loops iterate over all properties of an object, including those added later, whereas “for…each” only iterates over the existing values in the array or iterable object.

Overall, “for…each” is best used when working with arrays or iterable objects, while “for…in” is best used when working with objects and iterating over their properties.

Advantages of using each over in

Here are the advantages of using “for…each” over “for…in” loops.

  • Iterates only over the values of an array or iterable object: The “for…each” loop iterates over the values of an array or iterable object without including any additional properties added to the object. This feature ensures that any extra properties added to an array or iterable object do not affect the iteration process. This makes “for…each” ideal for iterating over data structures where additional properties may be added to the object.
  • More efficient when working with arrays or iterable objects: “For…each” loops are generally more efficient than “for…in” loops when working with arrays or iterable objects. This is because “for…each” loops do not check for inherited properties or properties added later. This makes them faster and more efficient when iterating over large arrays or iterable objects.
  • Easier to read and write: The syntax of “for…each” is simple and concise, making it easier to understand and maintain. It eliminates the need to use bracket notation to access object properties, which can be error-prone. This makes “for…each” a more readable and writable method when compared to “for…in” loops.
  • Eliminates potential errors: One of the issues with “for…in” loops is that they can potentially access inherited properties or properties added later, which can lead to errors. “for…each” loops avoid this issue by iterating only over the values of an array or iterable object. This makes them a safer and more reliable method when compared to “for…in” loops.
  • More appropriate for working with ordered data: “for…each” is more appropriate when working with data that requires specific ordering or has a specific index. This is because “for…each” provides an easier way to access elements based on their index or order. This is particularly useful when working with arrays, where you may need to manipulate data based on its position or index.

Advantages of using in over each

While “for…each” loops have their advantages, “for…in” loops also have their place and can be advantageous in certain situations. Here are some advantages of using “for…in” over “for…each”:

  • Iterates over all properties of an object: One of the primary advantages of “for…in” loops is that they iterate over all properties of an object, including those that are not iterable. This makes “for…in” a more versatile method when working with complex data structures.
  • Allows access to both keys and values: Another advantage of “for…in” loops is that they allow access to both keys and values. This is particularly useful when working with objects, where you may need to manipulate both the keys and values.
  • Provides more flexibility: “for…in” loops provide more flexibility in terms of accessing object properties. This is because “for…in” loops allow the use of bracket notation to access object properties, which can be useful in certain situations.
  • Can be faster for small arrays or objects: “for…in” loops can be faster for small arrays or objects because they don’t have the additional overhead of checking whether the object is iterable or not.
  • Useful for prototype iteration: “for…in” loops can be useful for iterating over an object’s prototype, which is not possible with “for…each” loops

When to Use Each vs In

The choice of which looping structure to use will depend on the specific application. In general, it is best to use the each method when dealing with a known number of items and the in method when dealing with an unknown number of items. For instance, if you are dealing with a finite array or object, it may be more efficient to use the in method rather than writing out each loop individually.

In situations where you are dealing with a large amount of data, it may be more efficient to use the in method as it is faster than writing out each loop. It is also important to consider which type of data structure you are working with when deciding which looping structure to use. If you are dealing with an array or an object, it may be more efficient to use the in method as it provides more flexibility.

When using the in method, it is important to consider the order of the data structure. If the data structure is not ordered correctly, the looping structure may not work as expected. Additionally, it is important to consider the size of the data structure when deciding which looping structure to use. If the data structure is too large, it may be more efficient to use the each method as it is more efficient for larger data sets.

Using each and in together

Using “for…each” and “for…in” loops together can be useful when working with complex data structures that contain both arrays and objects.

Here’s an example of how to use “for…each” and “for…in” loops together:

const myData = {
  name: "John Doe",
  age: 30,
  hobbies: ["reading", "gaming", "coding"],
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
    zip: "12345"
  }
};
// using for...in to iterate over the properties of myData
for (const prop in myData) {
  console.log(`${prop}: ${myData[prop]}`);
   // using for...each to iterate over the hobbies array
  if (prop === "hobbies") {
    myData[prop].forEach(hobby => {
      console.log(`- ${hobby}`);
    });
  }
}

In this example, we have an object called “myData” that contains various properties, including an array of hobbies and an object called “address.” We use a “for…in” loop to iterate over the properties of “myData” and log the property name and value to the console.

Inside the “for…in” loop, we use an “if” statement to check if the current property is “hobbies.” If it is, we use a “for…each” loop to iterate over the hobbies array and log each hobby to the console.

This approach allows us to iterate over all the properties of “myData” and handle the hobbies array separately using a “for…each” loop. By using both “for…each” and “for…in” loops together, we can efficiently work with complex data structures that contain both arrays and objects.

In addition, using the each and in methods together can help to reduce the amount of code you need to write, as you can use the same loop for multiple operations. This can help to make your code more efficient and easier to read.

Tips for Writing Efficient Code with each and in

Writing efficient code is crucial for the performance of your application. Here are some tips for writing efficient code when using “for…each” and “for…in” loops:

  • Avoid Nesting Loops: Nesting “for…each” and “for…in” loops can lead to performance issues, especially if the data structures being iterated over are large. Instead of nesting loops, consider breaking the logic into smaller, more manageable functions.
  • Use Break Statements: When iterating over an array or object, consider using “break” statements to exit the loop once a certain condition is met. This can help to reduce unnecessary iterations and improve the performance of your code.
  • Cache Length Property: When using a “for…each” loop to iterate over an array, consider caching the length property in a variable to avoid calculating it on every iteration. This can help to improve the performance of your code, especially when working with large arrays.
  • Avoid Deleting or Adding Properties: Avoid deleting or adding properties during the iteration process. This can cause unexpected results and slow down your code. If you need to modify the data structure, consider creating a copy and modifying the copy instead.
  • Use for…in with hasOwnProperty: When using “for…in” loops to iterate over an object, use the “hasOwnProperty” method to check if the property belongs to the object or its prototype. This can help to avoid unexpected results and improve the performance of your code.
  • Use Map, Filter, and Reduce: Consider using the “map”, “filter”, and “reduce” methods instead of “for…each” and “for…in” loops when working with arrays. These methods are optimized for performance and can often provide more concise and readable code.

By following these tips, you can write more efficient code when using “for…each” and “for…in” loops, leading to faster and more responsive applications.

Conclusion

In conclusion, “for…each” and “for…in” loops are both useful for iterating over arrays and objects in JavaScript. However, they have different use cases and behavior, and understanding their differences is crucial to writing efficient and effective code.

“For…each” loops are best suited for iterating over the values of an array or iterable object, while “for…in” loops are best for iterating over the properties of an object. Developers should be careful when using “for…in” loops with arrays, as they may produce unexpected results.

By choosing the right loop for the task at hand, developers can improve their code’s performance and functionality.

Anand Das

Anand Das

Anand is Co-founder and CTO of Bito. He leads technical strategy and engineering, and is our biggest user! Formerly, Anand was CTO of Eyeota, a data company acquired by Dun & Bradstreet. He is co-founder of PubMatic, where he led the building of an ad exchange system that handles over 1 Trillion bids per day.

Amar Goel

Amar Goel

Amar is the Co-founder and CEO of Bito. With a background in software engineering and economics, Amar is a serial entrepreneur and has founded multiple companies including the publicly traded PubMatic and Komli Media.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

PEER REVIEW: A New Video Podcast by Engineers, for Engineers

How Can AI Handle My Large Codebase?

Elevate Code Quality with AI: Write Clean, Maintainable Code

Identifying and Fixing Scalability Issues in Pull Requests

Identifying Security Flaws During Pull Request Reviews with AI

Top posts

PEER REVIEW: A New Video Podcast by Engineers, for Engineers

How Can AI Handle My Large Codebase?

Elevate Code Quality with AI: Write Clean, Maintainable Code

Identifying and Fixing Scalability Issues in Pull Requests

Identifying Security Flaws During Pull Request Reviews with AI

From the blog

The latest industry news, interviews, technologies, and resources.

Get Bito for IDE of your choice