Beginner JavaScript Interview QuestionsBeginnerComparison
JavaScript · Question 19
When should you use map(), filter(), and reduce() in JavaScript?
Direct answer
Use map to transform items, filter to keep selected items, and reduce to combine an array into an accumulated result.
map()transforms each element and returns a new array of the same length.filter()tests each element and returns a new array containing only elements whose callback result is truthy.reduce()carries an accumulator across the array and can produce a number, string, object, array, map, or any other final value.
For const nums = [1,2,3,4];, you might use nums.map(n => n * 2), nums.filter(n => n % 2 === 0), or nums.reduce((sum, n) => sum + n, 0) depending on the desired result.