In JavaScript, a Map is a built-in object that allows us to store key-value pairs, where both the keys and the values can be of any type.
This makes maps a versatile data structure for associating information.
Here's a basic overview of how we can use Map in JavaScript:
// Creating an empty Map let yourMap = new Map(); // Adding entries to a Map yourMap.set('name', 'Alice'); yourMap.set('age', 23); // Creating a Map with initial key-value pairs let keyValueMap = new Map([ ['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3'] ]); // Printing yourMap Object // Output: Map(2) { 'name' => 'Alice', 'age' => 23 } console.log(yourMap) // Output: { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } console.log(keyValueMap)
set(key, value): Adds a new key-value pair to the Map.
let yourMap = new Map(); // Adding entries to a Map yourMap.set('name', 'Alice'); yourMap.set('age', 23); // set method yourMap.set('gender', 'female');
let yourMap = new Map(); yourMap.set('name', 'Alice'); yourMap.set('age', 23); yourMap.set('gender', 'female'); // get method for retrieving value associated with specified key console.log(yourMap.get('name')); // 'Alice'
let yourMap = new Map(); yourMap.set('name', 'Alice'); yourMap.set('age', 23); yourMap.set('gender', 'female'); // check `key` exists in `map` object console.log(yourMap.has('gender')); // true console.log(yourMap.has('profession')); // false
let yourMap = new Map(); yourMap.set('name', 'Alice'); yourMap.set('age', 23); yourMap.set('gender', 'female'); // remove key from map object yourMap.delete('age');
let yourMap = new Map(); yourMap.set('name', 'Alice'); yourMap.set('age', 23); yourMap.set('gender', 'female'); yourMap.delete('age'); console.log(yourMap.size); // Output: 2 -> now, yourMap contains :-> name and gender, age we have deleted.
let yourMap = new Map(); yourMap.set('name', 'Alice'); yourMap.set('age', 23); yourMap.set('gender', 'female'); yourMap.delete('age'); yourMap.clear();
get(key): Retrieves the value associated with the specified key.
has(key): Returns a boolean indicating whether the Map contains a specific key.
yourMap.forEach((value, key) => { console.log(key, value); }); // Or using a for...of loop for (let [key, value] of yourMap) { console.log(key, value); }
delete(key): Removes the entry with the specified key from the Map.
size: Returns the number of entries (key-value pairs) in the Map.
clear(): Removes all entries from the Map.
We can use the forEach method or the for...of loop to iterate over the entries of a Map.
Map is particularly useful when we need to associate unique keys with values, and it provides more flexibility compared to using objects as keys in plain JavaScript objects.