0
0
JavascriptHow-ToBeginner · 3 min read

How to Create a Map in JavaScript: Syntax and Examples

In JavaScript, you create a map using the Map object by calling new Map(). You can add key-value pairs with set(key, value) and retrieve values using get(key).
📐

Syntax

The basic syntax to create a map is using the Map constructor. You can optionally pass an array of key-value pairs to initialize it.

  • new Map(): creates an empty map.
  • new Map([[key1, value1], [key2, value2]]): creates a map with initial entries.
  • map.set(key, value): adds or updates a key-value pair.
  • map.get(key): retrieves the value for a key.
javascript
const map = new Map();
map.set('key1', 'value1');
const value = map.get('key1');
Output
value1
💻

Example

This example shows how to create a map, add key-value pairs, and get values by keys.

javascript
const fruits = new Map();
fruits.set('apple', 5);
fruits.set('banana', 10);
fruits.set('orange', 7);

console.log(fruits.get('apple'));
console.log(fruits.get('banana'));
console.log(fruits.get('grape'));
Output
5 10 undefined
⚠️

Common Pitfalls

Common mistakes include using objects as keys without understanding reference equality, or confusing Map with plain objects.

Remember, Map keys can be any value, including objects, but keys are compared by reference, not by value.

javascript
const map = new Map();
const objKey1 = { id: 1 };
const objKey2 = { id: 1 };

map.set(objKey1, 'Object 1');
console.log(map.get(objKey2)); // undefined because objKey2 is a different object reference

// Correct way: use the same object reference
console.log(map.get(objKey1)); // 'Object 1'
Output
undefined Object 1
📊

Quick Reference

MethodDescription
new Map()Creates a new empty map
new Map(iterable)Creates a map with initial key-value pairs
map.set(key, value)Adds or updates a key-value pair
map.get(key)Returns the value for the key or undefined
map.has(key)Checks if the key exists in the map
map.delete(key)Removes the key and its value
map.clear()Removes all key-value pairs
map.sizeReturns the number of key-value pairs

Key Takeaways

Use new Map() to create a map in JavaScript.
Add entries with set(key, value) and get values with get(key).
Map keys can be any type, but object keys must be the same reference to match.
Maps preserve insertion order and have useful methods like has, delete, and clear.
Avoid confusing Map with plain objects; they behave differently.