Interview question
What is the difference between map(), filter(), and forEach()? map(), filter(), और forEach() में क्या अंतर है?
Answer
| Method | Returns | Purpose | Mutates original? |
|---|---|---|---|
| map() | New array, same length | Transform each element | No |
| filter() | New array, possibly shorter | Keep elements matching a condition | No |
| forEach() | undefined | Run side effects per element (logging, DOM updates) | No (but callback can mutate) |
const numbers = [1, 2, 3, 4, 5];
// map - transforms every element, same array length
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - keeps elements passing a test, length can shrink
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// forEach - just iterates, no new array is created
const result = numbers.forEach(n => console.log(n * 2));
console.log(result); // undefined - forEach always returns undefined
// Common mistake: using forEach when you need a new array
const wrong = numbers.forEach(n => n * 2); // WRONG - returns undefined, not the doubled array
console.log(wrong); // undefined
// Correct: use map instead
const correct = numbers.map(n => n * 2);
console.log(correct); // [2, 4, 6, 8, 10]
// Chaining map and filter
const result2 = numbers
.filter(n => n % 2 === 0)
.map(n => n * 10);
console.log(result2); // [20, 40]| Method | Return | उद्देश्य | Original बदलता है? |
|---|---|---|---|
| map() | नया array, same length | हर element transform करना | नहीं |
| filter() | नया array, छोटा हो सकता है | Condition match करने वाले elements रखना | नहीं |
| forEach() | undefined | Side effects चलाना | नहीं |
const numbers = [1, 2, 3, 4, 5];
// map - हर element transform, same length
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - test pass करने वाले elements
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// forEach - सिर्फ iterate करता है, नया array नहीं बनता
const result = numbers.forEach(n => console.log(n * 2));
console.log(result); // undefined
// गलती: नया array चाहिए तो forEach use करना
const wrong = numbers.forEach(n => n * 2); // गलत - undefined return
console.log(wrong); // undefined
// सही: map use करना
const correct = numbers.map(n => n * 2);
console.log(correct); // [2, 4, 6, 8, 10]
// map और filter chain करना
const result2 = numbers
.filter(n => n % 2 === 0)
.map(n => n * 10);
console.log(result2); // [20, 40]Was this answer clear?