JavaScript Tutorials

JavaScript Array forEach()
Syntax & Examples

Array.forEach() method

The forEach() method of the Array class in JavaScript calls a provided function once for each element in an array, in ascending order.


Syntax of Array.forEach()

There are 2 variations for the syntax of Array.forEach() method. They are:

1.
forEach(callbackFn)

Parameters

ParameterOptional/RequiredDescription
callbackFnrequiredA function to execute on each element in the array. It takes three arguments: element, index, and array.

This method calls a function for each element in the calling array.

Returns value of type undefined.

2.
forEach(callbackFn, thisArg)

Parameters

ParameterOptional/RequiredDescription
callbackFnrequiredA function to execute on each element in the array. It takes three arguments: element, index, and array.
thisArgoptionalA value to use as this when executing callbackFn.

This method calls a function for each element in the calling array, using thisArg as the value of this inside callbackFn.

Returns value of type undefined.



✐ Examples

1 Using forEach() method to log each element

In JavaScript, we can use the forEach() method to log each element of an array to the console.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the forEach() method with a callback function that logs each element to the console.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));

Output

1
2
3
4
5

2 Using forEach() method to log each element with its index

We can use the forEach() method to log each element and its index in an array to the console.

For example,

  1. We define an array variable arr with elements ['a', 'b', 'c'].
  2. We use the forEach() method with a callback function that logs each element and its index to the console.

JavaScript Program

const arr = ['a', 'b', 'c'];
arr.forEach((element, index) => console.log(`Index: ${index}, Element: ${element}`));

Output

Index: 0, Element: a
Index: 1, Element: b
Index: 2, Element: c

3 Using forEach() method with a thisArg

We can use the forEach() method with a thisArg to log each element of an array to the console using a specific context.

For example,

  1. We define an array variable arr with elements [1, 2, 3].
  2. We define an object context with a prefix property set to 'Number:'.
  3. We define a callback function logWithPrefix that logs each element with the prefix property of the context object.
  4. We use the forEach() method with logWithPrefix and context as thisArg.

JavaScript Program

const arr = [1, 2, 3];
const context = { prefix: 'Number:' };
function logWithPrefix(element) {
  console.log(`${this.prefix} ${element}`);
}
arr.forEach(logWithPrefix, context);

Output

Number: 1
Number: 2
Number: 3

Summary

In this JavaScript tutorial, we learned about forEach() method of Array: the syntax and few working examples with output and detailed explanation for each example.