Beginner JavaScript Interview QuestionsBeginnerComparison
JavaScript · Question 18
What is the difference between map() and forEach() in JavaScript?
Direct answer
map() creates and returns a new array from callback results, while forEach() iterates for side effects and returns undefined.
Use map() when each input element should produce a corresponding output element. Use forEach() when the goal is an action such as logging, updating an external value, or invoking another operation.
const doubled = [1,2,3].map(n => n * 2); produces [2,4,6]. By contrast, assigning the result of [1,2,3].forEach(...) gives undefined.