Chapter 9 from Secrets of the JavaScript Ninja, Second Edition
Dealing with collections
This chapter covers:
-
Creating and modifying arrays
-
Using and reusing array functions
-
Creating dictionaries with maps
-
Creating collections of unique objects with sets
Now that we’ve spent some time wrangling the particularities of object-orientation in JavaScript, we’ll move on to a closely related topic: collections of items. We’ll start with arrays, the most basic type of collection in JavaScript, and look at some array peculiarities you may not expect if your programming background is in another programming language. We’ll continue by exploring some of the built-in array methods that will help you write more elegant array-handling code.
Next, we’ll discuss two new ES6 collections: maps and sets. Using maps, you can create dictionaries of a sort that carry mappings between keys and values—a collection that’s extremely useful in certain programming tasks. Sets, on the other hand, are collections of unique items in which each item can’t occur more than once. Let’s begin our exploration with the simplest and most common of all collections: arrays.
Do you know?
Q1:
What are some of the common pitfalls of using objects as dictionaries or maps?
Q2:
What value types can a key/value pair have in a Map
?
Q3:
Must the items in a Set
be of the same type?