Skip to main content

Command Palette

Search for a command to run...

Difference between Map and object

Updated
3 min read
A

I am working as freelancer. I am a experienced full stack web developer. My lovely stack is MERN but I am open for new tech. I love to work with teammates for achieve goals. I love researches to find specific new things.

What is Map()?

The map creates a new Map object. It is an object that holds key-value pairs in order of key insertion. Key or value uses any type of data(primitive or object reference).

A key is unique in the map's collection. It has no default keys.

Map methods

Map.size

It returns the number of key-value pairs in the Map object.

Map.clear()

It clears all the key-value pairs from the object.

Map.delete()

It returns true if an element is existed in the object and is removed. It returns false if the given element is not present in the object.

Map.get()

It returns with key-value pair of the given key. If the given key-value pair does not exist, it returns undefined.

Map.has()

It returns a boolean value true if the given key is present in the object. If the given key does not exist, gives false.

Map.set()

It sets the given key-value pair in the object and returns the Map object.

Map.keys()

It returns an iteration object that holds the key of the Map object.

Map.values()

It returns an iteration object with the values of the Map object.

Map.entries()

It returns an iteration object with an array of two elements (key, value) for every pair of Map objects.

Map.forEach()

It calls callbackFunction once for each key-value pair present in the Map object. It uses this value for each pair if thisarg parameter is passed.

Examples

Output

Maps vs Object

The Map is similar to Object. But a Map has also some attributes, which are different from objects.

 

Map

Object

Accidental Keys

  This has no default keys only external keys exist.

It has some default keys for that collision may be possible with your own keys.

Security

A Map is safe with user-defined keys and values.

Setting user key value may allow attackers to override objects prototype.

Key types

Map’s key can be any type of value(including function, object or primitive value).

Its key must be a string or symbol.

Key Order

Map’s key order becomes in simple, and straightforward way. Iteration takes place in the order of insertion of keys.

There is not a single way for iteration of all keys in a single way.

Size

The number of items in the map can be easily retrieved from the size property.

The number of items that can be retrieved from the length of the array method is less efficient.

Iteration

It is iterable so it can be directly iterated.

It has no iterable protocol so it cannot be directly iterable.

Performance

It has better performance in frequently adding and frequently removing.

Not optimized for frequently adding and removing.