forEach()

Introduction
The forEach method in JavaScript is used to loop through elements of an array. It executes a provided function once for each element, making it simple and readable for handling repetitive tasks.

What is forEach()
forEach is an array method that allows you to iterate over each item without writing a traditional loop. It does not return a new array and is mainly used for performing actions like displaying or modifying data.

Syntax
array.forEach(function(currentValue, index, array) {
// code to execute
});

Parameters Explanation
currentValue refers to the current element being processed
index is the position of the element in the array
array is the original array being looped through

Basic Example

let numbers = [1, 2, 3, 4];

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

This example prints each number in the array to the console.

Example with Index

let fruits = ["Apple", "Banana", "Mango"];

fruits.forEach(function(item, index) {
console.log(index + ": " + item);
});

This shows both the index and value of each item.

Arrow Function Example

let names = ["Ali", "Sara", "Ahmed"];

names.forEach(name => console.log(name));

Using arrow functions makes the code shorter and cleaner.

Common Use Cases
Displaying data from an array on a webpage
Performing calculations on each element
Updating values in an array
Logging or debugging data

Important Notes
forEach does not return a new array
You cannot use break or continue inside forEach
It is best used when you want to perform an action for each element

Difference Between forEach and map
forEach is used for executing a function on each item
map returns a new array after transforming each element

Conclusion
The forEach method is an essential tool in JavaScript for working with arrays. It improves code readability and simplifies iteration tasks, especially for beginners.

Home ยป Intermediate JavaScript > Arrays > forEach()