Map
object provided by ES6
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
Constructor
Map()
creates new Map
objects.
Example 1:
Example 2:
Example 3:
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.
Map.prototype.has(key):
returns a boolean asserting whether a value has been associated to the key
in the Map
object or not.
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.
Map.prototype.clear():
removes all key-value pairs from the Map
object.
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.
Map.prototype.keys():
returns a new Iterator
object that contains the keys for each element in the Map
object in insertion order.
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.
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.
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), Object
s have been used as Map
s historically.
Please take a look at the important differences that make Map
preferable in certain cases:
Reference: https://developer.mozilla.org/
Enjoy! 😊