Sling Academy
Home/JavaScript/How to create a Map object in JavaScript

How to create a Map object in JavaScript

Last updated: March 22, 2023

Map objects were added to JavaScript as part of the ECMAScript 2015 (ES6) standard. They are collections of key-value pairs where the keys can be any value (including functions, objects, or any primitive), and the values can be any value as well. Map objects remember the original insertion order of the keys and allow iteration over them by key-value pairs.

The only way to create a new Map object is to use the new Map() constructor (there is an exception where you call the clone() method on a map to create a copy, but we don’t count in the context of this article). However, you can use various sources of data for this. Let’s see some examples for a better understanding.

Creating a Map object from an array of key-value pairs

Here’s the code:

// create a new Map object
let myMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
]);

// log the Map object
console.log(myMap);

Output:

Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }

Using the Map.set() method to add key-value pairs

In this example, we will create an empty map with the new Map() constructive, then call the set() method to add new key-value pairs to that map one by one:

// create an empty map
const myMap = new Map();

// add key-value pairs to the map
myMap.set('place', 'Sling Academy');
myMap.set([1, 2, 3], 'This uses an array as a key');
myMap.set({ foo: 'bar' }, 'This uses an object as a key');

console.log(myMap);

Output:

Map(3) {
  'place' => 'Sling Academy',
  [ 1, 2, 3 ] => 'This uses an array as a key',
  { foo: 'bar' } => 'This uses an object as a key'
}

Creating a Map object from an iterable object that yields key-value pairs

You can also construct a Map object from an iterable object that yields key-value pairs, such as a Set:

const set = new Set([
  ['a', 1],
  ['b', 2],
  ['c', 3],
]);

const map = new Map(set);
console.log(map);

Output:

Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }

Creating a Map object with Object.entries()

You can also create a Map object by using an object literal as an argument for the Object.entries() method and passing it to the new Map() constructor as shown below:

let obj = { a: 1, b: 2, c: 3 };
let map = new Map(Object.entries(obj));
console.log(map);

Output:

Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }

Creating a Map object from an existing Map object

It’s possible to create a new Map object by using the new Map() constructor with the existing Map object as an argument:

const map1 = new Map([['a', 1], ['b', 2], ['c', 3]]);

// create a new map with the same key-value pairs as map1
const map2 = new Map(map1);

// map2 is a new map, but it is not the same as map1
if(map1 === map2) {
    console.log('map1 and map2 are the same');
} else {
    console.log('map1 and map2 are different things');
}

console.log(map2);

Output:

map1 and map2 are different things
Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }

That’s it. The tutorial ends here. Happy coding & have a nice day!

Next Article: How to iterate over a Map object in JavaScript

Series: Modern Data Structures in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration