let myMap = new Map([
["😀", "smiley face"],
["👽", "alien"],
["🦄", "unicorn"]
]);
// Iterate both keys and values
for (let [key, value] of myMap.entries())
{
console.log(`Map key: ${key}, value: ${value}`);
}
The for-of loop could also be written for (let [key, value] of myMap)
, i.e. without the call to .entries()
, as the default if you don't specify something else is to iterate entries.
The let [key, value]
syntax is part of JavaScript called destructuring. It's another fairly complex area we won't go any further in to right now, but we covered it briefly here just to demonstrate how you can iterate both keys and values in a map at the same time. For now, it's worth pointing out the similarity to how maps are created with two-element arrays for each key and value, e.g. ["😀", "smiley face"]
: the for-of loop will place the first element in the first variable, and the second element in the second variable.
Converting to an array
Similar to sets, maps can also be coverted to an array with [...myMap]
. This creates an array in the same format used to initialise a map: an array of two-element arrays with the key and value.
let myMap = new Map([
["😀", "smiley face"],
["👽", "alien"],
["🦄", "unicorn"]
]);
// Convert map back to array
let asArray = [...myMap];
// Log array to console.
// This is the same format as the map was
// initialised with, i.e.:
// [
// ["😀", "smiley face"],
// ["👽", "alien"],
// ["🦄", "unicorn"]
// ]
console.log("Map converted to array: ", asArray);
Conclusion
In this part we've covered:
- Creating arrays, accessing array elements, and reading the array length
- Iterating arrays with both for loops and for-of loops
- Adding and removing array elements
- Creating sets, adding and removing set values, and reading the set size
- Iterating sets, and converting sets back to arrays
- Creating maps, adding and removing keys and values, and retrieving values from keys
- Different ways to iterate maps, and converting maps back to arrays
These data structures come in useful with day-to-day programming in JavaScript, so it's good to get familiar with how they work. In particular arrays are very common, so if you want to focus on one area, focus on them.
We've touched on a few built-in features of JavaScript in this guide so far. In the next part we'll focus on covering more built-ins, including some of the many features that browsers provide.
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following MDN Web Docs links:
Part 10
When you're ready to continue, head on to the next part at Learn JavaScript in Construct, part 10: Standard library!