JavaScript – forEach

JavaScript – forEach is used to execute a given function for each element in the Array. In this tutorial, we shall learn the syntax and usage of forEach with Examples.

Syntax

The syntax of forEach() function is

arr.forEach(function callbackFun(currentValue[, index[, array]]) {
    //set of statements
}[, thisArg]);

where

Keyword/Variable/ParameterMandatory/OptionalDescription
arrMandatoryThe array containing elements.
callbackFunOptionalFunction which has to be applied for each element of array
currentValueMandatoryThe current element’s value for which callback function is being applied.
indexOptionalIndex of the current element.
arrayOptionalArray, on which forEach is being applied.
thisArgOptionalthisArg is provided to forEach. Used as this value in forEach.arr.forEach(callbackFun, thisArg);

Example – JavaScript forEach

var names = ['Arjun', 'Akhil', 'Varma'];
      
names.forEach(function printing(element, index, names){
	msg += element + '<br>';
});
Try Online

Try Online

Conclusion

In this JavaScript Tutorial, we have learnt to use Array.forEach method to apply a function for each element of the array.