The Difference Between Javascript ForEach(), Map() and Filter() Array Methods
Functions are usually passed into array methods and called on elements within the array.This is actually the array in which the method is called. wwe shall examine these array methods in details.
ForEach()
Array's ForEach() method takes in a callback function and invokes that callback function for each element in the array.Thus, iterates through an array similar to using a for loop. Check out its signature:
array.ForEach(function callback(currentValue, index, array) {
// Function code goes in here
})
This callback function itself receives the arguments: the current array element, its index, and the entire array itself.
Asumming we have a simple function, logIfOdd(), that takes in a single number and logs it to the console if that number is an odd number:
function logIfOdd(n) {
if (n % 2 !== 0) {
console.log(n);
}
}
logIfOdd(2);
// (nothing is logged)
logIfOdd(3);
// 3
If 2 is passed into the function, logIfOdd() does not output anything to the console because 2 is an even number. However, when 3 is passed into the function, 3 is logged to the console because it's an odd number. The logIfOdd() function works great for individual numbers, but let consider checking an entire array and log only the odd numbers within it?
[3, 7, 4, 8, 12, 13]
We can iterate through the above array with forEach() and simply pass it the logIfOdd() function!
[3, 7, 4, 8, 12, 13].forEach(function logIfOdd(n) {
if (n % 2 !== 0) {
console.log(n);
}
});
// 3
// 7
// 13
In the above array, only the numbers that are odd numbers are printed to the console. But what really happended: logIfOdd() is a function and is passed in as an argument to forEach(). forEach() then invokes logIfOdd() for each element in the array (i.e., [3, 7, 4, 8, 12, 13]), which outputs 3, 7, and 13. Keep in mind that it's quite common to pass an anonymous function as an argument in forEach() as well:
[3, 7, 4, 8, 12, 13].forEach(function (n) {
if (n % 2 !== 0) {
console.log(n);
}
});
// 3
// 7
// 13
Alternatively, it's possible to simply pass in just the name of the function as well (i.e., assuming the function was already defined, of course).
[3, 7, 4, 8, 12, 13].forEach(logIfOdd);
// 3
// 7
// 13
The three different ways shown each produce the same output (i.e., logging 3, 7, and 13 to the console).
Map() Method
Array's map() method is similar to forEach() in that it invokes a callback function for each element in an array. However, it should be noted that the map() method returns a new array with retrospect to what's returned from the callback function. see the following:
const names = ['kendrick', 'Thelma', 'Charlse'];
const nameLengths = names.map(function(name) {
return name.length;
});
The We call map() on the names array and pass it an anonymous function as an argument: method works on arrays, so we have to have an array to start with:
const names = ['kendrick', 'Thelma', 'Charlse'];
We call map() on the names array and pass it an anonymous function as an argument:
names.map(function(name) {
return name.length;
});
The function that's passed to We call map() on the names array and pass it an anonymous function as an argument: gets called for each item in the names array! The function receives the first name in the array, stores it in the name variable and returns its length. Then it does that again for the remaining two names. Remember that the key difference between forEach() and map() method is that forEach() doesn't return anything, but when We call map() on the names array and pass it an anonymous function as an argument, it returns a new array with the values that are returned from the function:
const nameLengths = names.map(function(name) {
return name.length;
});
So nameLengths will be a new array: [8, 6, 7]. Again, it is important to understand that we called map() on the names array and pass it an anonymous function as an argument. The map() method returns a new array; it does not modify the original array. This was just a brief overview of how we call map() on the names array and pass it an anonymous function as an argument. For a deeper dive, check out the map() method : on [MDN](developer.mozilla.org/en-US/docs/Web/JavaSc.. "Javascript MDN").
filter() Method
Array's filter() method is similar to the map() method:
- It is called on an array
- It takes a function as an argument
- It returns a new array.
The disparity between them is that the function passed to filter() is used as a test, and only items in the array that pass the test are included in the new array. Consider the following example:
const names = ['kendrick', 'Tesy', 'Charlse'];
const shortNames = names.filter(function(name) {
return name.length < 5;
});
Just as the previous, let's break it down a bit! We have a starting array:
const names = ['kendrick', 'Tesy', 'Charlse'];
We call filter() on the names array and pass it a function as an argument:
names.filter(function(name) {
return name.length < 5;
});
Again, just like with map(), the function that's passed to filter() gets called for each item in the names array. The first item (i.e., 'kendrick') is stored in the name variable. Then the test is performed -- and this is what's doing the actual filtering. First, it checks the length of the name. If it's 5 or greater, then it's skipped (and not included in the new array!). But, if the length of the name is less than 5, then name.length < 5 returns true and the name is included in the new array! And lastly, just like with map(), the filter() method returns a new array instead of modifying the original array:
const shortNames = names.filter(function(name) {
return name.length < 5;
});
console.log(shortNames);
// ['Tesy']
Above, the value of shortNames is the new array: ['Tesy']. Notice that it only has one name in it, because both 'kendrick' and 'charlse' are 8 and 7 characters respectively, and were filtered out. This was just a brief overview of how the filter() method works. For a deeper dive, check out the filter() method on [MDN](developer.mozilla.org/en-US/docs/Web/JavaSc.. "filter method").
Summary
It is imperative to note that JavaScript functions can take in a variety of different arguments. These can include strings, numbers, arrays, and objects. Since functions are first-class functions, functions can also be passed as arguments to a given function. Functions that take in other functions as arguments are called higher-order functions. When Functions are passed as arguments to other functions, they are called callback functions. Callbacks allow you to pass functions without needing to name them these are called anonymous functions, which leads to less variables floating around. They also allow you to delegate calling functions to other functions. Array methods, such as forEach(), map(), and filter(), take advantage of callbacks to execute functions onto a given array's elements. Be studious to check out the list of other array methods from the Javascript [MDN](developer.mozilla.org/en-US/docs/Web/JavaSc.. "Javascript MDN").