Previous Next

JavaScript Map

JavaScript Maps is a JavaScript data structure that was added in ECMAScript 6 (ES6). They hold key-value pairs.

Example:

let map1 = new Map();
console.log(map1); // Map {}

JavaScript Map Methods

There are various methods available in JavaScript Map object.

Method Description
set() Adds or overwrites a key-value pair to the Map.
get() Returns the value for the given key.
delete() Deletes the element specified from a Map object.
has() Looks whether the Map holds a certain key.
forEach() Invokes a function for every key/value in a Map

set() Method

In order to add things to a Map, use the set() method:

Example:

let myMap = new Map();

myMap.set('name', 'John');
myMap.set('age', 22);

console.log(myMap.get('name'));

Output:

John

get() Method

The get() method retrieves a value of a key in a Map.

Example:

let myMap = new Map();

myMap.set(1, 'JavaScript');

console.log(myMap.get(1));

Output:

JavaScript
Previous Next