JavaScript Maps

JavaScript Maps

JavaScript Maps

 

In JavaScript, a Map is a built-in object that allows you to store key-value pairs of any type, whether primitive values or object references. The keys are unique and any value (both objects and primitive values) can be used as either a key or a value.

Here’s an example of creating a new Map:

				
					let myMap = new Map();
				
			

You can add key-value pairs to a Map using the “set()” method, like this:

				
					myMap.set("key1", "value1");
myMap.set(42, true);
myMap.set({ name: "John" }, [1, 2, 3]);

				
			

In this example, we’re adding three key-value pairs to the Map.

You can check the size of a Map using the “size” property:

				
					console.log(myMap.size); 
				
			

This code will output “3” to the console.

You can retrieve the value associated with a specific key using the “get()” method:

				
					console.log(myMap.get("key1")); 
				
			

This code will output “value1” to the console, since “value1” is the value associated with the key “key1”.

You can check if a Map contains a specific key using the “has()” method:

				
					console.log(myMap.has(42));
				
			

This code will output “true” to the console, since the Map contains the key 42.

You can remove key-value pairs from a Map using the “delete()” method:

				
					myMap.delete({ name: "John" });
				
			

In this example, we’re removing the key-value pair with the key that is an object with a “name” property equal to “John”.

You can iterate over the key-value pairs in a Map using the “for…of” loop:

				
					for (let [key, value] of myMap) {
  console.log(key + " = " + value);
}

				
			

This code will output the following to the console:

				
					key1 = value1
42 = true

				
			

Maps can be useful when you need to store a collection of key-value pairs with unique keys. They also have other methods like “clear()” to remove all key-value pairs and “forEach()” to perform a function on each key-value pair in the map.

Join To Get Our Newsletter
Spread the love