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.

js
[1, 2, 3, 4, 5].forEach(function(number){
    console.log(number * 2)
})
js
// 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
js
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.

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

names.forEach(name => {
  doSomethingWithName(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.

js
// 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 => {
  classA.push(student)
});

console.log(classA);
// 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.

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

// with a for loop
for (i = 0; i < days.length; i++) {
  console.log(days[i]);
}

console.log('----------------------')

// with forEach
days.forEach(day => {
  console.log(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 Scotch.io which was acquired.

Comments

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