# Objects v/s Maps

## Introduction

In JavaScript, we usually use Objects to store key-value pairs, where the keys are strings or Symbols. Map, however, allow you to use any type of key, like numbers, objects, or functions, and they also remember the order in which the items are added.

In this article, we understand the differences between Objects and Maps, their performance, and practical use cases.

## What is a Map?

A **Map** is a special type of object in JavaScript that stores data in **key-value pairs**. Similar to an object, but with a few differences. In a Map, the **keys can be of any type**—not just strings. You can use numbers, objects, or even functions as keys.

Maps also remember the order in which the items were added. This means when you loop through a Map, you get the items in the same order you put them in.

## Creating A Map

To create a **Map** in JavaScript, you use the Map constructor. It allows **two main ways** to create a Map:

1. **Passing an Array to new Map()**
    
    * You can create a Map by passing an array of key-value pairs directly into the constructor.
        
    * Each key-value pair is represented as an inner array with two elements.
        
    * **Example:**
        
        ```javascript
        const user = new Map([
          ['name', 'Jay'],
          ['age', 18],
          ['city', 'Pune']
        ]);
        ```
        
2. **Creating a Map and Using** `.set()` **Method**
    
    * Alternatively, you can create an empty Map and add key-value pairs one by one using the `.set()` method.
        
    * **Example:**
        
        ```javascript
        const user = new Map();
        
        user.set('name', 'Jay');
        user.set('age', 18);
        user.set('city', 'Pune');
        ```
        
    * This approach gives you more flexibility, especially when the values are dynamic or coming from different sources.
        

## Methods & Properties

1. **new Map() -** Creates a new, empty Map.
    
2. **map.set(key, value) -** Adds a key-value pair to the Map. If the key already exists, it updates the value.
    
3. **map.get(key) -** Returns the value associated with the given key. If the key doesn’t exist, it returns undefined.
    
4. **map.has(key) -** Checks if a key exists in the Map. Returns true if found, otherwise false.
    
5. **map.delete(key) -** Removes the key-value pair for the given key from the Map.
    
6. **map.clear() -** Removes all key-value pairs from the Map.
    
7. **map.size -** Returns the total number of key-value pairs in the Map.
    

## How Does Map Compare Keys?

When checking if a key already exists, Map uses an internal algorithm called **SameValueZero** to compare keys.

This is **very similar** to the strict equality operator (===), but with **one difference**:

* In strict equality (===), NaN === NaN is **false**.
    
* In **SameValueZero**, NaN is considered **equal to NaN**.
    

This means you can **use NaN as a key** in a Map, and it will work as expected.

It’s also important to know that this comparison method is **built-in** and **cannot be changed or customized**.

## Chaining Methods

You can chain multiple methods together for cleaner code:

```javascript
let userMap = new Map()
  .set('name', 'Jay')
  .set('age', 20)
  .set('role', 'developer');
```

## Iteration Over Map

Map allows several ways to loop through its elements. Since it keeps items in the order they were added, you get predictable results when looping.

1. **map.keys() - R**eturns an **iterable of all keys** in the Map.
    
2. **map.values() -** Returns an **iterable of all values** in the Map.
    
3. **map.entries() -** Returns an **iterable of \[key, value\] pairs**. This is also the default when using for...of.
    

**Example:**

```javascript
let recipeMap = new Map([
  ['cucumber', 500],
  ['tomatoes', 300],
  ['coriander', 50]
]);

// iterate over keys (vegetables)
for (let vegetable of recipeMap.keys()) {
  alert(vegetable); // cucumber, tomatoes, coriander
}

// iterate over values (amounts)
for (let amount of recipeMap.values()) {
  alert(amount); // 500, 300, 50
}

// iterate over [key, value] entries
for (let entry of recipeMap) { // the same as of recipeMap.entries()
  alert(entry); // cucumber,500 (and so on)
}
```

**Using map.forEach()**

The Map object also includes a forEach() method that works just like it does for arrays:

```javascript
recipeMap.forEach( (value, key, map) => {
  alert(`${key}: ${value}`); // cucumber: 500 etc
});
```

## Map From Object

Normally, when we create a Map, we pass an array (or any iterable) of **key-value pairs** to initialize it. For example:

```javascript
let map = new Map([
  ['1',  'str1'],
  [1,    'num1'],
  [true, 'bool1']
]);
```

But, if you already have a **plain JavaScript object** and want to convert it into a Map, you can use the built-in method `Object.entries(obj)`.

The `Object.entries()` method returns an array of **\[key, value\]** pairs — exactly what Map needs for initialization.

**Example:**

```javascript
let obj = {
  name: "Jay",
  age: 20
};

let map = new Map(Object.entries(obj));
```

Now map behaves like a proper Map object, and you can use all the Map methods:

```javascript
map.get('name'); // Returns: "Jay"
map.has('age');  // Returns: true
```

## Object From Map

Just like we can create a Map from a plain object using `Object.entries(obj)`, we can also do the **reverse**—convert a Map back into a plain object.

This is useful when:

* You store data in a Map (for features like non-string keys or maintaining order),
    
* But need to pass that data to a function or third-party library that only accepts plain JavaScript objects.
    

The method `Object.fromEntries()` takes an **iterable of key-value pairs** and converts it into a plain object.

**Example:**

```javascript
let map = new Map();
map.set('banana', 1);
map.set('orange', 2);
map.set('watermelon', 4);

// Convert Map to Object
let obj = Object.fromEntries(map.entries());

console.log(obj.orange); // Output: 2
```

You can also write it more simply by skipping .entries():

```javascript
let obj = Object.fromEntries(map);
```

This works because Map is already iterable and returns key-value pairs by default when looped over.

## **Performance Benefits of Maps**

1. **Quick Access**: Maps allow you to quickly access values using keys, with lookup times being constant (O(1)). This makes them much faster than objects, especially when you’re working with large amounts of data.
    
2. **Flexible Keys**: Unlike objects, which only allow strings or symbols as keys, Maps can use any type of data as a key—such as numbers, objects, or even functions. This gives you more flexibility when working with complex data.
    
3. Maintains Insertion Order: Maps remember the order in which items are added. This ensures that when you loop through the Map, you’ll get the values in the exact order they were inserted, making iteration more predictable.
    
4. **No Prototype Conflicts**: Since Maps don’t have a prototype chain (unlike objects), there’s less chance of conflicts with inherited properties. This makes your code cleaner and avoids potential issues.
    
5. **Efficient Memory Use**: Maps are designed specifically for storing key-value pairs, which means they use memory more efficiently compared to objects, especially when handling large sets of data.
    

## **Practical Applications of Maps**

1. **Caching Data**: Use Maps to store frequently accessed data for quick retrieval, like API responses.
    
2. **Configuration Settings**: Store settings or options where each setting has a unique key.
    
3. **Tracking Relationships**: Use Maps to link items, such as users and their profiles or products and prices.
    
4. **Data Grouping**: Group items by a property, like categorizing books by genre.
    

## **Real-World Examples**

1. **User Profile Data**: Imagine a website where each user has a profile. You could use a **Map** to store user information, where the key is the user’s unique ID, and the value is their profile data (name, age, location, etc.).
    
2. **Inventory System**: In an online store, a **Map** could be used to link product IDs (keys) with product details (values), such as product name, description, and price. This allows for fast lookups when a user searches for a product.
    
3. **Student Grades**: A **Map** can be used in schools to store student names (keys) and their corresponding grades (values). For example, the key “Jay” maps to the grade “A”, and the key “Nikhil” maps to the grade “B”.
    

## Differences Between Objects and Maps

| **Feature** | **Map** | **Object** |
| --- | --- | --- |
| **Key Type** | Can use any type (e.g., strings, numbers, objects) | Only strings and symbols can be used as keys |
| **Key Order** | Maintains the insertion order of keys | Does not guarantee order (though modern engines do maintain it) |
| **Size** | .size property to get the number of entries | No built-in property to get the size of the object |
| **Iteration** | Iterates in insertion order using .keys(), .values(), .entries(), or forEach() | Does not have built-in methods for direct iteration (requires for...in or Object.keys()) |
| **Performance** | Faster for frequent additions/removals of key-value pairs | May perform worse with frequent modifications |
| **Default Prototype** | No default prototype chain, making it cleaner and less prone to inheritance issues | Inherits from Object.prototype, potentially causing conflicts |
| **Methods** | Built-in methods like .set(), .get(), .has(), .delete(), .clear() | Only has basic operations (assigning, deleting keys, etc.) |
| **Use Case** | Ideal for storing and working with dynamic or complex key-value pairs | Great for simple data structures and static properties |

## When To Use Maps

**Choose Maps when you need:**

* Key-value pairs where the keys can be of any type (e.g., strings, numbers, objects).
    
* Fast and efficient lookups for accessing data.
    
* Ordered entries that maintain the insertion order.
    

## Conclusion

Maps in JavaScript are great for storing collections of data as key-value pairs. They are useful when you need to associate one item with another, like linking a name to an age. By knowing when and how to use Maps, you can write cleaner and more efficient code.

### Want More…?

I write articles on [blog.devwithjay.com](https://blog.devwithjay.com) and also post development-related content on the following platforms:

* [**Twitter/X**](https://x.com/devwithjay)
    
* [**LinkedIn**](https://www.linkedin.com/in/devwithjay)
