This post will discuss how to initialize a map in JavaScript.

There are several ways to initialize a map in JavaScript, which is a collection of key-value pairs that can store any type of data. A map remembers the original insertion order of the keys and has some useful functions and properties. Here are some common functions to initialize a map:

1. Create a Map from an array

One way to initialize a map is to use the Map() constructor and pass an iterable object that contains key-value pairs as an argument. For example, we can pass an array of arrays, where each subarray has two elements: the first one is the key and the second one is the value.

Download  Run Code

 
The array can also be an array of objects, where each object has a key and a value property. For example:

Download  Run Code

2. Using Map.set() function

Another way to initialize a map is to create an empty map using the Map() constructor without any arguments, and then use the set() function to add key-value pairs to the map. The set() function takes a key and a value as parameters and returns the map object, so we can chain multiple calls to the function. This is a way to add key-value pairs to an existing map or an empty map.

Download  Run Code

3. Using Object.entries() function

Another way to initialize a map is to use the Object.entries() function to convert an object literal into an array of key-value pairs, and then pass it to the Map() constructor to create a map with the same keys and values as the object.

Download  Run Code

4. Create a Map from a Set

We can also create a new map from an iterable object, such as a set, with the spread operator (…) and the map() function, using the collection elements as Map’s keys and the desired value as Map’s value:

Download  Run Code

5. Create copy of an existing Map

If we need to create a copy of an existing map, we can pass the another map as an argument for the Map() constructor. For example:

Download  Run Code

That’s all about initializing a map in JavaScript.