JavaScript Map and Its Methods
Introduction to Maps in JavaScript
JavaScript Map and Its Methods
Do You Know
Maps are especially useful when dealing with non-string keys or when the order of insertion is crucial. They offer a flexible and efficient approach to key-value data management.
A Map in JavaScript is a collection of key-value pairs where both keys and values can be of any type. Unlike regular objects, Maps allow using any data type (including objects or functions) as keys, and they maintain the insertion order of entries.
Key Characteristics
- Key-value pairs: Maps store elements as key-value pairs.
- Any data type for keys: Keys can be of any type (objects, functions, etc.), unlike objects that use strings or symbols as keys.
- Maintains order: Maps remember the original insertion order of keys.
- Iterable: Maps can be iterated easily using built-in iteration methods.
Example
let myMap = new Map();
myMap.set('name', 'John');
myMap.set(1, 'one');
console.log(myMap); // Output: Map {'name' => 'John', 1 => 'one'}
Creating Maps
Maps can be created using the Map constructor and can optionally take an iterable like an array of key-value pairs.
Creating an Empty Map
let emptyMap = new Map();
Creating a Map from an Array of Key-Value Pairs
let mapFromArray = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
console.log(mapFromArray); // Output: Map { 'key1' => 'value1', 'key2' => 'value2' }
Map Methods
JavaScript provides various methods for adding, removing, and accessing elements in a Map.
set()
The set() method adds or updates an element with a specified key and value in the Map. If the key already exists, its value is updated.
let fruits = new Map();
fruits.set('apple', 5);
fruits.set('banana', 10);
console.log(fruits); // Output: Map { 'apple' => 5, 'banana' => 10 }
get()
The get() method retrieves the value associated with a specified key in the Map.
let cars = new Map();
cars.set('ford', 'Mustang');
console.log(cars.get('ford')); // Output: Mustang
has()
The has() method checks if a Map contains a certain key. It returns true if the key exists and false otherwise.
let animals = new Map();
animals.set('lion', 'wild');
console.log(animals.has('lion')); // Output: true
console.log(animals.has('cat')); // Output: false
delete()
The delete() method removes an element by its key from the Map and returns true if successful.
let countries = new Map();
countries.set('USA', 'Washington DC');
countries.delete('USA');
console.log(countries.has('USA')); // Output: false
clear()
The clear() method removes all elements from the Map, making it empty.
let cities = new Map();
cities.set('New York', 'USA');
cities.clear();
console.log(cities.size); // Output: 0
size
The size property returns the number of elements (key-value pairs) in the Map.
let languages = new Map([
['JavaScript', 'ES6'],
['Python', '3.9']
]);
console.log(languages.size); // Output: 2
Iterating Over Maps
Maps provide various methods to iterate through their key-value pairs.
forEach()
The forEach() method executes a provided function once for each key-value pair in the Map.
let books = new Map();
books.set('Title1', 'Author1');
books.set('Title2', 'Author2');
books.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Output:
// Title1: Author1
// Title2: Author2
keys()
The keys() method returns an iterator over the keys of the Map.
let map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
for (let key of map.keys()) {
console.log(key);
}
// Output:
// key1
// key2
values()
The values() method returns an iterator over the values of the Map.
let map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
for (let value of map.values()) {
console.log(value);
}
// Output:
// value1
// value2
entries()
The entries() method returns an iterator over the key-value pairs of the Map.
let map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
for (let entry of map.entries()) {
console.log(entry);
}
// Output:
// ['key1', 'value1']
// ['key2', 'value2']
Symbol.iterator
The default iterator for Map is the entries() method, which allows you to use a for...of loop directly on the Map.
let map = new Map([
['a', 1],
['b', 2]
]);
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// a: 1
// b: 2
Differences Between Maps and Objects
While both Maps and objects store key-value pairs, they have some key differences:
- Data type of keys: Object keys are always strings or symbols, whereas Map keys can be of any data type (objects, functions, etc.).
- Order: Maps preserve the insertion order of key-value pairs, whereas the order of keys in objects is more complex.
- Size: Maps have a built-in size property, while the size of an object must be determined manually.
- Performance: Maps generally perform better when frequent additions and removals of key-value pairs are needed.
Important Note
We will delve deeper into the properties and methods of objects in a subsequent chapter.
Summary
- Maps in JavaScript offer a more flexible and efficient way to manage key-value pairs compared to plain objects.
- They allow for any data type as keys and maintain the insertion order of elements.
- Maps provide a range of methods to add, retrieve, remove, and iterate through their elements.
- They are particularly useful when non-string keys or insertion order are critical.