Sitemap

Map() in JavaScript

2 min readFeb 11, 2025

--

Press enter or click to view image in full size

Map() is built-in object in JavaScript that allows you to store key value pairs. It is a part of ES6 release.

It is more like a object with better performance and following features.

Key-value pairs: Map()provide flexibility to choose any datatype for key-value pair, unlike object which only supports string type of key.

const myMap=new Map()
myMap.set(1,'One')
myMap.set(true,'exist')
console.log(myMap)

//output { 1 => 'One', true => 'exist' }

Map Preserves Insertion Order: It preserve the order of element on their insertion, in other words you can say it maintain the order of values getting inserted.

Get Saurav sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

CRUD operation on map: There are multiple functions available for doing crud option as mention below
1.get()
2. set()
3. delete()
4.has()
and one property to calculate the size of Map()object

const myMap=new Map()
myMap.set(1,'One')
myMap.set(true,'exist')

console.log(myMap)

const mapValue=myMap.get(1)
console.log(mapValue)

myMap.delete(true)
console.log(myMap)

console.log(myMap.has(1))

console.log(myMap.size)

output(NodeJs)
Map(2) { 1 => 'One', true => 'exist' }
One
Map(1) { 1 => 'One' }
true
1

Best Use Cases:
1. Frequent Addition/Deletion of key-value pairs.
2. As a object alternative.
3. Where you need a specific type of key-value pairs.
4. You want to maintain the order as object shuffle the element or object don’t don’t have any order.

Note:
1. For iterating over the map, we can either use forEach or for…of.
2. Map() don’t have key by default
Map is implemented differently from regular objects:

  • It does not inherit keys from Object.prototype.
  • It stores keys explicitly without prototype chaining.

3. Mapis more secure than object.
4. Map()is a iterable but object is not directly iterable.
5.Map() no built-in support for serialization and parsing.

I hope this article help you understand Map()

Thanks and Regards
Saurav Kumar Sharma

--

--