Maps in ES6

ES6

A map object in ES6 is just a simple key-value map. Javascript objects in maps are very similar to each other. But maps offers a few benefits for us which we can’t get from objects. E.g. in an object keys have to be a string where is in a map it can be anything from a function to all kinds of primitives. Maps have methods what allow to easily a size of map, clear keys and values and etc.

let myMap = new Map();

map.set("Competa", "Hello");
console.log(map.get("Competa"));  // "Hello"

In this example key-value pair is stored into myMap. The set method is used to create a key as ‘Competa’ with associated value ‘Hello’. The get method is used to retrieve the value of ket ‘Competa’. If the given key doesn’t exist undefined will be returned by get method.

let myMap = new Map([['Competa', 'Hello']]);

console.log(myMap.get('Competa')); // 'Hello'

The second way to initialize a map is by passing an array to the Map constructor. Each item of this array should be an array where the first element is the key and the second is the value.

console.log(myMap.size()) // 1

The size method returns an amount of key-value pairs in the map.

console.log(myMap.has('Competa')); // true

The has method returns true if the given key is presented in the map and false if it is not.

The delete method removes key-value pair by the given key.
The clear method delete all key-value pair from a map.

Share your thoughts

Leave a Reply