Chapter 10: Dealing with collections
The chapter introduces JavaScript collections by distinguishing arrays, maps, and sets, then previews a discussion of immutability.
After this chapter you will be able to
- Array map and set distinctions. Distinguish the collection types introduced here: arrays are the most common JavaScript collection, maps hold key-value pairs, and sets hold items without duplicates.
- Dynamic JavaScript array characteristics. Explain how JavaScript arrays differ from the fixed-size, same-type arrays familiar from languages such as C, and describe the convenience and performance tradeoff noted here.
- Array creation choices. Distinguish array literals from the Array constructor, including how a single numeric constructor argument differs from multiple arguments and why the constructor can be useful with fill.
- Array indexes and holes. Explain what happens when code reads or writes an array index beyond its existing items, and distinguish a hole from an item whose value is undefined.
- Array length changes. Describe how an out-of-range write affects array length and how assigning a larger or smaller value to length changes the array.
- Array end operations. Describe which methods add or remove an item at the beginning or end of an array.
- Holes left by delete. Explain what happens when the delete operator removes an array item, compared with methods that move other items.
- Splice at arbitrary positions. Describe how splice removes or inserts items at a chosen array position and what its arguments specify.
- Array iteration choices. Distinguish for…of from for…in when traversing arrays, and explain why a loop may be preferable to forEach when iteration must stop early or wait for asynchronous work.
- One-to-one and variable transformations. Explain how map builds a new array from callback results and how flatMap lets each original item contribute zero, one, or multiple results.
- All-or-some condition tests. Distinguish what every and some test, including when each can stop and how callback return values are interpreted.
- Finding versus filtering items. Distinguish searching for an item with find from constructing a new array of matching items with filter, and describe how their callback results are treated.
- Sort comparison and mutation. Explain how sort interprets a compare function’s result and distinguish its mutation of the original array from toSorted; describe why Intl.Collator is preferred for sorting strings.
- Reduce accumulator flow. Trace how reduce uses an initial accumulator, the current item, and each callback result to produce a final value.
- Explicit map entries. Explain why prototype inheritance can make it hard to tell what is in an object used as a key-value store, and contrast that with a Map’s explicitly stored entries. Describe Object.create(null) as a way to avoid the prototype issue for objects.
- Flexible map keys. Distinguish object keys from Map keys: bracket-access keys on objects are converted to strings except for symbols, while Maps can use keys of any type, including objects.
- Separate object metadata. Explain why a map with object keys can hold metadata outside the original objects and how clear() helps dispose of temporary metadata.
- Map key equivalence. Explain when two keys refer to the same map entry, including mutated objects, different references to one object, identical-looking objects, and the numbers 1 and string "1".
- Map entries and iteration order. Explain that a for...of loop over a map visits its mappings in insertion order, yielding each mapping as a two-item [key, value] entry that can be destructured.
- WeakMap keys and garbage collection. Explain why a Map used for ninja metadata can retain discarded ninja objects, and how WeakMap changes what happens when no other references to a key remain.
- Distinct items in sets. Explain that a set holds distinct items, so an item cannot appear more than once, and why it is preferable to using a map to track them.
- Set construction and uniqueness. Explain how to create a Set from an array and what happens when the array contains duplicate items.
- Set and Map API differences. Distinguish a Set's item-based operations from a Map's entry-based operations while identifying their shared membership and size APIs.
- Set operations and subset checks. Distinguish what union, intersection, difference, and isSubsetOf do to two sets, including which methods create a new set and which tests membership.
- WeakSet and garbage collection. Explain why a WeakSet can track objects, such as ninjas who completed training, without preventing those objects from being garbage-collected.
- Mutation and API expectations. Explain that objects, arrays, maps, and sets are mutable, and why changing a collection after passing it to an API can be a problem.
- Immutable collection tradeoffs. Describe how an immutable collection avoids unexpected modification and what adding or removing an item requires instead.
- Immutable React state updates. Explain why a React to-do list should pass a new array to its state setter instead of pushing into the existing todos array, and describe both benefits of keeping the original array unchanged.
- Const assertions and precise types. Explain how `as const` preserves the exact contents of an array or object literal as type information, makes the example array read-only, and allows a union type to be derived from its items.
- Read-only enforcement boundaries. Distinguish TypeScript’s compile-time checks against collection mutation from runtime immutability, and explain why a read-only collection variable may still be reassigned.
- Nested copying tradeoffs. Explain why spreading a state object does not safely isolate nested changes, and why deep-copying the entire state can be wasteful.
- Immer drafts and produce. Trace how Immer's produce callback lets code modify a draft while producing an updated copy of read-only state, including the role of Proxy and the draft's TypeScript type.
What it builds on
- Iterables and iterators (chapter 8) · The idea of iterating over values with for…of.
- Dynamic inheritance with prototypes (chapter 9) · Objects inherit from prototypes.
- Customizing objects with properties (chapter 9) · Objects have properties accessed by keys.
- Type annotations and declarations (chapter 2) · TypeScript type declarations and annotations
- Intercepting object access with Proxy and Reflect (chapter 9) · Proxy can intercept interactions with an object
Section by section
Introduction
The chapter introduces JavaScript collections by distinguishing arrays, maps, and sets, then previews a discussion of immutability.
- Array map and set distinctions: Distinguish the collection types introduced here: arrays are the most common JavaScript collection, maps hold key-value pairs, and sets hold items without duplicates.
Why it matters: These distinctions give you a starting point for choosing which collection to explore for a task.
Key terms: arrays, maps, sets, key-value pairs
10.1 Arrays
Introduces JavaScript arrays as dynamic objects, notes their convenience and performance tradeoff, and distinguishes them from typed arrays.
- Dynamic JavaScript array characteristics: Explain how JavaScript arrays differ from the fixed-size, same-type arrays familiar from languages such as C, and describe the convenience and performance tradeoff noted here.
Why it matters: This explains both why ordinary JavaScript arrays are flexible to use and why that flexibility can carry a cost. - Typed array distinction: Distinguish typed arrays from traditional JavaScript arrays using the purpose and interface difference stated here.
Why it matters: It prevents confusion between the ordinary arrays discussed here and the separate typed-array types used for raw data.
Key terms: array, object, built-in methods, typed arrays, Uint8Array, Int32Array, raw data
10.1.1 Creating arrays
This section explains how to create arrays and how indexing and the length property behave when items are missing or array bounds change.
- Array creation choices: Distinguish array literals from the Array constructor, including how a single numeric constructor argument differs from multiple arguments and why the constructor can be useful with fill.
Why it matters: It helps you choose the intended way to create an array, especially when a constructor call contains a number. - Array indexes and holes: Explain what happens when code reads or writes an array index beyond its existing items, and distinguish a hole from an item whose value is undefined.
Why it matters: A missing array position can look like an undefined value when read but behave differently during iteration. - Array length changes: Describe how an out-of-range write affects array length and how assigning a larger or smaller value to length changes the array.
Why it matters: The length reports the array's extent, not necessarily the number of items present, and changing it can remove items.
Key terms: array literal, Array constructor, fill method, index notation, undefined, hole, forEach, length property, empty items
10.1.2 Adding and removing items at either end of an array
Explains how to add and remove items at either end of an array, how arrays can serve as stacks or queues, and why operations at the beginning can be costly.
- Array end operations: Describe which methods add or remove an item at the beginning or end of an array.
Why it matters: These four methods let you change an array at either end. - Array stack and queue roles: Explain the stack and queue behaviors the section attributes to dynamic arrays.
Why it matters: The order in which items leave a collection determines whether it behaves like a stack or a queue. - Cost of front-end changes: Explain why shift and unshift can be expensive on large arrays compared with push and pop.
Why it matters: The end you modify can affect performance when an array grows large.
Key terms: push, pop, shift, unshift, dynamic arrays, stack, queue, last in, first out, first in, first out, moved in memory
10.1.3 Adding and removing items at any array location
This section explains how deleting an array item differs from using splice, and distinguishes splice from slice and array-copying syntax.
- Holes left by delete: Explain what happens when the delete operator removes an array item, compared with methods that move other items.
Why it matters: Deleting an item may leave a hole where you expected the remaining items to move together. - Splice at arbitrary positions: Describe how splice removes or inserts items at a chosen array position and what its arguments specify.
Why it matters: Splice is the method described here for changing items at a chosen position without leaving a gap. - Slice and array copies: Distinguish slice from splice and state the two array-copying forms shown in the section.
Why it matters: The similar names are easy to confuse, but this section uses them for different purposes.
Key terms: delete operator, empty slot, splice, index, slice, spread syntax
10.1.4 Common operations on arrays
This section explains how to traverse arrays, transform and test their items, search and sort them, and accumulate a result.
- Array iteration choices: Distinguish for…of from for…in when traversing arrays, and explain why a loop may be preferable to forEach when iteration must stop early or wait for asynchronous work.
Why it matters: Choosing the right iteration form avoids surprising behavior when you need to stop or await work. - One-to-one and variable transformations: Explain how map builds a new array from callback results and how flatMap lets each original item contribute zero, one, or multiple results.
Why it matters: This distinction helps you choose between replacing every item and producing a result with fewer or more items. - All-or-some condition tests: Distinguish what every and some test, including when each can stop and how callback return values are interpreted.
Why it matters: These methods answer different questions without necessarily checking every item. - Finding versus filtering items: Distinguish searching for an item with find from constructing a new array of matching items with filter, and describe how their callback results are treated.
Why it matters: The choice depends on whether you need an item or a collection of matching items. - Sort comparison and mutation: Explain how sort interprets a compare function’s result and distinguish its mutation of the original array from toSorted; describe why Intl.Collator is preferred for sorting strings.
Why it matters: Understanding comparison results and mutation helps you sort in the intended order without accidentally changing shared data. - Reduce accumulator flow: Trace how reduce uses an initial accumulator, the current item, and each callback result to produce a final value.
Why it matters: Following the accumulator makes reduce understandable even when it builds something more complex than a sum.
Key terms: for…of, for…in, forEach, break, await, map, flat, flatMap, callback, every
10.2 Maps
This section explains why Maps can be preferable to objects for storing key-value pairs: they contain only explicitly stored entries and accept keys of any type.
- Explicit map entries: Explain why prototype inheritance can make it hard to tell what is in an object used as a key-value store, and contrast that with a Map’s explicitly stored entries. Describe Object.create(null) as a way to avoid the prototype issue for objects.
Why it matters: This distinction helps explain when a Map is clearer than an object used as a key-value store. - Flexible map keys: Distinguish object keys from Map keys: bracket-access keys on objects are converted to strings except for symbols, while Maps can use keys of any type, including objects.
Why it matters: The ability to use objects and other values as keys is a main reason to choose a Map.
Key terms: prototypes, Object.create(null), Maps, key-value pairs, object keys, symbols, keys
10.2.1 Creating our first map
This section shows how to create a typed map, use object keys for separate metadata, and determine when two keys identify the same entry.
- Typed map creation: Describe how to create an empty map with new Map<Key, Value>() and what the two TypeScript type parameters specify.
Why it matters: It gives you the starting point for storing typed key-value entries. - Separate object metadata: Explain why a map with object keys can hold metadata outside the original objects and how clear() helps dispose of temporary metadata.
Why it matters: Separate metadata is useful when an object should not be changed or the metadata is only temporary. - Map key equivalence: Explain when two keys refer to the same map entry, including mutated objects, different references to one object, identical-looking objects, and the numbers 1 and string "1".
Why it matters: It helps you predict which value a map lookup will retrieve.
Key terms: Map, Key, Value, type parameter, object keys, external metadata, clear(), garbage collection, map key, key1 === key2
10.2.2 Iterating over maps
This section explains how to iterate over maps in insertion order, choose between entries and key-only or value-only iterators, and convert between maps and objects.
- Map entries and iteration order: Explain that a for...of loop over a map visits its mappings in insertion order, yielding each mapping as a two-item [key, value] entry that can be destructured.
Why it matters: This lets you predict what a loop over a map produces and in what order. - Keys and values iterators: Distinguish direct map iteration from using keys() or values() when only one part of each mapping is needed, and explain the memory benefit stated here.
Why it matters: Choosing the appropriate iterator avoids collecting an unnecessary array when working with a large map. - Map and object conversion: Describe how entries support conversion from an object to a map and from a map to an object, including the stated limitation of map-to-object conversion.
Why it matters: The entry format connects maps and objects, but converting to an object can change the meaning of map keys.
Key terms: for...of, tuple, array destructuring, entry, keys, values, iterator objects, entries, Object.entries, Object.fromEntries
10.2.3 Weakly holding references with WeakMap
Explains how WeakMap avoids retaining discarded object keys and their metadata, and what limitations come with using it instead of Map.
- WeakMap keys and garbage collection: Explain why a Map used for ninja metadata can retain discarded ninja objects, and how WeakMap changes what happens when no other references to a key remain.
Why it matters: It explains when metadata storage can cause a memory leak and why WeakMap helps prevent it. - WeakMap access and key limits: Distinguish WeakMap from Map by describing its permitted keys and the limits on inspecting its contents.
Why it matters: These limits determine whether WeakMap fits a collection you need to inspect or traverse.
Key terms: Map, WeakMap, weak references, garbage-collection, memory leaks, objects as keys, primitives, size property, get(key), iterate
10.3 Sets
Introduces sets as collections of distinct items and contrasts them with using a map to track those items.
- Distinct items in sets: Explain that a set holds distinct items, so an item cannot appear more than once, and why it is preferable to using a map to track them.
Why it matters: This distinction helps you recognize when a set fits a collection of items better than a map.
Key terms: sets, distinct items, map, keys, values
10.3.1 Creating our first set
This section introduces Set construction, its item-based API, and why sets are useful for repeated membership checks.
- Set construction and uniqueness: Explain how to create a Set from an array and what happens when the array contains duplicate items.
Why it matters: Uniqueness is the defining behavior to remember when creating or adding to a set. - Set and Map API differences: Distinguish a Set's item-based operations from a Map's entry-based operations while identifying their shared membership and size APIs.
Why it matters: The comparison makes it easier to use the right collection API without treating set items as map entries. - Repeated membership lookup: Justify using a set when repeatedly checking whether the same array contains an item.
Why it matters: Repeated membership checks are a practical signal that a set may be the better collection.
Key terms: Set, constructor, add(item), Map API, has, size, iterator, entries, array.includes(item), set.has(item)
10.3.2 Combining and comparing sets
This section introduces ES2024 methods for combining and comparing sets and notes when they are practical to use.
- Set operations and subset checks: Distinguish what union, intersection, difference, and isSubsetOf do to two sets, including which methods create a new set and which tests membership.
Why it matters: Choosing the right operation makes the intended relationship between sets clear. - Runtime support for set methods: Explain why the section recommends checking runtime support before using these set methods, and what benefit it claims when they are supported.
Why it matters: A useful set method is only an option when the target runtime supports it.
Key terms: union, intersection, difference, isSubsetOf, ES2024, runtime, Node.js 22
10.3.3 Weakly holding references with WeakSet
This section explains how WeakSet tracks objects without preventing their garbage collection, along with its main limitations.
- WeakSet and garbage collection: Explain why a WeakSet can track objects, such as ninjas who completed training, without preventing those objects from being garbage-collected.
Why it matters: You can track objects without the collection itself keeping them in memory. - WeakSet storage and access limits: State the limitations given for WeakSet: it stores objects rather than primitives, has no size property, and cannot be iterated over.
Why it matters: These limits determine whether WeakSet fits a collection task.
Key terms: WeakSet, garbage-collected, memory leaks, objects, primitives, size property, iterate
10.4 Mutable and immutable collections
Introduces mutable and immutable collections, why unexpected mutation matters, and the costs of making changes without mutation.
- Mutation and API expectations: Explain that objects, arrays, maps, and sets are mutable, and why changing a collection after passing it to an API can be a problem.
Why it matters: This expectation explains why direct mutation can cause trouble even when a collection allows it. - Immutable collection tradeoffs: Describe how an immutable collection avoids unexpected modification and what adding or removing an item requires instead.
Why it matters: Immutability prevents surprise changes, but getting a changed collection has a cost.
Key terms: mutable collections, mutated, anti-pattern, immutable collections, in-place
10.4.1 The perils of mutability
This section uses a React to-do list to show why collection updates should preserve the original state, then compares ways to avoid mutation.
- Immutable React state updates: Explain why a React to-do list should pass a new array to its state setter instead of pushing into the existing todos array, and describe both benefits of keeping the original array unchanged.
Why it matters: A new array makes the update visible to React without disrupting work that still relies on the previous state. - Ways to avoid collection mutation: Distinguish using an immutable collection type from avoiding changes to a mutable collection, including the tradeoffs and limits described here.
Why it matters: The choice depends partly on whether you need to guard against mutation outside your own code.
Key terms: React state, todos, push, setTodos, spreading, immutable operation, Immutable.js, List, mutable collection, ESLint
10.4.2 Read-only collections in TypeScript
This section shows how TypeScript read-only collection types help prevent unintended mutation at compile time, while explaining their limits and the precise types available through `as const`.
- Const assertions and precise types: Explain how `as const` preserves the exact contents of an array or object literal as type information, makes the example array read-only, and allows a union type to be derived from its items.
Why it matters: One literal can define both the collection and a type that matches its values. - Read-only enforcement boundaries: Distinguish TypeScript’s compile-time checks against collection mutation from runtime immutability, and explain why a read-only collection variable may still be reassigned.
Why it matters: Read-only types help catch accidental changes in your code without guaranteeing that a collection cannot change at runtime. - Read-only map and set types: Describe how this section types a map as `ReadonlyMap`, why its key and value types need explicit attention, and what analogous type exists for sets.
Why it matters: The map example shows how to retain useful type precision while adding compile-time mutation checks.
Key terms: as const, readonly, NinjaName, string union, read-only type, compile-time error, runtime error, reassigned, ReadonlyMap, ReadonlySet
10.4.3 Immutable transformations with Immer
This section explains why nested immutable updates are difficult and how Immer creates updated copies through a mutable-looking draft.
- Simple immutable collection changes: Describe how the section uses spread to create an extended object or array and destructuring to omit selected entries.
Why it matters: These simple techniques provide a contrast with the harder case of updating nested state. - Nested copying tradeoffs: Explain why spreading a state object does not safely isolate nested changes, and why deep-copying the entire state can be wasteful.
Why it matters: It explains why nested immutable updates need more care than copying the outer object. - Immer drafts and produce: Trace how Immer's produce callback lets code modify a draft while producing an updated copy of read-only state, including the role of Proxy and the draft's TypeScript type.
Why it matters: The draft explains how mutation-style code can yield a new state without directly changing the original. - Immer support and performance limits: State which collections Immer handles by default, how the example enables maps and sets, and what performance tradeoff Proxy introduces.
Why it matters: These limits help determine when the convenience of Immer is worth using.
Key terms: spread operator, destructuring, shallow, deep copy, nested objects, Immer, produce, draft, Proxy, NinjaState
10.5 Summary
Where this is used later
- (chapter intro) (chapter 11) · Familiarity with conventional JavaScript arrays.
- Accessing buffered bytes with typed arrays (chapter 11) · Ordinary JavaScript arrays and their collection operations.
- Compiling regular expressions (chapter 12) · Arrays can be accessed by index.
- Importing and exporting in ESM (chapter 13) · Uses the distinction between changing an object and changing the variable that refers to it.
Concepts explained in this chapter
- arrayAn array is an ordered JavaScript collection whose elements are accessed by numeric indexes.
- for...ofJavaScript loop syntax that retrieves successive values from an iterable.
- Array.prototype.filterA JavaScript method that creates a new array containing the elements that satisfy a predicate.
- Array.prototype.sortA JavaScript method that sorts an array in place using a default ordering or a supplied comparison function.
- allA JavaScript method that returns true if every array element satisfies a predicate.
- anyA JavaScript method that returns true if at least one array element satisfies a predicate.
- findA JavaScript method that returns the first array element satisfying a predicate, or undefined if none does.
- mapA JavaScript method that creates a new array by applying a callback to each element of an array.
- Intl.CollatorIntl.Collator is a JavaScript internationalization API constructor that creates locale-sensitive string comparison objects.
- accumulatorAn accumulator is the intermediate value carried from one reduction step to the next and returned after the final step.
- comparison functionA compare function is a sorting callback that returns a negative, positive, or zero number to order two items.
- flatThe flat method creates an array by replacing nested arrays with their elements to a specified depth.
- flatmapflatMap is an array method that maps each element to a value and flattens the resulting arrays by one level.
- forEachThe forEach method is a JavaScript array method that invokes a callback for each assigned element while skipping unassigned index positions.
- tosortedThe toSorted method returns a sorted copy of an array without modifying the original array.
- readonly typeA TypeScript type whose properties or elements cannot be modified through values of that type.
- immutable collectionAn immutable collection is a collection whose contents cannot be modified after the collection is created.
- ImmerImmer is a JavaScript library that enables immutable updates by presenting mutable draft views and producing modified copies with structural sharing.
- MapA JavaScript Map is a collection that associates keys with values and permits keys of arbitrary value types, including objects.
- setA collection of unique items with no duplicate membership.
- as constA TypeScript const assertion that preserves literal types and applies readonly semantics to the asserted literal expression.
- destructuring assignmentDestructuring syntax assigns values extracted from an iterable or other structured value to program bindings.
- iteratorAn iterator is an object that advances through a sequence and reports each successive iteration result.
- JavaScriptJavaScript is a high-level programming language standardized as ECMAScript and widely used for web and general-purpose software development.
- typed arrayA typed array is a JavaScript array-like data structure that stores elements of a specified numeric type in a raw binary representation.
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.
