Maps in Javascript
ES6 introduced new data structures to take care of some problems that the language did not take care of.

Before its’ introduction, people generally used Objects to do the work.

However, Objects do not allow keys to be anything other than a string or integer. Keys in a Map, on the other hand, can be anything (object, array, string, or number). This allows for some interesting uses.

Features that objects do not have

Can store Arrays and Objects as keys.

Easily iterable in order of entry.

How to Create a Map

let m = new Map()

Built in Methods

.set()

Use the set method to add entries to a Map.

m.set('key', 'value')

m.set('hello', 'world)

.get()

Use the get method to get the value of a Key, Value pair in a map

m.get('hello')

// 'world'

.has()

Use the has method to check if a key is in the Map. Returns a boolean.

m.has('hi')

//false m.has('hello')

//true

.size()

Use the size method to check the size of a Map. Something that is not available with an object.

m.size()

//2

.delete()

Use the delete method to remove an entry from a Map.

m.delete('hello')

// will remove hello from the Map m.size()

// 1

Iterating Through a Map

One of the biggest improvements of a Map over an Object is the ability to iterate through the data structure in the order that the objects were added.

In doing this we also have access to the value using destructuring. We can use a “for, of” loop to get this done.

for(const [k, v] of m){ console.log(k, v) } // hello world

Conclusion

These features allow for a more expansive set of use cases and better ways to solve problems.

Thank you for reading! Please follow me on Twitter @thedrewprint and connect with me on LinkedIn. — Andrew Richards
['Andrew Richards']
['Javascript Tips', 'JavaScript', 'Javascript Development', 'Software Development', 'ES6']