Home/Blog/Programming/What is a JavaScript map? Get started in 5 minutes
What is JavaScript map?
Home/Blog/Programming/What is a JavaScript map? Get started in 5 minutes

What is a JavaScript map? Get started in 5 minutes

5 min read
May 19, 2025
content
What is JavaScript Map?
JavaScript Map syntax
JavaScript Map methods and use cases
Initialize a Map with an iterable object
Return a value mapped to a specific key
Return a boolean value showing whether a specified key exists
Return the number of entries in the Map
Return a new iterator object that includes the value of each element
Remove specified elements from the Map object
Remove all elements in the map object
Demo of Map methods and use cases
Other useful Map methods
Advanced Map concepts
Why use a Map instead of an object?
Best practices for using Map
Wrapping up and next steps
Continue reading about JavaScript

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • ES6 introduced the Map collection, enabling key-value pairs of any type with guaranteed key insertion order.

  • Map can efficiently store and retrieve dynamic or complex key-value pairs.

  • Map is ideal for predictable key-value operations and dynamic or non-string keys.

  • Common Map methods include set(key, value), get(key), has(key), delete(key), clear(), and size.

  • Advanced JavaScript concepts like metaprogramming, prototypal inheritance, and constructors complement Map usage.

JavaScript once had limited capabilities for working with collections. Unlike other languages that provided sets, associative maps, lists, and dictionaries, JavaScript developers had to rely on arrays for these functionalities. JavaScript developers found creative workarounds to map keys to values, but their method was limited.

In the ES6 release, JavaScript introduced a new built-in class for maps that makes it easier to work with collections. This quick tutorial will discuss JavaScript Map with code examples, methods, and use cases, along with a glimpse into advanced concepts.

Introduction to JavaScript: First Steps

Cover
Introduction to JavaScript: First Steps

This is an introduction to JavaScript for the complete beginner. It'll provide the fundamentals of the language. Topics include variables, operators, functions, arrays, objects, and loops. After this course, you should be ready to further your learning through advanced courses or other resources. There is NO installation required for this course. Code can be viewed and run directly from the lessons. This course has been created by Arnav Aggarwal, a full-stack engineer. Arnav has attended a coding boot camp and has taught at another one. He has extensive experience understanding how people learn to code. In under a month, Arnav's published articles on JavaScript concepts have received over 50,000 views and have been featured on Medium.com and code mentor.io due to their value. After this course, check out the next one in the series. Step Up Your JS: A Comprehensive Guide to Intermediate JavaScript https://goo.gl/GjM8Mu

8hrs
Beginner
13 Challenges
11 Quizzes

What is JavaScript Map?#

Before ES6, JavaScript developers used objects to map keys to values, but this approach had several limitations:

  • Object keys could only be strings or symbols, limiting flexibility.

  • Iteration was unreliable since object properties were unordered.

  • Objects did not provide built-in methods for key-value manipulation.

The ES6 Map collection solves these issues by:

  • Allowing any data type as a key (numbers, objects, functions).

  • Maintaining the order of key insertion.

  • Providing built-in methods for easier manipulation.

JavaScript Map is a data structure that holds key-value pairs. It has many essential uses.

Note: WeakMap is similar to Map, but all keys in a WeakMap must be objects.

JavaScript Map syntax#

To create a new Map, follow the syntax below:

let map = new Map([iterable]);

Example

We want to create one that stores names as keys and scores as values.

Javascript (babel-node-es2024)
'use strict';
//START:DEFINE
const scores =
new Map([['Ruby', 12], ['Steven', 11], ['Sam', 15], ['Robin', 14]]);
scores.set('James', 14);
console.log(scores.size);
//END:DEFINE

We did three things in the above code:

  • Lines 4–5: We initialize the scores map with names and scores.

  • Line 7: We add a key and value to the map using the set() method.

  • Line 9: We use the size property to determine how many keys are on the map.

Let’s look into the visual representation of this map:

Visual representation of names as keys and scores as values
Visual representation of names as keys and scores as values

Connect the dots between powerful algorithms and efficient coding:

Cover
Mastering Data Structures and Sorting Algorithms in JavaScript

Are you ready to become a top-notch JavaScript developer? Understand two of the most important concepts in programming - Data Structures & Sorting Algorithms. Learn to make efficient algorithms that save space and time if you want to excel in the field of software development. Take this interactive course to find out how to employ the most effective data structure in any scenario. This course covers sorting algorithms and their time complexity using JavaScript along with various data structures like Trees, Graphs, Heaps, Linked lists and many more.

3hrs
Beginner
34 Playgrounds
304 Illustrations

JavaScript Map methods and use cases#

Now that we understand the JavaScript Map syntax and have walked through an example implementation, let’s discuss some commonly used map methods and their use cases.

Initialize a Map with an iterable object#

The Map() constructor initializes a map with an iterable object:

let userRoles = new Map( [
['ruby', 'director'],
['steven', 'producer'],
['foo', 'writer'],
['robin', 'actress']
]);

Return a value mapped to a specific key#

The get() method returns a value mapped to a specific key:

userRoles.get('robin'); // actress

If you pass a key that is not in the map, it will return as undefined:

let emma = {name: 'Emma'};
userRoles.get(emma); // undefined

Return a boolean value showing whether a specified key exists#

The has() method returns a boolean value showing whether a specified key exists:

userRoles.has('emma'); // false
userRoles.has('ruby'); // true

Return the number of entries in the Map#

The size property returns the number of entries in the Map:

console.log(userRoles.size); // 4

Return a new iterator object that includes the value of each element#

The values() method returns a new iterator object that includes the value of each element:

for (let role of userRoles.values()) {
console.log(role);
}
// director
// producer
// writer
// actress

Remove specified elements from the Map object#

The delete() method removes specified elements from the Map object:

userRoles.delete('ruby');

Remove all elements in the map object#

The clear() method removes all elements in the Map object:

userRoles.clear();

If we checked the size, it would return as zero:

console.log(userRoles.size); // 0

Demo of Map methods and use cases#

Let’s run the following playground to see the discussed code in action:

Javascript (babel-node-es2024)
let userRoles = new Map( [ ['ruby', 'director'], ['steven', 'producer'], ['foo', 'writer'], ['robin', 'actress'] ]);
console.log(userRoles.get('robin')); // actress)
let emma = {name: 'Emma'};
console.log(userRoles.get(emma)); // undefined
console.log(userRoles.has('emma')); // false
console.log(userRoles.has('ruby')); // true)
console.log(userRoles.size); // 4
for (let role of userRoles.values()) {
console.log(role);
}
// director
// producer
// writer
// actress
userRoles.delete('ruby');
console.log(userRoles.has('ruby')); // false)
userRoles.clear();
console.log(userRoles.size); // 0

Other useful Map methods#

  • forEach(callback[, thisArg]): It invokes a callback for each key-pair value in the map in insertion order.

  • set(key, value): It sets the value for the key in the map object.

  • values() and keys(): They return a new iterator with the keys for elements in insertion order.

  • entries(): It iterates over a collection of keys and values.

Advanced Map concepts#

JavaScript Map is a valuable collection type that makes programming with JavaScript cleaner and more efficient. We’ve learned about map syntax, methods, and use cases. Now, you’re ready to tackle more advanced concepts. Some recommended concepts to cover next are:

  • Metaprogramming: Enhancing the functionality of objects and classes.

  • Prototypal inheritance: Leveraging JavaScript’s prototype chain.

  • Implementing constructors: Building reusable templates for creating objects.

  • Literals: Simplifying object creation with concise syntax.

Why use a Map instead of an object?#

Traditionally, JavaScript objects were used for key-value storage, but they have significant limitations:

  • Keys in objects are always strings or symbols.

  • Iterating through objects can be unreliable due to inherited properties.

A Map resolves these issues by:

  • Supporting keys of any type.

  • Guaranteeing the order of insertion.

Object vs. Map

Feature

Object

Map

Key type

Strings, Symbols

Any type

Order

Not guaranteed

Guaranteed

Iteration

Complex, manual

Built-in methods

Best practices for using Map#

  • Use Map for predictable key-value operations.

  • Prefer Map over objects when keys are dynamic or non-string.

  • Avoid excessive size to ensure performance efficiency.

Wrapping up and next steps#

JavaScript’s Map is a game changer for handling key-value pairs, offering better flexibility, ordering, and efficiency than objects. If you’re working with dynamic keys, non-string identifiers, or need predictable iteration, Map is the way to go.

Try refactoring an existing object-based key-value structure in your codebase to use Map and see the benefits firsthand!

Happy learning!

Continue reading about JavaScript#

Explore more key JavaScript concepts and advancements with the following blogs:

Elevate your JavaScript expertise with this comprehensive course, designed to help you master modern features introduced in ES6, ES7, and ES8. Whether you’re looking to write cleaner, more efficient code or stay competitive in front-end and back-end development, this course below offers the tools, examples, and exercises to ensure you’re equipped with the latest skills.

Rediscovering JavaScript: ES6, ES7 & ES8

Cover
Rediscovering JavaScript: ES6, ES7 & ES8

JavaScript is one of the most powerful and flexible languages, and it has evolved rapidly in recent years. The ECMAScript 2015 (ES6), 2016 (ES7), and 2017 (ES8) have introduced many new features for front-end and back-end development. This course covers the modern JavaScript features to make your code elegant, concise, expressive, and less error prone. You will start by learning the basic features of modern JavaScript, including variables, constants, classes, iterators, arguments, loops, arrow functions, and symbols. In the second half, you will dive deep into complex features, like destructuring, literals, inheritance, modules, promises, and metaprogramming. This course has several examples for you to practice and strengthen your coding skills. Moreover, every chapter has quizzes and multiple exercises to strengthen your grasp of the concepts. By the end of this course, you will be able to add new features with minimum effort and write code more efficiently.

13hrs
Intermediate
13 Challenges
12 Quizzes

Frequently Asked Questions

Is a JavaScript Map a HashMap?

No, a JavaScript Map is not the same as a HashMap, though they share similarities. Both structures store key-value pairs and offer efficient lookups. However:

  • A JavaScript Map can have keys of any type (primitive or object), while traditional HashMaps in other languages often only support certain types like strings or integers.
  • It maintains the insertion order of keys, making iterate over its elements predictable.
  • It is a built-in class introduced in ES6 and is designed for use in JavaScript, while a HashMap is a generic concept implemented differently across programming languages.

In JavaScript, a Map is often preferred over plain objects for key-value storage when more features, like key ordering and type flexibility, are needed.

What is Array.prototype.map()?

Array.prototype.map() is available on array instances. It creates a new array populated with the results of calling a provided function on every element in the calling array. The method transforms arrays by applying a function to each element in the original array.

How to use the map() function?

The map() function in JavaScript is a method used with arrays. It creates a new array by applying a given function to each original array element.

Syntax:

array.map(function(currentValue, index, arr), thisValue);
  • currentValue: The current element being processed
  • index (optional): The index of the current element
  • arr (optional): The array map() was called on
  • thisValue (optional): Value to use as this when executing the callback function

Example:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

In this example, map() applies the function num * 2 to each number array element and returns a new array with doubled values.

What are map(), filter(), and reduce() methods in JavaScript?

These are common methods used for array manipulation in JavaScript, each serving a unique purpose:

  • map(): It transforms each element of an array based on a provided function and returns a new array with the same number of elements.

    Example:

    const numbers = [1, 2, 3];
    const squared = numbers.map(num => num * num);
    console.log(squared); // [1, 4, 9]
    
  • filter(): It filters elements of an array based on a condition specified in a callback function and returns a new array with elements that pass the condition.

    Example:

    const numbers = [1, 2, 3, 4, 5];
    const evenNumbers = numbers.filter(num => num % 2 === 0);
    console.log(evenNumbers); // [2, 4]
    
  • reduce(): It reduces an array to a single value by applying a function repeatedly to its elements. It requires an initial accumulator value, which is updated with each iteration.

    Example:

    const numbers = [1, 2, 3, 4];
    const sum = numbers.reduce((acc, num) => acc + num, 0);
    console.log(sum); // 10
    

These methods are powerful for data processing and manipulation, making JavaScript code cleaner and more functional.

What are the key differences between Map and array.map()?

JavaScript Map:

  • Stores key-value pairs with keys of any type (primitives or objects).
  • Maintains the order of insertion.
  • Optimized for efficient lookups, insertions, and deletions.
  • Iterated using methods like forEach() or for...of loops.
  • Returns a new Map object when operations produce new collections.

array.map():

  • An array method for transforming each element using a provided function.
  • Returns a new array containing the transformed values.
  • Leaves the original array unchanged.
  • Manages its internal iteration without exposing keys.

Written By:
Erin Schaffer

Free Resources