JavaScript Maps

A Map in JavaScript is a collection of key-value pairs where keys can be of any data type. Unlike objects, Maps maintain the order of their elements and provide better performance for frequent additions and removals of key-value pairs.

Map Methods:

  • set(key, value): Adds or updates an element with the specified key and value.
  • get(key): Returns the value associated with the specified key.
  • has(key): Returns true if a key exists in the Map.
  • delete(key): Removes the specified key-value pair from the Map.
  • clear(): Removes all key-value pairs from the Map.
  • keys(): Returns a new Iterator object containing the keys for each element in the Map.
  • values(): Returns a new Iterator object containing the values for each element in the Map.
  • entries(): Returns a new Iterator object containing an array of [key, value] for each element in the Map.

Example:

let myMap = new Map();

myMap.set('name', 'John');
myMap.set('age', 30);
myMap.set('city', 'New York');

console.log(myMap.get('name')); // 'John'
console.log(myMap.size); // 3

myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

myMap.delete('age');
console.log(myMap.has('age')); // false

myMap.clear();
console.log(myMap.size); // 0

Try It Now

Key Characteristics of Maps:

  • Key-value pairs: Each key is unique, and the Map holds a value associated with that key.
  • Ordered elements: Elements are iterated in the order of their insertion.
  • Keys of any type: Keys can be of any data type (e.g., objects, functions, primitive types).

Creating a Map:

You can create a Map using the Map constructor.

let myMap = new Map();

Try It Now

You can also initialize a Map with an array of key-value pairs.

let myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2']
]);

Try It Now

Adding Elements:

Use the set() method to add key-value pairs to the Map.

myMap.set('key3', 'value3');
myMap.set('key1', 'newValue1'); // Updates existing key

Try It Now

Accessing Elements:

Use the get() method to retrieve the value associated with a key.

console.log(myMap.get('key1')); // 'newValue1'
console.log(myMap.get('key3')); // 'value3'

Try It Now

Checking for Keys:

Use the has() method to check if a key exists in the Map.

console.log(myMap.has('key2')); // true
console.log(myMap.has('key4')); // false

Try It Now

Removing Elements:

  • Remove a specific key: Use the delete() method.
    myMap.delete('key2');
    console.log(myMap.has('key2')); // false
    

    Try It Now

  • Remove all elements: Use the clear() method.
    myMap.clear();
    console.log(myMap.size); // 0
    

    Try It Now

Map Properties:

  • size: Returns the number of key-value pairs in the Map.
    console.log(myMap.size); // Number of elements in the Map
    

    Try It Now

Iterating Over a Map:

You can iterate through a Map using various methods:

  • for...of loop:
    for (let [key, value] of myMap) {
      console.log(`${key}: ${value}`);
    }
    

    Try It Now

  • forEach method:
    myMap.forEach((value, key) => {
      console.log(`${key}: ${value}`);
    });
    

    Try It Now

Summary:

JavaScript Maps provide a more flexible and efficient way to work with key-value pairs compared to regular objects, especially when you need to handle keys of various types or require ordered data.