Creating Maps in JavaScript
In JavaScript, a Map is a collection of key-value pairs where keys can be of any type (objects, functions, primitives). Maps maintain the insertion order of elements and provide useful methods like .set()
, .get()
, .has()
, .delete()
, and more.
There are several ways to create a Map:
1. Using the Map Constructor (Empty Map)
You can create an empty Map and then add entries dynamically using the .set()
method.
- Keys can be any type: string, number, boolean, object, or even a function.
- Map preserves the insertion order.
Syntax:
const myMap = new Map();
Example:
const myMap = new Map();
myMap.set('name', 'John');
myMap.set('age', 30);
myMap.set(true, 'isActive');
console.log(myMap);
// Output: Map(3) { 'name' => 'John', 'age' => 30, true => 'isActive' }
2. Initialize a Map with Key-Value Pairs
You can create a Map directly with an array of key-value pairs. Each pair is an array [key, value]
.
- Quick way to create a Map with predefined entries.
- Especially useful when converting objects or arrays into Maps.
Syntax:
const myMap = new Map([
[key1, value1],
[key2, value2],
...
]);
Example:
const myMap = new Map([
['name', 'Alice'],
['age', 25],
[true, 'isActive']
]);
console.log(myMap);
// Output: Map(3) { 'name' => 'Alice', 'age' => 25, true => 'isActive' }
3. Using the .set()
Method After Creation
You can start with an empty Map and add entries one by one using .set()
.
Calling .set()
with an existing key overwrites the previous value.
Syntax:
map.set(key, value);
Example:
const myMap = new Map();
myMap.set('country', 'India');
myMap.set('capital', 'New Delhi');
myMap.set(1, 'Number Key');
console.log(myMap);
// Output: Map(3) { 'country' => 'India', 'capital' => 'New Delhi', 1 => 'Number Key' }
myMap.set('country', 'USA');
console.log(myMap.get('country')); // Output: USA
4. Converting Objects or Arrays into Maps
Since Maps support any type of key, you can easily convert an object or array into a Map.
From Object:
const obj = { name: 'John', age: 30 };
const myMap = new Map(Object.entries(obj));
console.log(myMap);
// Output: Map(2) { 'name' => 'John', 'age' => 30 }
From Array of Arrays:
const arr = [['id', 101], ['role', 'admin']];
const myMap = new Map(arr);
console.log(myMap);
// Output: Map(2) { 'id' => 101, 'role' => 'admin' }