JavaScript Array Methods: map(), forEach(), filter(), reduce() Explained

Day 14/50 – JavaScript Interview Question? Question: What is the difference between map(), forEach(), filter(), and reduce()? Simple Answer: forEach() executes a function for each element (returns undefined). map() transforms each element and returns a new array. filter() returns a new array with elements that pass a test. reduce() accumulates values into a single result. 🧠 Why it matters in real projects: These are essential for functional programming and data transformation. Using the right method makes code more readable and maintainable. React heavily relies on map() for rendering lists, and reduce() is powerful for complex data aggregations. 💡 One common mistake: Using forEach() when you need a return value, or using map() without using the returned array (side effects only). Also, forgetting that these methods don't mutate the original array. 📌 Bonus: const numbers = [1, 2, 3, 4, 5]; // forEach - just iterate (returns undefined) numbers.forEach(n => console.log(n * 2)); // map - transform each element const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10] // filter - keep elements that pass test const evens = numbers.filter(n => n % 2 === 0); // [2, 4] // reduce - accumulate to single value const sum = numbers.reduce((acc, n) => acc + n, 0); // 15 // Chaining for complex operations const result = numbers .filter(n => n > 2) .map(n => n * 2) .reduce((sum, n) => sum + n, 0); // 24 #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories