A Deep Dive into the forEach() Method in JavaScript Arrays

Explore the power of the forEach() method in JavaScript array with our in-depth guide.

In this article, you’ll learn how this built-in function can simplify array iteration, making your code cleaner and more efficient.

Dive into practical examples and discover how array.forEach() can transform your JavaScript programming.

What is forEach() method in JavaScript?

The array.forEach() method in JavaScript is a handy tool that allows you to loop over each element in an array.

It’s like taking a tour of each item in the array one by one. For each stop (or element), it performs a specific action that you define.

This action is defined by a function you provide, which gets called for each element. This function can take up to three parameters: the current element, its index, and the entire array.

One thing to note about forEach() is that it doesn’t change the original array. Also, forEach() doesn’t skip over empty spots in the array.

It visits every index from start to finish, even if some stops don’t have any elements.

Here’s an example:

const subjects = ["English", "Math", "Programming"];
subjects.forEach(function(item, index, array) ✅  {
  console.log(item, index); 
});

In this code, forEach() is taking us on a tour of the subjects array. At each stop, it logs a message to the console with the subject and its position in the array.

Output:

English 0
Math 1
Programming 2

Here’s another example:

let sum = 0; // Initialize sum to 0
const numbers = [10, 20, 30, 40, 50]; // The array of numbers
numbers.forEach(sampleFunction); ✅ // Call sampleFunction for each number in the array

function sampleFunction(item) {
  sum += item; // Add each number to the sum
}


console.log(sum);

Output:

150

Syntax

array.forEach(function(currentValue, index, array), thisValue) 

Parameters

function(currentValue, index, array):

A function that gets executed for every element in the array.

currentValue (required)

This represents the current element’s value.

index (optional)

This is the current element’s index

array (optional)

This is the array to which the current element belongs.

thisValue (optional)

A value is to be passed to the function as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value.

Return value

The forEach() method does not return a value. It always returns undefined.

📌Please take note that forEach() method does not mutate the array on which it is called (but function, if invoked, may do so).

Also, unlike map() or reduce(), it always returns undefined and is not chainable. The typical use case of forEach() is to execute side effects at the end of a chain.

How to Use forEach() to Iterate/loop an Array in JavaScript

The array.forEach() method in JavaScript is used to iterate or loop over an array.

Here’s a simple guide on how to use the forEach() method to iterate or to loop over an array in JavaScript:

Define your array

First, you need an array. This could be an array of numbers, strings, objects, etc.

For example:

const subjects = ["English", "Math", "Programming"]; 

Define your function

Next, you need a function that will be applied to each element in the array.

This function takes up to three arguments: the current element, its index, and the entire array.

For example:

function printSubject (subject, index) {
  console.log(`Subject number ${index + 1} is ${subject}`);
}

Use forEach()

Now, you can use forEach() to apply your function to each element in the array.

For example:

subjects.forEach(printSubject);

When you run this code, it will print each subject in the array along with its position (index + 1).

Here’s the complete code of array.foreach in JavaScript:

const subjects = ["English", "Math", "Programming"];

function printSubject (subject, index)  {
  console.log(`Subject number ${index + 1} is ${subject}`);✅ 
}

subjects.forEach(printSubject);✅ 

Output:

Subject number 1 is English
Subject number 2 is Math
Subject number 3 is Programming

Here’s another illustration on how you can use it:

// Define your array
let samplearray = [10, 20, 30, 40, 50];

// Use forEach to iterate over the array
samplearray.forEach(function(element) {
    console.log(element); // This will log each element of the array
});

As you can see in our example code, the forEach() method is called on the array and for each element in the array, it executes the provided function, which logs the element to the console.

Output:

10
20
30
40
50

Moreover, the function that you pass into the forEach() method accepts up to three arguments: the current element, the index of the current element, and the array that forEach() was called upon.

Here’s an example:

let samplearray = [10, 20, 30, 40, 50];

samplearray.forEach(function(element, index, array) {
    console.log(`Element: ${element}, Index: ${index}, Array: ${array}`); 
});

Output:

Element: 10, Index: 0, Array: 10,20,30,40,50
Element: 20, Index: 1, Array: 10,20,30,40,50
Element: 30, Index: 2, Array: 10,20,30,40,50
Element: 40, Index: 3, Array: 10,20,30,40,50
Element: 50, Index: 4, Array: 10,20,30,40,50

This output shows the value of each element in the array (element), its position in the array (index), and the entire array (array) for each iteration of the forEach() loop.

This can be useful for debugging or understanding how forEach() works.

Frequently Asked Question (FAQs)

Can we use forEach for array in JavaScript?

Absolutely, yes! The forEach() method is a tool in JavaScript that is made for going through each item in an array.

How to store forEach value in array in JavaScript?

While forEach() is great for doing something with each item in an array, it doesn’t save the results.

If you want to save the results of doing something to each item in an array, you might want to use the map() method.

This method creates a new array with the results of doing something to each item in the original array.

Does forEach work with arrays?

Yes, it does! The forEach() method is a function that’s built into arrays in JavaScript. It’s used to do something with each item in an array.

Conclusion

In conclusion, the article delves into the functionality of the JavaScript forEach() method, which serves as a powerful tool for iterating over elements in an array.

By offering a clear and concise way to loop through array items, forEach() enhances code readability and efficiency.

It allows the execution of a specified action for each element, guided by a user-defined function.

While maintaining the original array unchanged, the method visits all indices sequentially, even those without elements.

We are hoping that this article provides you with enough information that helps you understand the JavaScript foreach in array.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment