Because map returns a new array, which is wasted if you only want side effects. forEach returns undefined and signals that you are not transforming data. Using map for side effects is misleading and wastes memory.
Common Higher-Order Function Mistakes in JavaScript
Why should you use forEach instead of map for side effects in JavaScript?
The answer
More FAQs in Common Higher-Order Function Mistakes in JavaScript
Because without an initial value, reduce uses the first element as the accumulator. An empty array has no first element, so it throws TypeError: Reduce of empty array with no initial value. Always pass an initial value.
Because sort defaults to string comparison. It converts elements to strings and sorts lexicographically. '10' comes before '2' because '1' < '2'. Use a numeric comparator: sort((a, b) => a - b).
Because the arrow function has a block body (braces) with no return statement. Block bodies need an explicit return. Use an expression body (n => n * 2) or add return (n => { return n * 2; }).
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.