✅ Logical Operators in JavaScript – Complete Guide with Real Examples
map(), filter() & reduce() in JavaScript - Simplified!JavaScript offers powerful array methods to work with data efficiently. Among them, the trio of map(), filter(), and reduce() are must-know tools for every developer.
This guide will break them down with simple examples that you can copy and run in your browser or code editor.
map() – Transform Every ElementThe map() method creates a new array by transforming each element of the original array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
map() when you want to apply a function to each item and return a new array.
filter() – Keep What You NeedThe filter() method returns a new array containing elements that match a condition.
const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // Output: [2, 4]
filter() when you want to keep only the elements that pass a test.
reduce() – Combine Everything into OneThe reduce() method reduces an array to a single value by accumulating the result.
const numbers = [1, 2, 3, 4];
const total = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(total); // Output: 10
reduce() when you want to compute a single result from all items, like a sum or a product.
Mastering these three methods (map, filter, and reduce) can help you write cleaner, more functional JavaScript code.
They are extremely useful in real-world development, especially when working with APIs or manipulating complex data structures.
๐ Blog by: Web Coding with Ankur
Comments
Post a Comment