Loading...

How to Use the Map function in JavaScript?

How to Use the Map function in JavaScript?

JavaScript is the most popular language for web developers around the world. Although it has a complex learning curve, developers turn to the same because of its flexibility and versatility, enabling developers to write code for thousands of use cases using one single tool – JavaScript. This article runs the readers through maps – one essential utility to have, which makes the developers look like magicians with exciting tricks up their sleeves. This article provides the need for map function, the intuition behind the same, and how they are implemented with a compelling example of tasty ice creams. Readers are encouraged to take a pen and a notebook to take notes and use the codedamn playground to execute the code snippets.

Introduction

Maps offer developers flexibility in arranging and structuring the data provided by the users. It enables the developers to have key-value pairs which can be used to access and set information in a well-defined manner that is readily available for use.

In all object-oriented programming languages, maps or dictionaries are available as basic data structures, either used independently or coupled with other data structures to implement complex algorithms and use cases.

In JavaScript, before ES6 was introduced, there was no concept of dictionaries, and hence maps were used as a substitute to the same. An interesting fact about maps is that the keys don’t necessarily have to be of the string data type. The keys can be of any data type JavaScript supports and can be objects and functions!

You must now wonder why we turn to maps when we have objects readily available in JavaScript. There are several use cases where maps perform way better than objects. In objects, we have a significant restriction on the keys – they can be integers, strings, or symbols, but in maps, there is no such restriction. In objects, if we want to add functionality to individual properties, that is not possible, but in maps, the same is available. This does not, however, mean that maps can completely replace objects. Objects should be used when the keys will be numbers or strings since objects offer simplicity and also should be used when working with JSON.

Maps in JavaScript

What are Maps?

const codedamnMap = new Map(); let keyNum = 2, keyStr = 'Name', keyObj = {}, keyFunc = function(){}; codedamnMap.set(keyNum,"Codedamn Map String"); codedamnMap.set(keyStr,"Codedamn Map String"); codedamnMap.set(keyObj,"Codedamn Map Object"); codedamnMap.set(keyFunc,"Codedamn Map Function"); codedamnMap.get(keyNum); codedamnMap.get(keyStr); codedamnMap.get(keyObj); codedamnMap.get(keyFunc);
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

Let us understand this piece of code. We have initiated a new instance of a map using the Map() function and named it to be codedamnMap. Further, we have defined four different types of keys – keyNum, which is a number, keyStr, which is a string, keyObj, which is a blank object and keyFunc, which is an empty function.

To set the values corresponding to the keys of the map, we need to use the set() function, which takes two arguments – first, the key, and the second, the value which will map to the key we wrote in the first argument.

To obtain the values corresponding to the map’s keys, we need to use the get() function.

Other Functions and Properties of Maps in JavaScript

A map also has other functions and properties which are helpful using development.

Size Property

This property tells the number of elements in the map or the size of the map.

console.log(codedamnMap.size);
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

This will return four as there are four key-value pairs in the codedamn map.

Clear Method

This method clears the map, or in other words, deletes all the elements that the map contains – both keys and values.

console.log(codedamnMap.size); codedamnMap.clear(); console.log(codedamnMap.size);
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

First, the output will be 4 since there are 4 key-value pairs in the map, but after the clear() method is called, the next time when we try to find out the size of the map, the output will be 0 since there does not exist any element in the map now.

Delete Method

As the name suggests, this method deletes a specific element from the map. It needs one argument – the key of the value that must be deleted.

console.log(codedamnMap.has(keyNum)); codedamnMap.delete(keyNum); console.log(codedamnMap.has(keyNum));
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

First, the output will be true since keyNum exists in the codedamnMap. Still, after the delete() method is called on the codedamnMap using the keyNum as the argument key, the next time the has() method is called on the codedamnMap for keyNum, it will return false because its existence has been removed from the map.

Has Method

This method is used to verify the existence of a specific key in the map. It needs one argument – the key that has to be checked for presence.

console.log(codedamnMap.has(keyStr)); console.log(codedamnMap.has(keyNotOk));
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

When the has() method is called on the codedamnMap using the keyStr key, and it will return true since keyStr exists in the map; however, when the same has() method is called on the codedamnMap using the keyNotOk key, it will return false since keyNotOk does not exist in the map.

Array Map() Method

When using arrays in any programming language, the primary goal is to iterate over elements in the array and then perform some operations on it. Iterating over the arrays requires developers to write code, and performing operations requires writing more. The map() method of arrays does both things in one go – one can iterate over the entire array and perform operations using callback functions.

let codedamnArray = [1,2,3,4,5]; let newCodedamnArray = codedamnArray.map(function(item){ return item+2; }); console.log(newCodedamnArray);
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

The codedamnArray contains five numbers. We now want that an array contains elements that are two more than each element of the codedamnArray. To do the same, we created a new array. We used the map() function on the codedamnArray where in the function, we passed the argument item that corresponded to the elements of the codedamnArray and returned item+2, which corresponds to the elements of newCodedamnArray.

The newCodedamnArray will contain 3,4,5,6,7 as elements now.

let iceCreams = [ { flavor:"chocolate", price:10, popularityScore:100 }, { flavor:"strawberry", price:15, popularityScore:200 }, { flavor:"vanilla", price:5, popularityScore:50 }, { flavor:"butterscotch", price:20, popularityScore:150 } ]
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

Given above is an array of objects. We will now apply the map function on this array of objects.

let iceCreamDetails = iceCreams.map(function(item){ return `${item.flavor} ice-cream has a popularity score of ${item.popularityScore} and is priced at INR ${item.price}`; }); console.log(iceCreamDetails);
Code language: JavaScript (javascript)

Run this piece of code in codedamn playground.

The above code generates a new array, iceCreamDetails which contains strings about the details of each ice cream. Upon execution, the code will return – ["Chocolate ice cream has a popularity score of 100 and is priced at INR 10", "Strawberry ice cream has a popularity score of 200 and is priced at INR 15", "Vanilla ice cream has a popularity score of 50 and is priced at INR 5", "Butterscotch ice-cream has a popularity score of 150 and is priced at INR 20"].

Summary

In this article, we saw the importance of maps as a programmer. Maps are convenient when we store information that needs to be accessed readily and doesn’t require the restriction of which types of keys we require. We also saw the different properties and methods associated with the in-built Map() provided by JavaScript and then also saw how the map() function can be used with arrays.

Readers are encouraged to run the code in codedamn’s in-built playground, which offers fast compilation and VSCode-like in-browser coding experience for web development and JavaScript.

Read more about learning paths at codedamn here.

Happy Learning!

Sharing is caring

Did you like what Pooja Gera wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far