How to Use map(), filter(), and reduce() in JavaScript

JavaScript Array Methods Explained Simply: map(), filter(), reduce(): * JavaScript provides powerful methods to handle arrays easily. * The three most commonly used methods are map(), filter(), and reduce(). Let’s understand each one clearly with simple examples: 1. map() – Transform each element Meaning: *The map() method is used when you want to change or modify every element in an array. * It creates a new array without changing the original one. Example: const numbers = [1, 2, 3, 4]; const double = numbers.map(num => num * 2); console.log(double); Output: [2, 4, 6, 8] Explanation: * Each number is multiplied by 2. The original array remains [1, 2, 3, 4]. 2. filter() – Select specific elements Meaning: * The filter() method checks every element and keeps only those that meet a condition. * It returns a new array of filtered items. Example: const ages = [12, 17, 20, 25, 15]; const adults = ages.filter(age => age >= 18); console.log(adults); Output: [20, 25] Explanation: * Only ages that are greater than or equal to 18 are included in the new array. 3. reduce() – Combine all elements into one value Meaning: * The reduce() method takes all the elements in an array and reduces them to a single value, such as a total, average, or product. Example: const marks = [50, 70, 80]; const total = marks.reduce((acc, val) => acc + val, 0); console.log(total); Output: 200 Explanation: * acc (accumulator) keeps track of the total. * val is the current value being added. * Starts from 0 and adds each number → 0 + 50 + 70 + 80 = 200. KGiSL MicroCollege #JavaScript #WebDevelopment #Coding #Programming #FrontendDevelopment #LearnToCode #Developers #WebDevCommunity #SoftwareEngineering #CodeNewbie #JavaScriptTips #JSDeveloper #WebDesign #FrontendDeveloper #CodeLearning #TechCommunity #ProgrammersLife #SoftwareDevelopment #WebTech #FullStackDevelopment #CodingCommunity #TechLearners #JavaScriptLearning #JSCode #WebAppDevelopment #ModernJS #TechEducation #DeveloperJourney #CodeWithMe

  • No alternative text description for this image

.some? .every? .indexOf? Btw .reduce can do all the other methods jobs if needed

To view or add a comment, sign in

Explore content categories