.forEach()
What is it?
This method is the most similar to the forloop. Example -
// forloop
const numbers = [2,6,8,10,12];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// forEach
const numbers = [2,6,8,10,12];
numbers.forEach(number => {
console.log(number);
});
forEach() is simply executed "for each" element of the array.
.map()
What is it?
map is almost similar to the forEach method. This method loops through each element.
// map
const numbers = [2,6,8,10,12];
numbers.map(number =>console.log(number))
// map
const numbers = [2,6,8,10,12];
numbers.map(number =>console.log(number * 2))
map vs. forEach:
forEach:
It calls a function for each element of an array but doesn't return anything. That means no result fount means undefined
const numbers = [2,6,8,10,12];
let result = numbers.forEach((number) =>{
return number*10
})
console.log(result); //undefined
map:
This method returns a new array by applying the callback function on each element of an array.
// map
const numbers = [2,6,8,10,12];
let result = numbers.map((number) =>{
return number*10
})
console.log(result); //[20,60,80,100,120]
Top comments (0)