Back to articles
What is the purpose of the map() method in JavaScript?

What is the purpose of the map() method in JavaScript?

via Dev.to BeginnersShashi Bhushan Kumar

The purpose of the map() method is simple: It creates a new array by transforming every element of an existing array. It does NOT change the original array. It returns a brand new array. Very Simple Real-life Example 🍎 Imagine you have a basket of fruits: ["apple", "banana", "mango"] Now you want to convert all fruits into uppercase: ["APPLE", "BANANA", "MANGO"] Instead of changing the original basket, you create a new basket with updated fruits. That is exactly what map() does. Basic Example const numbers = [ 1 , 2 , 3 , 4 ]; const doubled = numbers . map ( num => num * 2 ); console . log ( doubled ); // [2, 4, 6, 8] Here: Original array → [1, 2, 3, 4] New array → [2, 4, 6, 8] The original array stays the same. When Should We Use map()? When we want to modify data When we want a new array When we want cleaner and shorter code Important Difference map() → returns a new array forEach() → does not return anything One-line Summary map() is used to transform each item in an array and retur

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
1 views

Related Articles