Array Methods: forEach, map, filter, find
In this lesson, we will introduce four methods used for iterating over array elements: forEach, map, filter, and find.
forEach
forEach executes a provided function once for each array element.
For example, using forEach, you can sequentially print out all the items in an array.
const fruits = ['Apple', 'Banana', 'Cherry']; fruits.forEach(function (fruit) { console.log(fruit); });
map
map applies the given function to each item of the array and creates a new array with the results.
For instance, you can use map to double all numbers in an array.
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(function (num) { return num * 2; }); console.log(doubled); // [2, 4, 6, 8]
filter
filter creates a new array with all items that meet the given condition.
For example, you can use filter to extract only even numbers.
const numbers = [1, 2, 3, 4]; const evens = numbers.filter(function (num) { return num % 2 === 0; }); console.log(evens); // [2, 4]
find
find returns the first item in an array that satisfies the provided condition.
If no matching item is found, it returns undefined.
For example, in the given array, you can find the first number greater than 10.
const numbers = [5, 12, 8, 130, 44]; const found = numbers.find(function (num) { return num > 10; }); console.log(found); // 12
The forEach method iterates over each element of an array, executing a given function, and returns a new array.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result