JavaScript Maps¶
Depending on the language, these can be called Maps, Dictionaries, or associative arrays. Although there are differences in how they are implemented, the basic idea is the same. In the same way that we can use an array to store multiple values within one variable, we can use a map
to store multiple values within a single variable. Instead of accessing the values based on an index number, however, we assign an arbitrary key
to access it’s associated value.
To create a map and set values:
let englishToFrench = new Map();
englishToFrench.set("hello", "bonjour");
englishToFrench.set("goodbye", "au revoir");
To access a value in the map:
englishToFrench.get("goodbye");
To check if a key exists inside a map:
if (englishToFrench.has("goodbye")) {
console.log(englishToFrench.get("goodbye"));
}
To remove a key/value pair from the map:
englishToFrench.delete("goodbye")
Note that we can save any type of data inside the value, not just a string. It can be a number, an object, an array, etc. A simple example would be to save coordinates (an x, y pair) into a map as an object…
CodingJS Practice Problems¶
Map Level 1¶
Map Level 2¶
Iterating Over a Map¶
Sometimes you want to look at every key/value pair within a map. There are a number of ways to do this, but one of the simplest is to use a for...of
loop, which could look like the following:
for (let [key, value] of someMap) {
// the key variable holds the value used to access something in the map
// the value variable holds whatever the contents are
// in other words, someMap.get(key) would return the same thing as value
}
To practice iterating through a map, you should try the following questions from CodingJS:
More In Depth Demo¶
Try beating my mind reader built in p5js. I won’t tell you how it works yet, but I do use the Map data type.
Assignment Idea¶
Give starter code
for movie review sentiment analysis, and have the students just fill in two functions (related to storing/accessing information from a Map). Idea from Nifty assignments
Practice Quiz¶
To confirm that you understand maps, you should try the Maps Practice Quiz.