How to use a Map in JavaScript

Using a Map in JavaScript provides a robust key-value data structure that offers advantages over regular objects, including better performance and support for any data type as keys. As the creator of CoreUI with 25 years of JavaScript experience since 2000, I’ve implemented Maps extensively in enterprise applications for caching, data indexing, and complex state management scenarios. The most effective approach involves creating Map instances and using their built-in methods for adding, retrieving, and managing key-value pairs. This method provides optimal performance with iteration order preservation and type-safe key handling for modern JavaScript applications.

Create a Map instance and use its methods for efficient key-value storage and retrieval operations.

const userMap = new Map()

// Adding key-value pairs
userMap.set('john', { name: 'John Doe', age: 30 })
userMap.set(123, 'User ID 123')
userMap.set(true, 'Boolean key')

// Getting values
const user = userMap.get('john')
console.log(user) // { name: 'John Doe', age: 30 }

// Checking if key exists
console.log(userMap.has('john')) // true
console.log(userMap.has('jane')) // false

// Getting map size
console.log(userMap.size) // 3

// Iterating over map
for (const [key, value] of userMap) {
    console.log(`${key}: ${value}`)
}

// Deleting entries
userMap.delete('john')
console.log(userMap.size) // 2

This code demonstrates Map creation and essential operations including setting key-value pairs with set(), retrieving values with get(), checking key existence with has(), and iterating through entries. Maps maintain insertion order and allow any data type as keys, unlike objects which convert keys to strings. The Map provides methods for size checking, deletion, and efficient iteration, making it ideal for scenarios requiring frequent lookups and dynamic key management.

Best Practice Note:

This is the Map usage pattern we implement in CoreUI caching systems for optimal performance and memory management. Use Map over objects when you need frequent additions and deletions, non-string keys, or when iteration order matters.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What are the three dots `...` in JavaScript do?
What are the three dots `...` in JavaScript do?

How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to Detect a Click Outside of a React Component
How to Detect a Click Outside of a React Component

Answers by CoreUI Core Team