Map

In JavaScript, a Map is a collection of key-value pairs where both keys and values can be of any type. This makes Map more versatile than objects, which only support string or symbol keys. Map preserves the insertion order of elements, which is not guaranteed in objects.

Creating a Map

A Map can be created by passing an array of key-value pairs to the Map constructor.

Example:

javascript
	let capitals = new Map([
	  ['USA', 'Washington, D.C.'],
	  ['France', 'Paris'],
	  ['Japan', 'Tokyo']
	]);

Adding Elements to a Map

Elements can be added to a Map using the set method.

Example:

javascript
	capitals.set('India', 'New Delhi');

Accessing Map Elements

Values in a Map can be accessed using the get method.

Example:

javascript
	console.log(capitals.get('France')); // Paris

Checking for Elements

To check if a Map contains a key, use the has method.

Example:

javascript
	if (capitals.has('Japan')) {
	  console.log('Japan is in the map');
	} else {
	  console.log('Japan is not in the map');
	}

Iterating Over a Map

Map objects can be iterated using methods like forEach or the for...of loop.

Example:

javascript
	capitals.forEach((value, key) => {
	  console.log(`${key}: ${value}`);
	});
	
	for (let [key, value] of capitals) {
	  console.log(`${key}: ${value}`);
	}

Removing Elements

Elements can be removed from a Map using the delete method. To remove all elements, use the clear method.

Example:

javascript
	capitals.delete('USA'); // Removes the key-value pair for 'USA'
	capitals.clear(); // Clears the map

Size of a Map

The number of key-value pairs in a Map can be found using the size property.

Example:

javascript
	console.log(capitals.size); // Outputs the number of key-value pairs in the map

Differences from Objects

  • Key Types: Map keys can be of any type, whereas object keys are strings or symbols.
  • Order of Elements: Map preserves the order of elements.
  • Size Property: Map has a size property, while the size of an object must be determined manually.

Conclusion

The Map object in JavaScript is a useful data structure for storing pairs of keys and values. Its ability to use any type as a key and to maintain the order of elements makes it a powerful tool for complex data structures.