How to Use the Map Syntax in JavaScript?

Estimated read time 2 min read

In JavaScript, you can create a Map object using the Map constructor and passing an iterable object as an argument, or using a shorthand map syntax:

// Using the Map constructor
let map = new Map([["A", 1], ["B", 2], ["C", 3]]);
console.log(map.get("A")); // 1

// Using the shorthand map syntax
let map = new Map([["A", 1], ["B", 2], ["C", 3]]);
console.log(map.get("A")); // 1

In the example above, we created two maps using the Map constructor and the shorthand map syntax. In both cases, we passed an array of arrays as an argument, where each inner array represents a key-value pair in the map.

You can also add, update, and retrieve elements from the map using the set, get, and has methods:

let map = new Map();

// Adding elements to the map
map.set("A", 1);
map.set("B", 2);
map.set("C", 3);

// Updating elements in the map
map.set("A", 10);

// Retrieving elements from the map
console.log(map.get("A")); // 10
console.log(map.has("B")); // true

In the example above, we first created an empty map using the Map constructor. Then, we used the set method to add elements to the map, and updated the value of the “A” key using the set method again. Finally, we used the get method to retrieve the value of the “A” key and the has method to check if the “B” key is present in the map.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply