Execute function for Each Element
- forEach()
- helps to visit each element in an array one by one.
- allows to perform a specific action on every element without changing original
array.
const fruits = ["apple", "banana", "mango", "orange"];
const displayFruit = fruit => {
[Link](`${fruit} is a fruit.`);
};
[Link](fruit => displayFruit(fruit));
the function we pass as an argument to forEach() can receive three helpful
parameters:
element: This is the current element of the array that we're visiting.
index: This is the index position of the current element in the array.
array: This is the entire array itself.
const fruits = ["apple", "banana", "mango", "orange"];
// In this case, the element is a single fruit
[Link]((fruit, index, array) => {
const result = `${fruit} is a fruit. It is at index ${index} in the array: $
{array}.`;
[Link](result)
});
const names = ["Adam", "Eve", "Oliver", "Sam"];
[Link](name=>{
[Link](`${name}`)
});
output=
Adam
Eve
Oliver
Sam
const products = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Phone", price: 499 },
{ id: 3, name: "Tablet", price: 299 }
];
// Write code below
let totalPrice=0;
[Link]((product, index, array)=>{
[Link](`Product: ${[Link]}, Price: $${[Link]}`);
totalPrice+=[Link]
});
[Link](`Total Price: $${totalPrice}`)
output:
Product: Laptop, Price: $999
Product: Phone, Price: $499
Product: Tablet, Price: $299
Total Price: $1797
- Map a function and get a new array
- map method is used to change the values in an array without changing the original
array and create a new array with modified elements easily.
const evenNumbers=[2,4,6];
const createOddNumberArray=(number)=>{
return number+1
}
const oddNumbers=[Link](number=>createOddNumberArray(number));
[Link](oddNumbers)
- we defined a function called createOddNumber(). This function takes a number and
returns that number incremented by 1.
- we use the map() method to call this function on each element of the evenNumbers
array and create a new array oddNumbers with the results.
//Improved version
const evenNumbers = [2, 4, 6];
const oddNumbers = [Link]((number) => number + 1);
[Link](oddNumbers);
NOTE:
Difference between forEach and Map
- map method returns an array while forEach doesnot.
- forEach() method is used to loop through array elements, it runs the same
function on each element. doesnot change in given array and returns undefined.