Mastering Iteration: A Guide to Sets and Maps in JavaScript
Written on
Chapter 1: Introduction to Sets and Maps
In modern JavaScript, sets and maps serve as powerful data structures that offer unique benefits when managing collections of values or pairs of keys and values. For developers aiming to enhance their coding practices, knowing how to iterate through these collections is crucial. This guide will cover essential techniques for looping through sets and maps, accompanied by up-to-date code examples.
What Are Sets and Maps?
Before we explore the various looping mechanisms, it's essential to clarify what sets and maps are.
A Set is an unordered collection comprised of unique values. It can store primitive data types such as numbers and strings, as well as objects. For instance, you can create and log a set as follows:
const mySet = new Set([1, 2, 3]);
console.log(mySet); // Output: Set {1, 2, 3}
Conversely, a Map is an ordered collection of key-value pairs, where keys must be unique, while values can repeat. Maps can contain both primitives and objects. Here's how you create and log a map:
const myMap = new Map([[1, 'one'], [2, 'two']]);
console.log(myMap); // Output: Map(2) {'1' => 'one', '2' => 'two'}
Now, let's dive into the methods available for looping through these data structures.
Section 1.1: Looping Through Sets
There are three primary methods to iterate through a set in JavaScript: for...of, forEach(), and the keys(), values(), and entries() methods.
Using For…Of
The for...of statement is the simplest way to loop through a set. Consider this example:
const mySet = new Set(['a', 'b', 'c']);
for (let value of mySet) {
console.log(value);
}
// Output:
// a
// b
// c
Using ForEach()
Another way to iterate through a set is through the forEach() method, which only handles values since sets do not possess keys. Here's an example:
mySet.forEach((value) => {
console.log(value);
});
// Output:
// a
// b
// c
Using Keys(), Values(), Entries() Methods
These methods return iterators for accessing specific properties of the set. Importantly, they all start at the same iterator position, so using them multiple times does not interfere with each other.
Here's how to use the keys() method:
const mySet = new Set(['a', 'b', 'c']);
for (let value of mySet.keys()) {
console.log(value);
}
// Output:
// a
// b
// c
Likewise, the equivalent example with the values() method looks like this:
for (let value of mySet.values()) {
console.log(value);
}
// Output:
// a
// b
// c
Lastly, the entries() method returns pairs of keys and values in arrays. However, since sets do not explicitly store keys, both elements in each array will match:
for (let entry of mySet.entries()) {
console.log(entry);
}
// Output:
// Array ['a', 'a']
// Array ['b', 'b']
// Array ['c', 'c']
Section 1.2: Looping Through Maps
Similar to sets, maps can be iterated through using methods like for...of, forEach(), and the keys(), values(), and entries() functions.
Using For…Of
When employing for...of on a map, the iteration encompasses the map's entries, each of which consists of a key followed by its corresponding value:
const myMap = new Map([['key1', 'val1'], ['key2', 'val2']]);
for (let entry of myMap) {
console.log(entry);
}
// Output:
// Array ['key1', 'val1']
// Array ['key2', 'val2']
Using ForEach()
The forEach() function also allows actions on every item in a collection. For maps, it requires two arguments: the current value and the respective key:
myMap.forEach((value, key) => {
console.log(${key}: ${value});
});
// Output:
// key1: val1
// key2: val2
Using Keys(), Values(), Entries() Methods
Maps, like sets, support keys(), values(), and entries(). These functions provide iterable objects for keys, values, or key-value pairs. Here are some examples:
Keys():
for (let key of myMap.keys()) {
console.log(key);
}
// Output:
// key1
// key2
Values():
for (let value of myMap.values()) {
console.log(value);
}
// Output:
// val1
// val2
Entries():
for (let entry of myMap.entries()) {
console.log(entry);
}
// Output:
// Array ['key1', 'val1']
// Array ['key2', 'val2']
Conclusion
Mastering the techniques to loop through sets and maps in JavaScript allows developers to fully leverage the capabilities of these data structures. By understanding these concepts, you can write cleaner and more efficient code that effortlessly tackles complex tasks.
The first video, "You Should Use Maps and Sets in JS," explores the advantages and applications of maps and sets in JavaScript.
The second video, "Maps and for of loop in JavaScript," demonstrates practical looping techniques for maps.