Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

Loop (forEach) over an array in JavaScript

Posted on December 14, 2024 By Admin No Comments on Loop (forEach) over an array in JavaScript

Loop (for each) over an Array in JavaScript: A Detailed Guide

When working with arrays, one of the most essential tasks is iterating over their elements. There are several methods to loop through an array in JavaScript, and in this article, we’ll dive deep into these approaches, focusing on the forEach() method as well as other alternatives.

1. Introduction to Looping Over Arrays

When working with arrays, looping through them allows you to perform operations like modifying elements, calculating sums, filtering data, or even transforming each element into a new form. JavaScript offers several built-in ways to loop through arrays, each suited for different use cases.

2. Using the forEach() Method

The forEach() method is a built-in JavaScript function used to iterate over all elements of an array. Unlike traditional for loops, forEach() is more concise and functional in style.

array.forEach(function(element, index, array) {
    // Your code here
});

Where –

  • element: The current element being processed.
  • index: The index of the current element (optional).
  • array: The array that forEach is iterating over (optional).
let arr = [10, 20, 30, 40, 50];

arr.forEach(function(item) {
    console.log(item);
});

/* Output:
10
20
30
40
50
*/

Use Cases

  • Simple iteration: Use forEach() when you need to loop through an array and perform an operation on each element without returning anything.
  • Side-effects: Ideal when you need to execute a function that does not need to return a value, such as logging or updating elements in the DOM.

Notes:

  • forEach() does not return a new array. It returns undefined.
  • It cannot be stopped or broken early; all elements are always processed.
  • It is slower than a traditional for loop in terms of performance.
JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Questions

Post navigation

Previous Post: How Can I Remove a Specific Item from an Array in JavaScript?
Next Post: Sort Array of Objects by String Property Value in JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme