The Map Object

In ES6, JavaScript added a new Map class. The Map class is very similar to the standard object class, with a few differences. Today, we’re going over when to use and why to use them.

Why Map

Map, unlike the object class, does not have extra keys that have to be enumerated. This saves time when iterating over values in the map. The second thing is that a map can have a key of any type where an object’s key must be a string. Lastly, a map has built-in functions for getting values.

The key functions of a map are set, get, has, and delete. “set” adds the key-value pair to the map. “get” retrieves the value of the key. “has” checks if the key exists. Lastly, “delete” removes the key-value pair from the map without error. Each function provides a lot of value to the map class, which is better than spending time coercing an object to do the same job; this makes maps very useful.

These three things make the map extremely useful in situations where key-value pairs need to be stored. The built-in functions add flexibility that a basic object can’t provide. Here’s an example of using a map vs using an object.

// Map Example
const a = new Map();
const b = {};
//Adding key-value pairs
console.log("Set Key");
//Map
a.set('test', 3);
console.log(a.entries()); //[ 'test', 3 ]
//Object
b['test'] = 3;
console.log(b); //{ test: 3 }
//Get key
console.log("\nGet Key");
//Map
const c = a.get('test');
console.log("Map:", c);//Map: 3
//Object
const d = b['test'];
console.log("Object:", d); //Object: 3
//Has key
console.log("\nHas Test");
//Map
console.log("Map:", a.has('test')); //true
//Object
console.log("Object:", b['test'] !== undefined); //true (But could be set to null or undefined by developer)
//Remove key
console.log("\nDelete Key");
//Map
console.log("Map:", a.delete('test')); //true if there is a key to remove
console.log("Map:", a.get('test')); //Map: undefined
//Object
delete b['test'];
console.log("Object:",b['test']); //Object: undefined
view raw map-example.js hosted with ❤ by GitHub

So, that’s why to use a map, so what about when?

When To Use Map

A map should be used in select areas of your code. Given the “why”, they should be used when you need to store key-value pairs while the program is running. This is because maps can have keys that can’t be serialized properly in JSON. Furthermore, they would have to be coerced before being serialized. Although it’s not hard, if you only use strings as keys; using more complex keys will be trouble. So, use a map when you need to store key-value pairs that won’t be serialized. With that said, the map object provides a ton of value.

Conclusion

Maps are a great addition to the JavaScript language and have many uses. Although they shouldn’t be serialized, they come with built-in functions that make getting and looking up key-value pairs simple. The next time you think of using an object for storage, consider a map. Happy coding!

Sources

Map

%d bloggers like this: