Maps in Javascript

Andrew Richards
The Startup
Published in
2 min readSep 3, 2020

--

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()

--

--