Beginners approach to map(), forEach() and filter() function in Javascript
Recently, I've had people, especially my fellow newbies, come to ask about some array prototypes in javascript, it got the point I decided to put up a template that can help me in assisting them, now I am thinking that some other people out there might be having the same problem, so I decided to try and put some of it in an article format, maybe it could help someone someday.
Array.map()
Array.map
is one of the array functions in javascript, you can find more of the array functions here on mdn , Array.map() is written like this:
let array = [1, 4, 9, 16];
let map = array.map(x => x * 2);
console.log(map);
It is basically used to loop through an array and perform an operation on it.
Line by line explanation of the code above.
Let array = [1, 4, 9, 16];
//This line is where the array was initialized or declared. (i.e the array we want to work on), we called it array.
Let map = array.map( x => x*2);
//This line of code is where we work on the array, the array.map() takes in a function, what the function returns is based on the operation that is being performed in the function (The sample above, looped through the array, and multiplied every number in the array by 2).
The sample function above is written in es6 syntax because it is one of the best and easy way to write a function, personally it is more readable, find more about Arrow Functions here
console.log(map);
//The last line is where we try to display our output on the console(the function in line 2 above, performed an operation and stored it in the map), This line here, we are printing the content of the map.
The code above can be re-written as
Let array = [1, 4, 9, 16];
Let map = array.map(function (x) {
return x * 2;
})
console.log(map)
Note:
- Array.map helps you perform an operation on each of the objects of the array.
- It takes in a function.
- Any kind of operation can be done on the array content
- Array.map() can be substituted for array.forEach(), array.filter(), etc.
Another example:
let highScores = [{name: "chike", score: '52'}, {name: "Treasure", score: '92'}, {name: "Precious", score: '22'}]
let highScoresList = highScores.map(scorers => {
return `<h1> ${scorers.name} has ${scorers.score}</h1>`
})
Array.forEach()
Array.forEach
the second array prototype discussed, is mostly confused with the first one, especially to beginners, they both mostly gives the same result, I will try to also highlight the differences between the two in this article.
const names = ["ada", "obi", "peter"];
names.forEach(name => console.log(`my name is ${name}`));
This prototype forEach() performs an operation on every element in the array.
Line by line explanation of the code above.
const names = ["ada", "obi", "peter"];
//Initialization/creation of array called names.
names.forEach(name => console.log(`my name is ${name}`));
//This is where the forEach operation was performed, the code simply makes a complete sentence with the elements of the array.
The code can also be written as:
const names = ["ada", "obi", "peter"]
names.forEach(function(name){
console.log(`my name is ${name}`)
})
Note The forEach code does not create a new array, it simply performs a particular operation or a function on every element of the array, this also means that forEach must not use the return statement.
Differences between forEach and Map
return: The .map() function returns a new array after it has performed an operation on the initial array, while .forEach() returns undefined
Mutability: mutability simply means to change or to alter, the .map() does not change the initial array, rather it performs an operation on it and returns a new array, but the .forEach mutate the array, (not necessarily though, but for beginners, it’s safer to understand it this way).
Performance: Though this depends on the operation you are carrying out, or the amount of data you’re working with, you can check your speed using this code below,
const names = [‘ada’, ‘obi’, ‘peter’];
const startForEach = performance.now()
names.forEach(name => console.log(`my name is ${name}`));
const endForEach = performance.now()
console.log(`Speed [forEach]: ${endForEach - startForEach} miliseconds`)
let array = [1, 4, 9, 16];
const startMap = performance.now()
let map = array.map(x => x * 2);
const endMap = performance.now()
console.log(`Speed [map]: ${endMap - startMap} miliseconds`)
The code above checks the speed of the sample codes I used in explaining map() and forEach(), you can read more about the differences here
Array.Filter()
Array.filter, the last array property/prototype to be discussed on this article is one of the array functions in javascript, Array.filter() code is written like this:
const numbers = [2, 4, 6, 7, 8, 9];
const result = numbers.filter(number => number > 2);
console.log(result);
Just as the name says, array.filter() filters an array and returns a new array with the elements of the array that passes the test that it was passed through.
Line by line explanation of the code
const numbers = [2, 4, 6, 7, 8, 9];
//Just like we did in map and forEach, the array was initialised here,
const result = numbers.filter(number => number > 2);
//this line of code is where the filter operation was performed, the code simply goes through the numbers in the array we created in the first line of code and returns a new array called result. The array has only the numbers that passed the test it was passed through (i.e: any number that is greater than 2 ) contained in it.
console.log(result);
//Just like before, the last line is where we try to display our output on the console.
Another way of writing the code
const numbers = [2, 4, 6, 7, 8, 9];
const result = numbers.filter(function (number) {
return number > 2
})
console.log(result)
Note:
- Array.filter() can not be done on an empty array
- It does not change the original array
- Return an empty array if none of the elements of the array passes the test
Another example:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const filteredWords = words.filter(word => word.length > 6);
console.log(filteredWords);
Thank you for reading, this article is not for detailed/deep learning on the topic, rather it is to give beginners a quick overview on how to get started using those properties/prototypes.