JavaScript Roadmap — Day 35: Array Method — map() — Transform Every Element

 

 

Day 35 of 180 🕐 13 min read · ⚡ Intermediate Phase

Array Method — map() — Transform Every Element

The map() method creates a new array by applying a function to every element of the original array. It's one of the most powerful and commonly used array methods in JavaScript.

1. The Problem — Transforming Array Data

Imagine you have an array of numbers and you want to double each one. Or you have an array of user objects and you want to extract just their names. Or you have prices and you want to add tax. These are all transformations — taking each element and converting it into something else.

Without map(), you would use a for loop, create a new array, and manually push() each transformed element. With map(), it's a single line of code that clearly expresses your intent.

Manual Transformation vs map()
// ❌ Manual way — verbose
let numbers = [1, 2, 3, 4, 5];
let doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

// ✅ map() — clean and declarative
let doubled = numbers.map(n => n * 2);

💡 The insight: map() is a pure function — it creates a new array and leaves the original unchanged. This makes your code more predictable and easier to debug.

2. map() Syntax — Transforming with a Callback

The map() method creates a new array by calling a callback function on every element. The callback can accept up to three parameters:

  • currentValue — The current element being processed (required)
  • index — The index of the current element (optional)
  • array — The array being traversed (optional)

Unlike forEach(), map() returns a new array with the same number of elements. The original array is never modified.

map() Parameters
let numbers = [10, 20, 30];

// Only the element (most common)
let doubled = numbers.map(n => n * 2);
console.log(doubled);  // [20, 40, 60]

// Element + Index
let withIndex = numbers.map((n, i) => `Index ${i}: ${n}`);
console.log(withIndex);  // ["Index 0: 10", "Index 1: 20", "Index 2: 30"]

// Element + Index + Array
let withArray = numbers.map((n, i, arr) => `${n} is from [${arr}]`);
console.log(withArray);
📝 QUIZ Test Your Understanding

Question 1: What does map() return?

3. map() — Practical Examples

Here are common real-world use cases for map():

Real-World map() Examples
// Example 1: Double each number
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(n => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

// Example 2: Convert array of strings to uppercase
let fruits = ["apple", "banana", "cherry"];
let upperFruits = fruits.map(f => f.toUpperCase());
console.log(upperFruits);  // ["APPLE", "BANANA", "CHERRY"]

// Example 3: Extract property from array of objects
let users = [
  { name: "Ali", age: 25 },
  { name: "Sara", age: 30 },
  { name: "Waheed", age: 28 }
];
let names = users.map(user => user.name);
console.log(names);  // ["Ali", "Sara", "Waheed"]

// Example 4: Add tax to prices
let prices = [10, 20, 30];
let withTax = prices.map(price => price * 1.1);
console.log(withTax);  // [11, 22, 33]

// Example 5: Format numbers as currency
let amounts = [5, 10, 15];
let formatted = amounts.map(amount => `$${amount}.00`);
console.log(formatted);  // ["$5.00", "$10.00", "$15.00"]
📝 QUIZ Test Your Understanding

Question 2: What will be the output of [1, 2, 3].map(x => x * x)?

4. map() vs forEach() — Choosing the Right Tool

Both map() and forEach() iterate through arrays, but they serve different purposes:

Feature forEach() map()
ReturnsundefinedNew array
Use forSide effects (logging, DOM)Transforming data
Chaining❌ Cannot chain✅ Can chain (.filter().map())
Modifies original❌ No (but can modify external)❌ No (returns new array)
When to Use Each
// Use forEach() when you want to DO something with each element
let numbers = [1, 2, 3];
numbers.forEach(n => console.log(n));  // Just logging

// Use map() when you want to CREATE a new array from each element
let doubled = numbers.map(n => n * 2);  // Create new array

// map() can be chained
let result = numbers
  .map(n => n * 2)      // [2, 4, 6]
  .filter(n => n > 3)   // [4, 6]
  .reduce((a,b) => a + b);  // 10

console.log(result);  // 10

5. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE 1: Forgetting to return a value from map()
let numbers = [1, 2, 3];
let result = numbers.map(n => { n * 2 });  // Missing return!
console.log(result);  // [undefined, undefined, undefined]

// ✅ FIX: Use implicit return or explicit return
let result = numbers.map(n => n * 2);  // Implicit return
let result = numbers.map(n => { return n * 2 });  // Explicit return

// ❌ MISTAKE 2: Using map() when you don't need the return value
numbers.map(n => console.log(n));  // Creates unnecessary array

// ✅ FIX: Use forEach() for side effects
numbers.forEach(n => console.log(n));

// ❌ MISTAKE 3: Modifying the original array inside map()
let wrong = numbers.map((n, i, arr) => { arr[i] = n * 2; });  // Modifies original!

// ✅ FIX: map() is pure — don't modify the original
let correct = numbers.map(n => n * 2);

6. Best Practices — Professional Advice

🎯 Use map() for Transformations
Whenever you need to convert each element of an array into something else, map() is the right tool. It clearly communicates your intent.
📦 Chain map() with Other Array Methods
map() returns an array, so you can chain it with filter(), reduce(), sort(), and other array methods for powerful data transformations.
🔄 Keep Callbacks Pure
The callback inside map() should not modify anything outside its scope. It should take an input and return an output — nothing else.
📝 Use Arrow Functions for Conciseness
arr.map(x => x * 2) is much cleaner than arr.map(function(x) { return x * 2; }).

7. Try It Yourself — map() Playground

Experiment with map() below. See how it transforms each element and returns a new array.

✏️ map() Playground
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Each button creates a NEW transformed array!

8. Practice Tasks

Task 1 — Easy: Double the Numbers

Use map() to double each number in [5, 10, 15, 20, 25]. Store the result in a new variable and log it.

Task 2 — Medium: Extract Names from Objects

Given let users = [{name: "Ali"}, {name: "Sara"}, {name: "Waheed"}], use map() to extract just the names into a new array.

Task 3 — Hard: Add Tax and Format

Given [10, 20, 30, 40, 50], use map() to add 10% tax and format as currency (e.g., "$11.00"). Return the new array.

🔥 Challenge of the Day

Given an array of words ["hello", "world", "javascript"], use map() to create a new array with the first letter capitalized and the rest lowercase. Result should be ["Hello", "World", "Javascript"].

🔍 View Solution
let words = ["hello", "world", "javascript"];
let capitalized = words.map(word => word.charAt(0).toUpperCase() + word.slice(1));
console.log(capitalized); // ["Hello", "World", "Javascript"]
🎯 Key Takeaways Remember These
  • map() creates a new array by applying a function to each element — perfect for transformations
  • Returns a new array — original array is never modified
  • Callback receives currentValue, index, array — index is optional but useful
  • Always return a value — forgetting return gives undefined elements
  • map() vs forEach() — map() creates new array, forEach() is for side effects
  • Chainable — map() can be chained with filter(), reduce(), etc.
💼 Common Interview Questions Must Know

Q: What is the difference between map() and forEach()?

💡 A: map() returns a new array with transformed elements. forEach() returns undefined and is used for side effects.

Q: Does map() modify the original array?

💡 A: No, map() is pure — it returns a new array and leaves the original unchanged.

Q: What happens if you don't return a value from map() callback?

💡 A: The element becomes undefined in the new array. Always return a value from map().

📖 Download map() Cheat Sheet
Quick reference for array transformation with map()
Next Lesson
Day 36 — Array Method — filter()
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts