In JavaScript, both map and forEach
are used for iterating over arrays, but they have key differences in functionality and usage.
Key Differences Between map()
and forEach()
Feature |
|
|
---|---|---|
Return Value | Returns a new array with transformed elements | Returns undefined (does not return a new array) |
Mutation | Does not modify the original array | Works on existing array but does not return a new one |
Chaining | Supports method chaining (e.g., | Does not support chaining |
Use Case | When you need a transformed array as output | When you just need to iterate over items without modifying them |
Examples
📌 Using map()
→ Returns a new array
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] ✅ New array created
📌 Using forEach()
→ No new array returned
const numbers = [1, 2, 3, 4]; numbers.forEach(num => console.log(num * 2)); console.log(numbers); // [1, 2, 3, 4] ❌ No new array, just iteration
When to Use What?
✔ Use map()
when you need a new modified array.
✔ Use forEach()
when you just need to execute logic on each item without returning a new array🚀.
In JavaScript, both filter()
and find()
are used to search elements within an array, but they work differently based on the outcome.
1. filter()
Method:
- If no elements match, it returns an empty array (
[]
).
- Useful for extracting multiple matching values.
📌 Example of filter()
const numbers = [10, 20, 30, 40]; const greaterThan20 = numbers.filter(num => num > 20); console.log(greaterThan20); // [30, 40] ✅ Returns an array
2. find()
Method:
- If no match is found, it returns
undefined
.
- Useful for retrieving only one specific value.
📌 Example of find()
const numbers = [10, 20, 30, 40];
const firstGreaterThan20 = numbers.find(num => num > 20); console.log(firstGreaterThan20); // 30 ✅ Returns a single value
Key Differences Between filter()
and find()
Feature |
|
|
---|---|---|
Return Type | Array of matching elements | First matching element (or |
Multiple Matches | Returns all matches | Returns only the first match |
Usage | Extracting multiple items | Finding a specific item |
No comments:
Post a Comment