Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Array Methods
Interview question

What is the difference between map(), filter(), and forEach()? map(), filter(), और forEach() में क्या अंतर है?

Answer
MethodReturnsPurposeMutates original?
map()New array, same lengthTransform each elementNo
filter()New array, possibly shorterKeep elements matching a conditionNo
forEach()undefinedRun 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]
MethodReturnउद्देश्यOriginal बदलता है?
map()नया array, same lengthहर element transform करनानहीं
filter()नया array, छोटा हो सकता हैCondition match करने वाले elements रखनानहीं
forEach()undefinedSide 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?