Javascript Map

Vincentservio
2 min readMay 25, 2021

During a recent coding interview,I was given two arguments, one was a string and the other was an integer. I was asked to return the character/characters that appeared the number of times that corresponds with the integer. While that seemed easy to do, I was stumped with how to approach this because i couldn't remember how to place key/value pairs into an array. After acknowledging and telling my interviewer that i did not seem to remember how to accomplish this, she gave me permission to do a quick google. Through my search, while looking through the javascript docs, i stumbled across Map().

let myMap = new Map()

Map

The Map object is responsible for keeping track of or holding on to the key/value pairs and remembering the order it was inserted. objects and primitive values can be stored as either a key or a value. It is important to know that the map will return an array which can later be iterated through using for…of loop. Looping through array will return the [key,value] for each iteration.

Storing Data

Javascript built in some functions to help us manipulate, enter, or retrieve information from our array. Using the proper function can make this easy to use and you can use the list below as a cheat sheet.

let contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1

Above is an example of our get and set methods and how they work.

Set takes in two arguments, the first argument is a key and the second argument is the value. this functions sets the value for the key in the map object.

Get takes in one argument, the key. This returns the value corresponding to the key, or undefined if key isnt found.

Has is similar to Get however Has only returns true or false based on the whether the key is present in the array or not. Has takes in one argument as well, being the key.

Delete takes in a key as an argument, And returns true if the key existed and has been removed but will return false if key does not exist

Clear will remove all key-value pairs from the Map object.

--

--