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.
.map() Methodmap() 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]
const arr = [3, 7, 9];
const result = arr.map((value, idx, array) => value + idx);
// result: [3, 8, 11]
map()filter() and reduce() for advanced data manipulationMap 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
for (const [key, value] of map) {
console.log(key, value);
}
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 |
map(), and use Map to store and retrieve information about unique objects.