Map in Javascript
The map() method is one of the most commonly used array methods in JavaScript. It creates a new array by calling a function on every element of the original array.
Key Concepts
- Returns a new array (doesn't modify original)
- Always returns array of same length
- Each element is transformed by callback function
- Perfect for transforming data
Basic Map Usage
Code
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8, 10] console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)
Map with Objects
Extract specific properties Transform objects { displayName: "Tata -> Nexon", year: "2017" }, { displayName: "Hyundai -> Verna", year: "2008" }, { displayName: "Mahindra -> Bolero", year: "2012" }.
Code
const cars = [ { id: 1, name: "Nexon", brand: "Tata", make: "2017" }, { id: 2, name: "Verna", brand: "Hyundai", make: "2008" }, { id: 3, name: "Bolero", brand: "Mahindra", make: "2012" } ]; const carNames = cars.map(car => car.name); console.log(carNames); // ["Nexon", "Verna", "Bolero"] const carInfo = cars.map(car => ({ displayName: `${car.brand} -> ${car.name}`, year: car.make })); console.log(carInfo);
Map with Index
{ id: 1, name: "apple", position: 0 }, { id: 2, name: "banana", position: 1 }, { id: 3, name: "orange", position: 2 }.
Code
const fruits = ["apple", "banana", "orange"]; const indexedFruits = fruits.map((fruit, index) => ({ id: index + 1, name: fruit, position: index })); console.log(indexedFruits);
Map vs forEach
forEach - executes function but returns undefined map - returns new array.
Code
const result1 = cars.forEach(car => console.log(`${car.brand} -> ${car.name}`)); console.log(result1); // undefined const result2 = cars.map(car => `${car.brand} -> ${car.name}`); console.log(result2); // ["Tata -> Nexon", "Hyundai -> Verna", "Mahindra -> Bolero"]
Map with Conditional Logic
Code
const numbers2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenDoubled = numbers2.map(num => { if (num % 2 === 0) { return num * 2; } return num; // Return original if odd }); console.log(evenDoubled); // [1, 4, 3, 8, 5, 12, 7, 16, 9, 20]
Map with Nested Arrays
Code
const matrix = [[1, 2], [3, 4], [5, 6]]; const flattened = matrix.map(arr => arr.reduce((sum, num) => sum + num, 0)); console.log(flattened); // [3, 7, 11] (sum of each sub-array)
Map with thisArg (Context Binding)
With arrow function (lexical this) Arrow function uses 'this' from multiplier2.
Code
const multiplier = { factor: 2, multiply: function(numbers) { return numbers.map(function(num) { return num * this.factor; }, this); // 'this' refers to multiplier object } }; console.log(multiplier.multiply([1, 2, 3])); // [2, 4, 6] const multiplier2 = { factor: 3, multiply: function(numbers) { return numbers.map(num => num * this.factor); } }; console.log(multiplier2.multiply([1, 2, 3])); // [3, 6, 9]
Chaining Map Operations
Code
const prices = [10, 20, 30, 40, 50]; const finalPrices = prices .map(price => price * 1.1) // Add 10% tax .map(price => Math.round(price * 100) / 100) // Round to 2 decimals .map(price => `$${price.toFixed(2)}`); // Format as currency console.log(finalPrices); // ["$11.00", "$22.00", "$33.00", "$44.00", "$55.00"]
Map with Async Operations (Common Pattern)
Note: map returns array of promises Use Promise.
all to wait for all.
Code
const urls = ["/api/user/1", "/api/user/2", "/api/user/3"]; const promises = urls.map(url => fetch(url)); Promise.all(promises) .then(responses => responses.map(res => res.json())) .then(data => console.log(data));
Custom Map Implementation
Common Mistakes to Avoid ❌ Don't use map when you don't need the returned array Use forEach instead ❌ Don't use map for side effects only numbers.
map(num => console.
log(num)); // Wrong - use forEach ✅ Use map when you need to transform and return values ❌ Don't forget to return in map callback ✅ Always return a value.
Code
Array.prototype.myMap = function(callback, thisArg) { const result = []; for (let i = 0; i < this.length; i++) { if (i in this) { // Check if index exists result[i] = callback.call(thisArg, this[i], i, this); } } return result; }; const test = [1, 2, 3].myMap(x => x * 2); console.log(test); // [2, 4, 6] numbers.forEach(num => console.log(num)); // Correct const squared = numbers.map(num => num * num); // Correct const wrong = numbers.map(num => { num * 2; // Missing return statement }); console.log(wrong); // [undefined, undefined, undefined, undefined, undefined] const correct = numbers.map(num => num * 2); // Correct
Summary
Understanding map is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- map is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding map will help you in technical interviews