Skip to main content

JavaScript Maps

JavaScript Maps are data structures that store key-value pairs, where each key is unique and maps to a corresponding value.

Maps in JavaScript were introduced in ECMAScript 6, and they provide a more flexible alternative to objects for mapping keys to values.

Essential Map Methods

MethodDescription
new Map()Creates a new Map
set()Sets the value for a key in a Map
get()Gets the value for a key in a Map
delete()Removes a Map element specified by the key
has()Returns true if a key exists in a Map
forEach()Calls a function for each key/value pair in a Map
entries()Returns an iterator with the [key, value] pairs in a Map
PropertyDescription
sizeReturns the number of elements in a Map

How to Create a Map

For create a new Map, you can use the new keyword and the Map() constructor:

let myMap = new Map();
  • You can add key-value pairs to the map using the set() method:
myMap.set("key1", "value1");
myMap.set("key2", "value2");
  • You can also chain the set() method to add multiple key-value pairs in a single line of code:
myMap.set("key1", "value1").set("key2", "value2");
  • To retrieve a value from the map, you can use the get() method and pass in the key:
console.log(myMap.get("key1")); // Output: "value1"
  • You can also check if a key exists in the map using the has() method:
console.log(myMap.has("key1")); // Output: true
  • To remove a key-value pair from the map, you can use the delete() method and pass in the key:
myMap.delete("key1");
console.log(myMap.has("key1")); // Output: false
  • You can also clear all key-value pairs from the map using the clear() method:
myMap.clear();
console.log(myMap.size); // Output: 0
  • Maps also have a size property that returns the number of key-value pairs in the map:
console.log(myMap.size); // Output: 1

Overall, Maps in JavaScript are a powerful tool for working with key-value data and provide a more flexible alternative to objects.