Chapter 9: Chapter 9. Dealing with collections
Introduces arrays, maps, and sets by identifying the basic role of each collection.
After this chapter you will be able to
- Array map and set roles. Distinguish arrays as JavaScript’s most basic collection, maps as key–value dictionaries, and sets as collections whose items cannot occur more than once.
- JavaScript arrays as objects. Explain that JavaScript arrays hold collections of items but are also objects, which lets them use methods and can have performance costs.
- Array creation choices. Describe the two ways to create an array and explain why the section recommends array literals over the Array constructor.
- Indexed reads and writes. Explain what happens when code reads or writes an array index beyond the current bounds.
- Array length behavior. Describe how an array’s length changes when an item is written beyond its bounds or when length is assigned directly.
- Array End Modification Methods. Describe which end of an array push, unshift, pop, and shift modify, and whether each adds or removes an item.
- End Operation Performance Difference. Explain why push and pop are significantly faster than shift and unshift, and state the section’s recommendation.
- Splice removal behavior. Describe how splice removes items starting at an index, what happens to later items, and what it returns.
- Splice insertion and replacement. Describe how splice can insert items at an arbitrary array position, including while removing existing items.
- Array iteration with forEach. Explain how forEach visits array items through a callback and why it can be clearer than a counter-based for loop.
- New arrays through mapping. Describe how map creates a new array from callback results, such as extracting weapons from an array of ninja objects.
- All versus any item tests. Distinguish every from some when testing whether array items satisfy a condition.
- Matching items and their indexes. Distinguish finding a matching item, collecting all matches, and finding an item’s position using the array methods introduced here.
- Sort comparator return values. Explain how a comparator callback tells sort the relative order of two array items, using ninja names as an example.
- Single values through reduce. Trace how reduce combines an initial value with successive array items to produce one result.
- Array push on a normal object. Trace how the example uses Array.prototype.push to add an item to a normal object.
- Key-to-value map collections. Explain that a dictionary or map associates a key with a specific value, as when organizing website text for different languages.
- Inherited properties in object maps. Explain why looking up an undefined dictionary entry named constructor does not return undefined when a plain object is used as a map.
- String conversion of object keys. Trace why using two HTML elements as keys on a plain object causes the second element's data to replace the first element's data, and relate this to the choice of Map.
- Creating and retrieving map entries. Describe how the built-in Map constructor creates a map, set associates a key with a value, and get retrieves the value for a key used in set.
- Object identity as map keys. Explain why two separate URL objects pointing to the same page create different mappings when used as Map keys.
- Map iteration results. Describe how to iterate over a map with for...of, what each iteration yields, and how to iterate over only its keys or values.
- Distinct Items and Set Operations. Explain what makes a collection a set and describe how the pre-ES6 object-based example mimics one with has, add, and remove.
- Limits of Object-Based Sets. Justify why the object-based imitation is inadequate and why ES6 introduced a dedicated set collection.
- Set creation and uniqueness. Explain how to create an empty or pre-filled Set and why adding the same item twice leaves only one occurrence.
- Set union construction. Explain that a union contains every element from both collections only once, and describe how spreading the collections into an array and passing it to the Set constructor produces that result.
- Set intersection by filtering. Explain that the intersection contains only elements present in both sets, and describe how the ninja–samurai example converts the ninjas set to an array and filters it for members of the samurai set.
- Set difference membership test. Explain that the difference of sets A and B contains elements in A but not in B, and describe how negating the second set’s `has` check selects those elements.
What it builds on
- Callback functions (chapter 3) · Using a function as a callback
- Invocation with the apply and call methods (chapter 4) · Using call to set a function’s context.
- Do you know? (chapter 7) · Objects have prototypes through which properties can be accessed.
Section by section
Introduction
Introduces arrays, maps, and sets by identifying the basic role of each collection.
- Array map and set roles: Distinguish arrays as JavaScript’s most basic collection, maps as key–value dictionaries, and sets as collections whose items cannot occur more than once.
Why it matters: These distinctions give you a starting point for choosing a collection.
Key terms: arrays, maps, sets, dictionaries, keys, values
9.1 Arrays
Introduces arrays as collections and explains that JavaScript arrays are objects, with both benefits and performance costs.
- JavaScript arrays as objects: Explain that JavaScript arrays hold collections of items but are also objects, which lets them use methods and can have performance costs.
Why it matters: This explains why array methods are available and why JavaScript arrays may differ from arrays you know from other languages.
Key terms: arrays, objects, methods
9.1 Do you know?
This section poses three questions to check readers’ prior knowledge of objects as maps, Map key-value types, and Set item types.
9.1.1 Creating arrays
This section explains how to create JavaScript arrays and how indexed access and the length property behave when arrays grow or shrink.
- Array creation choices: Describe the two ways to create an array and explain why the section recommends array literals over the Array constructor.
Why it matters: Choosing the simpler form makes array creation straightforward and avoids relying on a replaceable constructor. - Indexed reads and writes: Explain what happens when code reads or writes an array index beyond the current bounds.
Why it matters: Reading a missing position and assigning to one have different effects. - Array length behavior: Describe how an array’s length changes when an item is written beyond its bounds or when length is assigned directly.
Why it matters: An array’s length can change through indexed writes or direct assignment, and need not count only defined items.
Key terms: array literal, Array constructor, index notation, undefined, array bounds, hole, length property, expand, trim
9.1.2 Adding and removing items at either end of an array
This section explains how four array methods add or remove items at either end and why operations at the end are faster.
- Array End Modification Methods: Describe which end of an array push, unshift, pop, and shift modify, and whether each adds or removes an item.
Why it matters: Choosing the right method lets you change the intended end of an array. - End Operation Performance Difference: Explain why push and pop are significantly faster than shift and unshift, and state the section’s recommendation.
Why it matters: The difference helps you choose the faster methods when either end would suit your task.
Key terms: push, unshift, pop, shift, indexes
9.1.3 Adding and removing items at any array location
This section explains why deleting an array item leaves a hole and how splice removes or inserts items at arbitrary positions.
- Deletion versus array removal: Explain why deleting an array item does not properly remove it from the array.
Why it matters: It explains why deleting a position is not a substitute for removing an array item. - Splice removal behavior: Describe how splice removes items starting at an index, what happens to later items, and what it returns.
Why it matters: splice removes items without leaving the hole that simple deletion creates. - Splice insertion and replacement: Describe how splice can insert items at an arbitrary array position, including while removing existing items.
Why it matters: The same method handles inserting or replacing items away from either end of an array.
Key terms: hole, undefined, splice, index, array of items that have been removed, insert, arbitrary positions
9.1.4 Common operations on arrays
This section explains how built-in array methods handle iteration, mapping, condition testing, searching, sorting, and aggregation without manually managing every loop.
- Array iteration with forEach: Explain how forEach visits array items through a callback and why it can be clearer than a counter-based for loop.
Why it matters: It lets you describe a visit to every item without distracting loop bookkeeping. - New arrays through mapping: Describe how map creates a new array from callback results, such as extracting weapons from an array of ninja objects.
Why it matters: It captures a common transformation without manually creating and filling the result array. - All versus any item tests: Distinguish every from some when testing whether array items satisfy a condition.
Why it matters: The choice depends on whether your question is about all items or at least one. - Matching items and their indexes: Distinguish finding a matching item, collecting all matches, and finding an item’s position using the array methods introduced here.
Why it matters: Choosing the method that returns what you need avoids confusing an item, a list of items, and a position. - Sort comparator return values: Explain how a comparator callback tells sort the relative order of two array items, using ninja names as an example.
Why it matters: You can specify the desired order without implementing a sorting algorithm yourself. - Single values through reduce: Trace how reduce combines an initial value with successive array items to produce one result.
Why it matters: It expresses calculations such as an array total as one accumulation rather than a manual loop.
Key terms: for loop, forEach, callback, map, mapping an array, every, some, find, filter, indexOf
9.1.5 Reusing built-in array functions
Shows how a normal object can store a collection alongside other state by reusing built-in array methods.
- Collection objects with extra state: Explain why the example uses a normal object to hold a collection rather than adding metadata and methods to each new array.
Why it matters: It explains why the example makes an ordinary object behave like a collection. - Array push on a normal object: Trace how the example uses Array.prototype.push to add an item to a normal object.
Why it matters: It shows how changing a method’s function context lets existing array code work on this object. - Custom collection helper methods: Describe what the example’s add, gather, and find methods do.
Why it matters: These helpers show how the object exposes useful collection behavior without rewriting every operation.
Key terms: normal object, metadata, collection, Array.prototype.push, length property, call method, function context, numbered property, add, gather
9.2 Maps
Introduces maps as key-to-value collections for tasks such as localization, and cautions that using ordinary objects as dictionaries is not generally reliable.
- Key-to-value map collections: Explain that a dictionary or map associates a key with a specific value, as when organizing website text for different languages.
Why it matters: This gives you the basic idea behind the collection discussed in the rest of the section. - Objects as dictionary stand-ins: Describe why ordinary JavaScript objects might seem useful as dictionaries and state the section’s caution about relying on them generally.
Why it matters: It explains why a familiar object-based solution is tempting while preserving the section’s warning about it.
Key terms: key, value, dictionaries, maps, localization, objects, named properties, values, dictionary
9.2.1 Don’t use objects as maps
This section explains why plain JavaScript objects are unreliable as maps: inherited properties can appear as entries, and non-string keys can collapse into the same string key.
- Inherited properties in object maps: Explain why looking up an undefined dictionary entry named constructor does not return undefined when a plain object is used as a map.
Why it matters: An object-map lookup can appear to find an entry you never added. - String conversion of object keys: Trace why using two HTML elements as keys on a plain object causes the second element's data to replace the first element's data, and relate this to the choice of Map.
Why it matters: Two distinct elements can unexpectedly share one object property, losing the data associated with the first.
Key terms: prototype, constructor property, undefined, string-only keys, toString, [object HTMLDivElement], Map
9.2.2 Creating our first map
This section shows how to create and use a JavaScript Map and explains why separate objects remain distinct map keys even when their contents match.
- Creating and retrieving map entries: Describe how the built-in Map constructor creates a map, set associates a key with a value, and get retrieves the value for a key used in set.
Why it matters: These operations are the basis for storing and looking up values by key in a Map. - Inspecting and removing mappings: Explain what a Map’s size property and has and delete methods do.
Why it matters: These features let you check a map’s contents and remove an entry when needed. - Object identity as map keys: Explain why two separate URL objects pointing to the same page create different mappings when used as Map keys.
Why it matters: Matching object contents do not make two object keys interchangeable in a Map.
Key terms: Map constructor, set, get, key, value, mapping, size, has, delete, key equality
9.2.3 Iterating over maps
This section explains how to iterate over a map’s entries, keys, and values, and why entry order is predictable.
- Map iteration results: Describe how to iterate over a map with for...of, what each iteration yields, and how to iterate over only its keys or values.
Why it matters: It lets you choose whether to process whole map entries or just their keys or values. - Map insertion order: Explain what order map iteration follows and how that differs from iterating over an object with for...in.
Why it matters: Predictable iteration order is a useful distinction between maps and objects.
Key terms: map, for...of, keys, values, insertion order, for...in
9.3 Sets
Introduces sets as collections of distinct items, shows how they were mimicked with objects before ES6, and explains why ES6 added a dedicated set type.
- Distinct Items and Set Operations: Explain what makes a collection a set and describe how the pre-ES6 object-based example mimics one with has, add, and remove.
Why it matters: Distinctness explains both the purpose of a set and why its add operation checks for an existing item. - Limits of Object-Based Sets: Justify why the object-based imitation is inadequate and why ES6 introduced a dedicated set collection.
Why it matters: These drawbacks explain why the book moves from a hand-built imitation to ES6 sets.
Key terms: set, distinct items, has, add, remove, prototype objects, ES6, sets
9.3.1 Creating our first set
Introduces how to create a Set, use its basic methods and property, and iterate over its unique items.
- Set creation and uniqueness: Explain how to create an empty or pre-filled Set and why adding the same item twice leaves only one occurrence.
Why it matters: Uniqueness is the reason to choose a set when duplicate items should not be stored. - Set membership and size: Describe what a set’s has and add methods do and how to find its number of items.
Why it matters: These are the basic operations for checking, adding, and counting set items. - Set iteration order: Explain how to iterate over a set and what order its items appear in.
Why it matters: The order of set iteration is predictable from the order items were inserted.
Key terms: Set constructor, set, unique items, has, add, size property, for...of loop, insertion order
9.3.2 Union of sets
This section explains what a union contains and how to create one by combining collections and letting a Set remove duplicates.
- Set union construction: Explain that a union contains every element from both collections only once, and describe how spreading the collections into an array and passing it to the Set constructor produces that result.
Why it matters: It lets you combine collections without manually checking whether an item was already included.
Key terms: union, spread operator, Set constructor
9.3.3 Intersection of sets
Defines set intersection and explains how to find members shared by two sets using array filtering.
- Set intersection by filtering: Explain that the intersection contains only elements present in both sets, and describe how the ninja–samurai example converts the ninjas set to an array and filters it for members of the samurai set.
Why it matters: It connects the meaning of set intersection to a practical way to find shared members.
Key terms: intersection, set, filter method, spread operator
9.3.4 Difference of sets
Defines set difference and shows how to select elements of one set that are absent from another.
- Set difference membership test: Explain that the difference of sets A and B contains elements in A but not in B, and describe how negating the second set’s `has` check selects those elements.
Why it matters: It lets you select members exclusive to one set rather than members shared by both.
Key terms: difference of two sets, samurai.has(ninja)
9.4 Summary
9.5 Exercises
Where this is used later
- Feature detection and polyfills (chapter 14) · Earlier array operations provide context for a method that searches array items.
Concepts explained in this chapter
- sorting algorithmAn Array method that sorts an array in place using a comparison function or default ordering.
- Array.prototype.filterAn Array method that creates a new array containing elements that pass a callback test.
- allAn Array method that returns true if every element passes a callback test.
- anyAn Array method that returns true if at least one element passes a callback test.
- findAn Array method that returns the first element passing a callback test, or undefined if none does.
- forEachAn Array method that invokes a callback once for each array element.
- mapAn Array method that creates a new array by applying a callback to each element.
- reduction operationAn Array method that applies a callback across elements to accumulate a single result.
- MapA collection type that stores key-value associations and supports efficient lookup by key.
- pushAn Array method that appends one or more elements and returns the new length.
- arrayAn ordered, indexed collection of values.
- setA JavaScript collection of unique values.
- set unionA set operation that produces a set containing every element present in either operand set.
- array methodA method available on arrays for operations such as iteration, transformation, or querying.
- set intersectionA set operation that produces a set containing the elements common to the operand sets.
- set differenceThe set of elements in one set that are not in another set.
- callbackA function supplied to other code to be invoked later when a condition or event occurs.
- constructor functionA function intended to create and initialize an object when invoked with new.
- arrow functionA concise JavaScript function syntax that captures this lexically from its creation context rather than creating its own binding.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
