The Wayback Machine - https://web.archive.org/web/20240824204735/https://www.geeksforgeeks.org/javascript-array-foreach-method/
Open In App

JavaScript Array forEach() Method

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The forEach() method calls a function for each element in an array. It does not return a new array and does not modify the original array. It’s commonly used for iteration and performing actions on each array element.

Syntax:

array.forEach(callback(element, index, arr), thisValue);

Parameters:

This method accepts five parameters as mentioned above and described below:

ParameterDescription
callbackThis parameter holds the function to be called for each array element.
elementThe parameter holds the value of the elements being processed currently.
indexThis parameter is optional, it holds the index of the current value element in the array starting from 0.
arrayThis parameter is optional, it holds the complete array on which forEach is called.
thisArgThis parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used as this for each invocation of the callback function, otherwise undefined is used as default.

Return value:

The return value of this method is always undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function. 

Example 1: In this example, the Array.forEach() method is used to copy every element from one array to another.

JavaScript
// JavaScript to illustrate forEach() method
function func() {

    // Original array
    const items = [12, 24, 36];
    const copy = [];
    items.forEach(function (item) {
        copy.push(item + item + 2);
    });
    console.log(copy);
}
func();

Output
[ 26, 50, 74 ]

Example 2: In this example, the method forEach() calculates the square of every element of the array.

JavaScript
// JavaScript to illustrate forEach() method
function func() {

    // Original array
    const items = [1, 29, 47];
    const copy = [];
    items.forEach(function (item) {
        copy.push(item * item);
    });
    console.log(copy);
}
func();

Output
[ 1, 841, 2209 ]

Supported Browsers:

JavaScript Array forEach() method- FAQs

What is the Array.forEach() method in JavaScript?

The Array.forEach() method executes a provided function once for each array element.

How does the Array.forEach() method work?

The Array.forEach() method takes a callback function as an argument, which is applied to each element of the array. The callback function receives three arguments:

  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element being processed.
  • array (optional): The array forEach() was called upon.

Does Array.forEach() return a new array?

No, Array.forEach() does not return a new array. It always returns undefined.

Does Array.forEach() mutate the original array?

No, Array.forEach() does not mutate the original array. However, if the callback function modifies the array elements, those changes will affect the original array.

What are common use cases for forEach()?

Common use cases include iterating over an array to perform side effects, such as:

  • Logging values to the console.
  • Modifying elements of the array.
  • Making API calls or other asynchronous operations for each element.
  • Performing operations that do not require the creation of a new array, such as updating a UI or accumulating results in a variable outside the array.

Previous Article
Next Article

Similar Reads

JavaScript typedArray.forEach() Method
The typedArray.forEach() is an inbuilt function in JavaScript which executes a given function once for each given typedArray element. Syntax: typedarray.forEach(callback) Parameter: It accepts a parameter "callback" function which produces each element of the new typedArray and this function takes three parameters that are specified below- currentV
1 min read
How to stop forEach() method in JavaScript ?
Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it. Sample example using forEach(): var sum = 0; var number = [90, 4, 22, 48]; number.forEach(myFunction); function myFunction(item) { sum += item; } console.log(sum); Tricks to stop forEach() loop: Method 1:The following method demonstrate
2 min read
What is forEach() method in JavaScript ?
The forEach() method in JavaScript is used to iterate over the elements of an array and execute a provided callback function once for each element. It provides a convenient way to perform operations on each element of an array without the need for a traditional for loop. Syntax:array.forEach(callback(element, index, arr), thisValue);Parameters:call
2 min read
JavaScript Set forEach() Method
The set.forEach() method is used to execute the function which is taken as a parameter and applied for each value in the set, in insertion order. Syntax:forEach(function(value, key, set) { /* ... */ }, thisArg)Parameters:Callback function: The function will be executed for each value and it takes three arguments.Value, Key: Value should be the curr
3 min read
JavaScript Map forEach() Method
JavaScript Map.forEach method is used to loop over the map with the given function and executes the given function over each key-value pair. Syntax:myMap.forEach(callback, value, key, thisArg)Parameters:This method accepts four parameters as mentioned above and described below: callback: This is the function that executes on each function call.valu
3 min read
How to Change Values in an Array when Doing foreach Loop in JavaScript ?
The forEach loop in JavaScript is one of the several ways to iterate through an array. ForEach method is different from all other looping methods as it passes a callback function for each element in the array. So, the possible approach to change the values in the array when doing foreach method in JavaScript, the method will not directly change the
3 min read
How to iterate an Array using forEach Loop in JavaScript?
Iterating through an array in JavaScript can be done in multiple ways. One of the most common methods is using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method. This method is different from the traditional approach as it uses a functional approach. This approach prov
2 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function( currentValue, index, array);Parameters:ParameterD
3 min read
ES6 | Array forEach() Method
When working with arrays, it's widespread to iterate through its elements and manipulate them. Traditionally this can be done using for, while or do-while loops. The forEach will call the function for each element in the array. Syntax: array.forEach( callback, thisObject ) Parameter: This method accept only two parameter mentioned above and describ
3 min read
TypeScript Array forEach() Method
The forEach() method in TypeScript calls a specified function for each element in an array. It takes a callback function executed on each element and an optional thisObject parameter to use as this context. It enhances iteration readability and efficiency. Syntaxarray.forEach(callback[, thisObject])ParametersThis method accepts two parameters as me
2 min read
How to use async/await with forEach loop in JavaScript ?
Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.
2 min read
Difference between forEach() and map() loop in JavaScript
When we work with an array, it is an essential step to iterate on the array to access elements and perform some kind of functionality on those elements to accomplish any task. For this loops like ForEach() and Map() are used. In this article, we are going to learn the difference between the forEach() and map() loops in JavaScript. JavaScript forEac
3 min read
How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
Difference between forEach and for loop in Javascript
In JavaScript, both forEach and for loops are used to iterate over arrays or collections, but they differ in usage and behavior. forEach is a higher-order function that simplifies iteration with built-in array methods, while for loops offer more control, flexibility, and broader application. For LoopThe for loop is one of the original ways to itera
4 min read
HTML DOM NodeList.forEach() Method
The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order. Syntax: NodeList.forEach(callback, currentValue); Parameters: Callback: A function to execute on each element of NodeList. It accepts 3 parameters:currentValue: The current element to be processed in NodeLis
2 min read
How to break forEach() method in Lodash ?
The Lodash _.forEach() method iterates over elements of the collection and invokes iterate for each element. In this article, we will see how to break the forEach loop in ladash library. Syntax: _.forEach( collection, [iterate = _.identity] ) Parameters: This method accepts two parameters as mentioned above and described below: collection: This par
2 min read
Ember.js EmberArray forEach() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of web
4 min read
Ember.js MutableArray forEach() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
6 min read
Ember.js ArrayProxy forEach() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Ember.js Ember.NativeArray forEach() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
6 min read
Lodash _.forEach() Method
Lodash _.forEach() method iterates over elements of the collection and invokes iteratee for each element. Syntax:_.forEach(collection, [iteratee = _.identity]);Parameters:collection: This parameter holds the collection to iterate over.iteratee: It is the function that is invoked per iteration.Return Value: This method returns the collection. Exampl
1 min read
Short Circuit Array.forEach Like Calling Break
The Array.forEach() loop is a built-in method in JavaScript that is used to reiterate over any array and execute a function for each element of the array. The main purpose of this method is to perform some operation on each element of the array without having to manually iterate over it using a loop. The Array.forEach() method is used to execute a
3 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
AngularJS angular.forEach() Function
The angular.forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object. Syntax: angular.forEach(object, iterator, [context])Parameter Values: object: It refers to the object to be iterated.iterator: It
1 min read
Node.js URLSearchParams.forEach()
In URLSearchParams interface, the foreach() method returns an iterator which allows to iterate through all values contained in this object with the help of a callback function. Syntax: searchParams.forEach(callback); Return: It does not return anything, used for invoking the function and iterating through it. Parameters: callback - Input the callba
1 min read
What is the difference between for and Foreach loop in PHP ?
Loops can be used to iterate over collection objects in PHP. The for and foreach loop can be used to iterate over the elements. for loopThe for loop works at the end of the given condition. It is used for the implementation of variables and works in a single way. The for loop does not work in the case of associative arrays. A for loop basically con
3 min read
Node forEach() function
forEach() is an array function Node that is used to iterate over items in a given array. Syntax: array_name.forEach(function)Parameter: This function takes a function (which is to be executed) as a parameter. Return type: The function returns an array element after iteration. The program below demonstrates the working of the function: Example 1: Be
1 min read
How to check foreach Loop Key Value in PHP ?
In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as Table of Content Using the for-each loop with simple valuesUsing the foreach loop with Key-Value pairsUsing array_keys Function to Access Keys and ValuesUsing array_walk Function for IterationUsing the for-each loop with simple valuesWe can u
3 min read
How to Break Foreach Loop in PHP?
Breaking a foreach loop consists of terminating the execution of the loop prematurely based on a certain condition. In this article, we will explore and learn two approaches to breaking for each loop in PHP. Below are the approaches to break for each loop in PHP: Table of Content Using break KeywordUsing goto KeywordUsing array_filter FunctionAdded
3 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read