Using .forEach() , .map() and .filter() in JavaScript
What, Why, and When you should use the Array methods .forEach() , .map() and .filter()
What is an Array Method in JavaScript?
The more you work with Arrays, the more likely you will come across three particular Array Methods called .map()
,.filter()
and forEach()
.
Previously when you have looked to loop or iterate through an array you would probably use a for
loop or for...of
loop to achieve this.
.forEach()
, .map()
and .filter()
can be considered another way of iterating or looping through arrays and performing a specific function on each element of the array.
These are known as Array Methods.
Why should we use Array Methods?
Uses fewer lines of code but more importantly...
More readable! map(), filter(), and forEach() all have names that say exactly what they do, whereas a
for
orfor...of
loop doesn't immediately tell us what it does when it loops through an array.You can name the element you are performing an action on instead of using the index. For instance, if you were iterating through an array called
animals
you could use the wordanimal
to refer to the parameter instead ofanimals[i]
.
.forEach()
What is this method?
The .forEach()
method is very similar to a for
loop. The two examples below basically do the same thing.
const alphabet = ['a', 'b', 'c', 'd', 'e'];
for (let i = 0; i < alphabet.length; i++) {
console.log(alphabet[i]);
}
// You will see 'a', 'b', 'c', 'd', 'e' on separate lines in the console
const alphabet = ['a', 'b', 'c', 'd', 'e'];
alphabet.forEach(function(letter) {
console.log(letter);
});
// You will see 'a', 'b', 'c', 'd', 'e' on separate lines in the console
As the name suggests, the function inside the parentheses of the .forEach()
method is executed 'for each' element of the array.
When should we use this?
.forEach()
should be used whenever there's a function that you would like to perform on each element in an array.
Bear in mind...
.forEach()
doesn't create a new array and it returns undefined
!
So if you try to do something like this...
const alphabet = ['a', 'b', 'c', 'd', 'e'];
const capitalised = alphabet.forEach(function (letter) {
return letter.toUpperCase();
});
console.log(capitalised);
Would log undefined
in the console.
.map()
What is this method?
.map()
is a lot like .forEach()
, but it performs a function on each element of an array and then returns those elements in a new array.
const numbers = [1, 2, 3];
const addOne = numbers.map(function (number) {
return number + 1;
});
console.log(addOne); // [2, 3, 4]
The code above returns a new array with each element increased by one.
When should I use this?
Use .map()
whenever you're updating the elements within an array. It's called map because you're mapping over the array.
For example, you might want to add 20% to a list of numbers to represent the total amount including VAT.
const amounts = [5, 10, 12, 15];
const amountsPlusVat = amounts.map(function (amount) {
return amount + (amount * 0.2);
});
console.log(amountsPlusVat); // [6, 12, 14.4, 18]
The .map()
Array Method will always return a new array of the same length as the original array.
.filter()
What is this method?
The .filter()
Array Method iterates or loops through an array and filters out any elements that don't meet the condition set inside the function within the .filter()
call.
For example, in the below case, I am filtering out any numbers that are less than 10 in the array.
const numbers = [
2,
12,
5,
18,
100,
6,
];
const numbersOverTen = numbers.filter(function (number) {
return number > 10;
});
console.log(threeLetterWords); // [12, 18, 100]
The .filter()
function will go through every element in the array to see if it meets the condition number > 10
. It will then take the elements that return true
for the condition and return them in a new array.
When should I use this?
You should use the .filter()
method whenever you weren't to filter out elements in an array based on a certain condition.
For example, perhaps you have an array of objects which represent people, and you only want to include those people who are students:
const people = [
{ name: 'John', age: 24, isStudent: true },
{ name: 'Andy', age: 40, isStudent: false },
{ name: 'Clive', age: 18, isStudent: true },
{ name: 'Hayley', age: 18, isStudent: true },
{ name: 'Carol', age: 30, isStudent: false },
];
const students = people.filter(function(person) {
return person.isStudent === true;
});
console.log(students);
/* [
{ name: 'John', age: 24, isStudent: true },
{ name: 'Clive', age: 18, isStudent: true },
{ name: 'Hayley', age: 18, isStudent: true },
] */
Conclusion
It took me a while to get my head around Array Methods and the idea of having functions inside other functions can also take some getting used to. However, once you get comfortable using them they will become invaluable as you manipulate data and solve problems in JavaScript. A good place to practice using Array Methods and other JavaScript fundamentals is Codewars or FreeCodeCamp. Happy coding!