Onjsdev

Share


For vs Foreach vs For..In vs For..of


By onjsdev

Dec 25th, 2023

JavaScript provides a variety of loops to execute a set of code multiple times. The most popular loop structures are for, forEach , for in and for of

Although they may appear similar, there are differences between them, making them suitable for different use cases. In this article, we will compare these loops structures and discuss when to use each.

For Loops

The for loop is a traditional loop that is widely used in JavaScript. It consists of three parts:

  • The initialization statement initializes a variable that will be used in the loop.
  • The condition checks if the loop should continue executing.
  • The update statement is executed after each iteration and is used to update the loop variable.

Here is a simple example of a for loop that prints the numbers 0 to 9:

for (let i = 0; i < 10; i++) {
  console.log(i); // 0, 1, 2 ... 9
}

The for loop is ideal to use for:

  • Iterating over arrays and objects with a known length.
  • Requiring more control over the iteration, such as skipping iterations, breaking out of the loop early or including index access and conditional termination

ForEach

The forEach loop is a higher-order function that is available on arrays in JavaScript. It executes a provided function once for each element in the array. The provided function accepts three parameters:

  • the current element,
  • the index of the element,
  • the array itself.

Here is an example of a forEach loop that prints the numbers 0 to 9:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

numbers.forEach(function(number) {
  console.log(number);
});

The foreach loop is ideal to use for:

  • Iterating over arrays and performing a set of operations on each element.
  • Writing loop easier to read and understand.

For ... In

The for...in loop is a type of loop used in JavaScript to iterate over the properties of an object. It is also known as an enumeration loop. The loop iterates over each enumerable property of an object, executing the code block for each property.

Here is an example:

var person = {
  name: "John",
  age: 30,
  gender: "Male"
};

for (var key in person) {
  console.log(key + ": " + person[key]);
}
/*
name: John
age: 30
gender: Male
*/

The for in loop is ideal to use for:

  • Accessing object properties and their values.

For ... Of

In JavaScript, the for...of loop is used to iterate over iterable objects such as arrays, strings, maps, sets and other collections.

Here's an example of using for...of to loop over an array of numbers:

const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
  console.log(number);

The for of loop is ideal to use for:

  • Iterating array values directly in modern JavaScript.

Key Points and Best Practices:

  • Array iteration: Prefer for...of for modern, clean iteration over array values.
  • Index access: Use for loop if you need to access and modify array indices.
  • Object properties: Use for...in to iterate over object properties, but be mindful of inherited properties.
  • Conciseness: forEach() offers a succinct approach for simple array operations.
  • Control flow: for and for...of allow break, continue, and return for more control over the loop.
  • Performance: While performance differences are often negligible, for and for...of might be slightly faster than forEach() in certain cases.

Here is the table that summarize the comprasion

FeatureforforEach()for...infor...of
Iterates overNumbersArray elementsObject propertiesIterable values
Syntaxfor (let i = 0; i < length; i++)array.forEach(function(element))for (let key in object)for (let value of iterable)
Index accessYesNoYesNo
Early terminationYes (break, continue)NoYes (break)Yes (break)
Object propertiesNoNoYesNo
Best forPrecise control, index accessSimple array operationsAccessing object propertiesArray value iteration (modern JS)

Conclusion

In this article, we have discussed different types of loop structures in Javascript and differences between them. You can choose the loop that best suits your specific needs based on these considerations.

Thank you for reading