Today, we're learning about Map
in JavaScript. A Map stores data as key-value pairs. We'll recall how to create Maps, implement them, and delve into the details of their memory management.
Maps are versatile data structures in JavaScript. They store key-value pairs and accept any data type as a key — even objects and functions!
Here is how we create an empty Map:
JavaScript1let myMap = new Map(); // creates an empty Map
Here, myMap
is a new JavaScript Map, eagerly awaiting to store your keys and values.
Maps provide some essential built-in methods:
set(key, value)
: Stores a key-value pair.get(key)
: Retrieves the value of a key.has(key)
: Checks if a key exists and returnstrue
orfalse
.delete(key)
: Erases a key-value pair.size
: Returns the count of key-value pairs.
To gain a better understanding, let's apply these methods:
JavaScript1let myMap = new Map(); 2 3// Add pairs with set 4myMap.set('apples', 10); // Adds a new pair 5myMap.set('bananas', 6); // Adds another pair 6 7// Use get 8console.log(myMap.get('apples')); // Outputs: 10, gets apples' value 9 10// Apply has 11console.log(myMap.has('bananas')); // Outputs: true, checks for bananas' existence 12 13// Delete with delete 14myMap.delete('bananas'); // Deletes bananas and its value from the map 15 16// Check size 17console.log(myMap.size); // Outputs: 1; gives the number of pairs
JavaScript uses a Hash Table to implement Maps. This table ensures the Map's size adjusts based on the stored data, optimizing memory usage.
The time complexity of get
, set
, has
, and delete
operations in Maps is O(1)
. This signifies that they execute instantly, regardless of the Map's size.
Imagine running a store with thousands of items. A Map lets you quickly handle any item!
JavaScript1let superstoreStock = new Map(); 2 3// Stock item 4superstoreStock.set('toothpaste', 1000); // Stock 1000 toothpaste 5superstoreStock.set('soap', 500); // Stock 500 soap 6superstoreStock.set('shampoo', 800); // Stock 800 shampoo 7 8// Purchase is made 9console.log(superstoreStock.get('toothpaste')); // Outputs: 1000 (current quantity) 10superstoreStock.set('toothpaste', superstoreStock.get('toothpaste') - 1); // Toothpaste is bought 11console.log(superstoreStock.get('toothpaste')); // Outputs: 999 (updated quantity) 12 13// Item is out of stock, will be replaced later 14superstoreStock.delete('soap'); // Soap is removed 15console.log(superstoreStock.has('soap')); // Outputs: false 16 17// Item is restocked 18superstoreStock.set('soap', 500); // Soap is restocked 19console.log(superstoreStock.has('soap')); // Outputs: true
Excellent work! You've now learned about JavaScript Maps. Use what you've learned in your practice exercises. Keep exploring Maps and stay curious!