- Courses
- đ»Programming Languages
- đJavaScript
- Core Objects
- Maps
On this page
Maps in JavaScript
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
Creating a Mapâ
You can create a Map using the new Map() syntax.
let map = new Map();
//or
const myMap = new Map([
["key1", "value1"],
["key2", "value2"],
["key3", "value3"],
]);
Setting, Getting, and Checking Valuesâ
The set method is used to set a key-value pair, get method is used to get the value by a key, and has method is used to check if a key exists.
map.set("name", "John"); // sets the key 'name' with value 'John'
console.log(map.get("name")); // outputs 'John'
console.log(map.has("name")); // outputs true
Size and Clearâ
The size property returns the current number of entries, and clear method removes all entries.
console.log(map.size); // outputs 1
map.clear();
console.log(map.size); // outputs 0
Deleting a Valueâ
The delete method removes a value by its key.
map.set("name", "John");
map.delete("name");
console.log(map.has("name")); // outputs false
Iterating Over a Mapâ
You can use for...of loop to iterate over a Map. It returns key-value pairs in the insertion order.
map.set("name", "John");
map.set("age", 30);
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
//to iterate over values only
for (let [_, value] of map) {
console.log(value);
}
//to iterate keys only
for (let key of map.keys()) {
}
Object vs Mapâ
- Keys of any type: While objects only allow strings and symbols to be keys, a Map allows any data type to be a key including functions, objects, and any primitive value.
- Order: The
Mapobject holds key-value pairs and remembers the original insertion order of the keys. On the other hand, the order of keys in an object is complex and doesnât rely on the order of insertion. - Size: You can easily get the number of entries in a Map using the
sizeproperty, while you have to manually count the number of properties in an Object.
Tuples as keysâ
Since JavaScript does not support tuples, like other languages do, one way to use tuples as keys it to convert tuples to a string and then use them as keys:
const key = `${i},${j}`;
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Date
Next
Sets
- Creating a Map
- Setting, Getting, and Checking Values
- Size and Clear
- Deleting a Value
- Iterating Over a Map
- Object vs Map
- Tuples as keys
