How to create a shallow Copy of a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 28, 2021

banner

Photo from Unsplash

Create a shallow Copy of a Map in JavaScript #

To create a shallow copy of a Map, pass the existing Map as a parameter to the Map() constructor, e.g. const newMap = new Map(oldMap). The Map() constructor takes an iterable, such as another Map, and adds the key-value pairs to the new Map.

index.js
const oldMap = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(oldMap); const copy = new Map(oldMap); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(copy);

We used the Map() constructor to create a shallow copy of an existing Map.

The only parameter the constructor takes is an iterable, such as an array, or another Map.

The elements in the iterable should be key-value pairs, e.g. a two dimensional array or another Map object.

index.js
const example1 = [ ['name', 'Tom'], ['country', 'Chile'], ]; const example2 = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]);

Each key-value pair gets added to the new Map.

The new Map object has a completely different reference and location in memory. Adding key-value pairs to it does not interact with the existing Map.

index.js
const oldMap = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // {'name' => 'Tom', 'country' => 'Chile'} console.log(oldMap); const copy = new Map(oldMap); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(copy); copy.set('age', 30); // 👇️ {'name' => 'Tom', 'country => 'Chile', 'age' => 30} console.log(copy); // 👇️ {'name' => 'Tom', 'country => 'Chile'} console.log(oldMap);

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.