The methods we are about to cover are called Higher-Order Functions. This is a fancy term that simply means they are functions that take another function as an argument (this is the "callback" function you provide).
The Core Idea: Instead of manually writing a for loop every time, you tell the array what you want to do, and the array method handles the looping for you.
Let's use this sample array for our examples:
const products = [
{ id: 1, name: "Laptop", category: "Electronics", price: 1200, inStock: true },
{ id: 2, name: "Book", category: "Books", price: 30, inStock: true },
{ id: 3, name: "Coffee Maker", category: "Appliances", price: 150, inStock: false },
{ id: 4, name: "Headphones", category: "Electronics", price: 200, inStock: true }
];
.forEach() - The Simple LooperFirst Thought: "I want to walk along the conveyor belt and do something with each item, but I'm not creating a new line of items."
Core Purpose: To execute a function once for each element in the array. It's a modern alternative to a for loop.
Key Characteristics:
undefined).break out of it or continue to the next iteration.Syntax:array.forEach((element, index) => { /* ... your code ... */ });
element: The current item being processed in the array.index (Optional): The index of the current item.Detailed Example: Just logging the name of each product.
console.log("--- Our Products ---");
products.forEach(product => {
console.log(`- ${product.name}`);
});
Output:
--- Our Products ---
- Laptop
- Book
- Coffee Maker
- Headphones
When to Use: When you need to "do something" for each item but you don't need to create a new array from the results. Examples: logging, updating a UI, saving each item to a database.
.map() - The TransformerFirst Thought: "I have a list of raw materials. I want to put each one through a machine to create a new list of finished products."
Core Purpose: To create a new array by transforming every element from an original array.
Key Characteristics:
Syntax:const newArray = array.map((element, index) => { return /* new value */; });
The return value from your callback function becomes the element in the new array at that same position.
Detailed Example: Let's create a new array containing just the names of the products for display.
const productNames = products.map(product => {
return product.name;
});
console.log(productNames); // ["Laptop", "Book", "Coffee Maker", "Headphones"]
console.log(products); // The original `products` array is unchanged!