JavaScript: Map (Array .map & Map Object)

JavaScript has two major concepts called "Map": the Array.prototype.map() method and the Map object. Both are essential for modern JS development, but they serve different purposes.

1. Array .map() Method

map() is an array method that creates a new array by applying a function to each element of the original array. It does not mutate the original array.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8]
    
// Output:
[2, 4, 6, 8]
const arr = [3, 7, 9];
const result = arr.map((value, idx, array) => value + idx);
// result: [3, 8, 11]
    

Use Cases for Array map()

2. Map Object (ES6)

The Map object is a collection of key-value pairs, where keys can be any type (not just strings or symbols, unlike objects). Maps remember the original insertion order of the keys.

const map = new Map();
map.set('name', 'Alice');
map.set(123, true);
map.set({ x: 1 }, [10, 20]);

console.log(map.get('name')); // 'Alice'
console.log(map.get(123));    // true
    
// Output:
Alice
true
for (const [key, value] of map) {
  console.log(key, value);
}
    

When to Use Map vs Object

Feature Map Object
Key Types Any (object, function, etc) String or Symbol
Order Preserves insertion order Not guaranteed
Iteration Directly iterable Not directly iterable
Performance Faster for frequent additions/removals Good for static keys

Summary

Practice: Try converting an array of user objects into an array of names with map(), and use Map to store and retrieve information about unique objects.