This is one of the concepts where people get confused. Every one thinks that Array.map function and forEach for an Array is the same, but which is not. Lets try to differentiate:
1. forEach
forEach can be used with any array to iterate through each and every value. It's just like using a traditional 'for loop' that starts with 1 and goes through the end element.
10
20
30
40
50
2. Array.map
The map function creates a new Array with the result of calling the given function or expression on every elements of the Array.
[ 20, 40, 60, 80, 100 ]
In the above example we are trying to iterate through every element of Array and multiply it by 2. The resultant applied on every element will be also an array.
Happy Coding! | dhandrohit@gmail.com
1. forEach
forEach can be used with any array to iterate through each and every value. It's just like using a traditional 'for loop' that starts with 1 and goes through the end element.
The above code will generate the following output.let array = [10,20,30,40,50]; array.forEach((number)=>{ console.log(number); })
10
20
30
40
50
2. Array.map
The map function creates a new Array with the result of calling the given function or expression on every elements of the Array.
var result = array.map((number)=>{
return (number * 2);
});
console.log(result);
The output of the code is:[ 20, 40, 60, 80, 100 ]
In the above example we are trying to iterate through every element of Array and multiply it by 2. The resultant applied on every element will be also an array.
Happy Coding! | dhandrohit@gmail.com
Comments