# Mastering JavaScript's Map

## Introduction

Objects have long been the go-to choice for storing key-value pairs in JavaScript. However, the `Map` data structure offers a more powerful and flexible alternative. Unlike objects, `Map` allows keys of any data type, maintains insertion order, and performs better in some cases.

In this guide, you'll learn everything about `Map` JavaScript, including how to use it effectively in real-world scenarios.

---

## What is a Map?

A `Map` is a built-in JavaScript data structure that holds key-value pairs, where keys can be **any type of value**, including objects, functions, and primitive types.

### Why Use Map Over Object?

| Feature | Map | Object |
| --- | --- | --- |
| Key Types | Any (objects, functions, etc.) | Strings or symbols only |
| Order | Maintains insertion order | No guaranteed order |
| Size Property | `.size` | Must use `Object.keys(obj).length` |
| Performance | Faster for frequent additions/removals | Slower when handling large key-value sets |

---

## Creating a Map

You can create a `Map` using the `new Map()` constructor:

```js
const myMap = new Map();
```

### Adding Key-Value Pairs

Use `.set(key, value)` to add entries:

```js
myMap.set('name', 'Alice');
myMap.set(42, 'The Answer');
myMap.set(true, 'Boolean Key');
```

### Accessing Values

Retrieve values using `.get(key)`, ensuring you use the exact key reference:

```js
console.log(myMap.get('name')); // Alice
console.log(myMap.get(42)); // The Answer
```

### Checking Key Existence

Use `.has(key)` to check if a key exists:

```js
console.log(myMap.has('name')); // true
console.log(myMap.has('age')); // false
```

### Removing a Key

Delete a key-value pair using `.delete(key)`:

```js
myMap.delete(42);
console.log(myMap.has(42)); // false
```

### Finding the Size

Use `.size` to get the number of elements:

```js
console.log(myMap.size); // 2
```

---

## Iterating Over a Map

You can loop through a `Map` using different methods:

### Using `forEach()`

```js
myMap.forEach((value, key) => {
    console.log(`${key} -> ${value}`);
});
```

### Using `for...of`

```js
for (let [key, value] of myMap) {
    console.log(`${key} -> ${value}`);
}
```

### Converting Map to Array

If you need an array representation:

```js
const entriesArray = Array.from(myMap);
console.log(entriesArray);
```

---

## Using Arrays or Objects as Keys

Unlike objects, `Map` allows arrays and objects as keys:

```js
const myMap = new Map();
const keyArray = [1, 2, 3];
myMap.set(keyArray, 'Array as Key');

console.log(myMap.get(keyArray)); // Array as Key ✅
```

**Important Note:** If you try to retrieve the value using a new array (`myMap.get([1, 2, 3])`), it won’t work because objects and arrays are **reference-based**, not value-based.

---

## Clearing a Map

Use `.clear()` to remove all key-value pairs:

```js
myMap.clear();
console.log(myMap.size); // 0
```

---

## Real-World Use Cases

### 1\. **Caching Computation Results**

```javascript
const myMap = new Map();

const getSumofArray = (...arr) => {
    if (myMap.has(arr)) return myMap.get(arr);
    
    let computeSum = arr.reduce((initialValue, accum) => initialValue + accum, 0);
    myMap.set(arr, computeSum); //we can store arr as the key
    return computeSum;
};

console.time("Function Execution Time");
console.log(getSumofArray(1, 2, 3, 4, 5));
console.timeEnd("Function Execution Time");

console.time("Function Execution Time");
console.log(getSumofArray(1, 3, 4, 5));
console.timeEnd("Function Execution Time");

console.time("Function Execution Time");
console.log(getSumofArray(1, 2, 3, 4, 5));
console.timeEnd("Function Execution Time");

/***
output
15
Function Execution Time: 74.399ms
13
Function Execution Time: 0.078ms
15
Function Execution Time: 0.087ms

=== Code Execution Successful ===
**/
```

Using `Map` to cache computed values can speed up repeated function calls:

---

## Conclusion

The `Map` data structure in JavaScript is a **powerful alternative to objects** for handling key-value pairs. It offers flexibility, better performance, and maintains insertion order. Whether you're working with **complex keys (objects/arrays), tracking data efficiently, or improving performance**, `Map` is a great choice.

**What’s your favorite use case for Map? Let me know in the comments!** 🚀
