Loops are indefinite while coding using any programming language. While there are many ways to iterate through the list of items be it an array or objects, forEach method comes in handy for easily looping through the items. We will be going to see the difference between forEach() and map() functions in this article and these methods can be used based on their behaviour.
A forEach function is normally used to loop through the array thereby accessing each item in the array one by one. The basic syntax for the forEach function is as follows:
const numbers = [5, 10, 15, 20, 25, 30]; numbers.forEach(printMyNumbers); function printMyNumbers(number){ console.log(number); }
When you execute the above code in Google developer console, it will loop through the numbers array and print each numbers line by line like the following output:
The forEach method will not return any value and can be used only to loop through i.e. only to access each of the elements in the array and hence cannot modify the existing array or create a new array based on the existing array.
The map() function is used to modify an existing array and thereby creates a new array out of the existing array. The map() function will only modify the array upon which it acts and creates a new array and will not disturb the existing array. map() function will not make any changes to the existing array and all the changes that it makes will be made available only in the new array that it returns as a return value.
Below is an example of map() function:
const numbers = [2, 4, 6, 8]; const newNumbers = numbers.map(squareMyNumbers) function squareMyNumbers(number) { return number * number; } console.log(numbers); console.log(newNumbers);
When you execute the above function the numbers are multiplied by itself and then returned back the a new array variable newNumbers. Upon printing the variables “numbers” and “newNumbers”, we can notice that the old variable is not changed and only a new array is created by squaring the numbers:
Thus the difference between forEach() and the map() functions.