JavaScript Glossary - Lesson #8

JavaScript Array .forEach() Method

The forEach() method takes a function that performs an action on each of the elements in this array.

[1, 2, 3, 4, 5].forEach(function(number){
    console.log(number * 2)
// Create array of numbers
let arr = [1, 2, 3, 4, 5];

// Double each number and display
arr.forEach(function(number) {
  console.log(number * 2);
// 2
// 4
// 6
// 8
// 10
array.forEach(callback[, thisArg])

callback This is the function which performs an action on each element. This function can take three parameters.

  • value: the value currently being processed in the array.
  • index: this is the index of the value being processed - optional.
  • array: this is the parent array running the forEach method - optional.

thisArg This is an optional value to be used as the this value for the array - optional

The method returns undefined and doesn't mutate the original calling array.

const names = ['Johnny', 'Pete', 'Sammy']

names.forEach(name => {

The forEach method can be used to copy the content of an array into a new array. Several ways exist to do this but the forEach method affords the ability to modify each element before being copied.

// Create new array
const students = ['Jerry', 'Mary', 'Brenda', 'John'];

// Create empty array to be copied into
const classA = [];

// Copy names into new array
students.forEach(student => {

// output: ["Jerry","Mary","Brenda","John"]

Using the forEach method in place of a for loop. Since it has a simpler syntax, it is mostly used in place of a regular for loop.

// Array of dates
const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

// with a for loop
for (i = 0; i < days.length; i++) {


// with forEach
days.forEach(day => {
// output:
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday
// ----------------------
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)