JavaScript Maps

Understanding Maps

The JavaScript Map object is a collection of key-value pairs where each key is unique and mapped to a value. Unlike objects, keys in a Map can be of any type, even functions, objects, or any primitive. Maps remember the original insertion order of the keys, making them particularly useful when the order of elements is important.

Here's how you can work with Maps in JavaScript:

Creating a Map

const myMap = new Map();
    myMap.set('key1', 'value1');
    myMap.set('key2', 'value2');

Accessing Values

To access values in a Map, use the get method:

console.log(myMap.get('key1')); // Outputs: 'value1'

Checking for a Key

Check if a key exists in a Map with the has method:

console.log(myMap.has('key2')); // Outputs: true

Iterating Over a Map

You can iterate over the keys and values in a Map using a for...of loop:

for (let [key, value] of myMap) {
        console.log(key + ': ' + value);
    }

Map Size and Deletion

To find out the number of key-value pairs in a Map, use the size property. To delete a key from a Map, use the delete method:

console.log(myMap.size); // Outputs: 2
    myMap.delete('key1');
    console.log(myMap.size); // Outputs: 1

Maps are highly beneficial for scenarios where key integrity is important, and you need to maintain an orderly collection that does not coerce the keys to strings, as standard JavaScript objects do.

Try it Yourself

Test Your Knowledge: JavaScript Maps

Which method is used to get a value from a Map using a key?