Maps

Contact Us or call 1-877-932-8228
Maps

Maps

So far in this lesson we've written prototypes (classes) to create our own custom objects, with properties and methods specific to our needs. We'll look now at a few built-in objects from JavaScript that may be useful to you, the first of which is the Map object. Similar to the built-in Object, a Map is a collection of key-value pairs. But, unlike an Object, a Map allows for any data type as a key, not just Strings and Symbols. So a key could be an array, an instance of a custom class, etc.

Below are listed common Map properties and methods:

Common Map Properties
Property Description Example
constructor Creates a Map theMap = new Map()
size Returns the number of elements theMap.size
Common Map Methods
Method Description Example
clear Removes all elements theMap.clear()
delete Removes a specified element theMap.delete(16) //deletes element with index 16
forEach Iterates over the Map theMap.forEach(function (value, key, map) { //do something with each key/value })
get Returns element from specified key theMap.get("arizona") // gets value of element with key "arizona"
has Returns true if key exists theMap.has(20) // returns true if key 20 exists
set Adds element or modifies existing element theMap.set(-9, "blue") // adds element "blue" with key -9, or changes value of existing key
toString Returns string representation theMap.toString()

Let's look at a simple example:

Code Sample:

AdvancedObjects/Demos/map.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Map</title>
</head>
<body>
	<h1>Map</h1>
	<script>
		class Person {
			constructor(fname, lname, age) {
				this.fname = fname;
				this.lname = lname;
				this.age = age;
			}
			toString() {
				return this.fname + ' ' + this.lname;
			}
		}

		var p = new Person('Jane','Doe',31);
		var arr = ['one', 'two', 'three'];
		var myMap = new Map();
		myMap.set(1, "black");
		myMap.set("lemonade", 2);
		myMap.set(p, 3);
		myMap.set(47, arr);
		myMap.set(1, "red");

		document.write('<ul>');
		myMap.forEach(function (value, key, map) {
			document.write('<li>');
			document.write(key.toString() + ' - ' + value.toString());
			document.write('</li>');
		});
		document.write('</ul>');

		document.write('<p>Size of map: ' + myMap.size + '</p>');
		document.write('<p>Get element with Person key: ' + myMap.get(p) + '</p>');
		document.write('<p>Does myMap have element with key Person p?: ' + myMap.has(p) + '</p>');
		document.write('<p>Does myMap have element with key 15?: ' + myMap.has(15) + '</p>');
		myMap.clear();
		document.write('<p>(myMap cleared)</p>');
		document.write('<p>Size of map: ' + myMap.size + '</p>');
	</script>
</body>
</html>

Code Explanation

We create a new Map on line 23 and add elements to it with the set method. As you can see, keys for our Map (myMap) can be an object of class Person or an array, in addition to numbers and strings.

We can also create a Map object from any iterable object when calling the constructor. An iterable object is any object that implements the Iterable interface - data types like Array, String, String, and Map (itself) are all examples of iterable objects in JavaScript. If we return the iterator object associated with the iterable object, we can create a Map from the original object.

Thus we can create a new Map with code like this:

var arr = [1, 2, 3];
var m = new Map(arr.entries());

where entries() returns the iterator object from the array. For a string, we could do the following:

var str = "abc";
var m = new Map(Array.from(str).entries());

Map vs Object?

Because JavaScript already offers a built-in data structure (Object) for associative arrays, a reasonable question is "why use maps at all?" The ability to use non-primitive data as keys is one answer to this question; as you saw in the example above, we can use an object from a custom class (like Person) or an array as the key for a Map, which we can't do for an Object.

Another reason to use a Map is that, unlike with Objects, the built-in iterator (forEach) offers an easy way to loop over the collection housed in the Map object, and those key/value pairs are returned by the iterator in insertion order (that is, in the order in which we added them), which isn't necessarily true for iterating over an Object. Furthermore, the size property makes it considerably easier to find the length of a Map, which is more difficult with an Object.

Next