Map object provided by ES6

sonia dumitru
4 min readFeb 17, 2020

The Map object holds key-value pairs and remembers the original insertion order of the keys, therefore when we iterate over the map object it returns the key, value pair in the same order as inserted. Any value (both objects and primitive values) may be used as either a key or a value.

Syntax

Syntax to create Map objects

Constructor

Map()creates new Map objects.

Example 1:

map1 object

Example 2:

map2 object

Example 3:

map3 object

Map instances

Properties

All Map instances inherit from Map.prototype.

Map.prototype.constructor:returns the function that created an instance's prototype. This is the Map function by default.

Map.prototype.size:returns the number of key/value pairs in the Map object.

Methods

Map.prototype.set(key, value):sets the value for the key in the Map object & returns the Map object.

.set () method

Map.prototype.has(key): returns a boolean asserting whether a value has been associated to the key in the Map object or not.

.has() method

Map.prototype.delete(key):returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.

.delete() method

Map.prototype.clear():removes all key-value pairs from the Map object.

.clear() method

Map.prototype.entries():returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.

.entries() method

Map.prototype.keys():returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

.keys() method

Map.prototype.values():returns a new Iterator object that contains the values for each element in the Map object in insertion order.

Map.prototype.forEach(callbackFn[, thisArg]):calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.

.forEach() method

Map.prototype[@@iterator]():returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.

.iterator() method

Object is similar to Map, both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Objects have been used as Maps historically.

Please take a look at the important differences that make Map preferable in certain cases:

Map vs. Object

Reference: https://developer.mozilla.org/

Enjoy! 😊

--

--