Overview

10 Dealing with collections

This chapter introduces collections in JavaScript by starting with arrays, then expanding to maps, sets, and techniques for keeping data immutable. It emphasizes that JavaScript collections are flexible but come with important tradeoffs around performance, mutation, and how different data structures behave under the hood. Along the way, it shows how TypeScript and utility libraries can help developers write safer, cleaner collection-handling code.

Arrays are presented as the most familiar collection type, but with JavaScript-specific behavior: they can hold mixed types, grow and shrink dynamically, and return undefined for missing items instead of throwing errors. The chapter covers creation, adding and removing items from either end or anywhere in the array, and common operations such as iterating, mapping, flattening, testing conditions, searching, filtering, sorting, and reducing. It highlights when methods like for...of, map, flatMap, every, some, find, filter, sort, and reduce are useful, while also noting their limitations and performance implications.

The chapter then turns to maps and sets as more specialized alternatives to ordinary objects and arrays. Maps provide reliable key-value storage with any kind of key, while weak maps avoid memory leaks by allowing garbage collection of unreferenced object keys; sets offer fast membership checks and enforce uniqueness, with newer methods for union, intersection, difference, and subset testing. Finally, the chapter explains why immutability matters in application state, especially in React, shows how TypeScript’s read-only types can prevent accidental mutation, and demonstrates how Immer can make immutable updates feel like direct mutation while actually producing safe copied data.

Writing to an array index outside of array bounds expands the array.
The push and pop methods modify the end of an array, whereas shift and unshift modify the array’s beginning.
Deleting an item from an array creates a hole in the array.
The map function calls the provided callback function (f) on each array item, and creates a new array with callback return values.
The find function finds one item in an array: the first item for which the find callback returns true.
The filter function creates a new array that contains all items for which the callback returns true.
The reduce function applies a callback to an aggregated value and each item in an array to reduce the array to a single value.
A map is a collection of key-value pairs, where a key can be anything—even another object.

Summary

  • Arrays in JavaScript are dynamic and resize automatically when new items are added.
  • We can modify the contents of an array using several methods accessible from array objects:
    • The built-in push and pop methods add items to and remove items from the end of the array.
    • The built-in shift and unshift methods add items to and remove items from the beginning of the array.
    • The built-in splice method can be used to remove items from and add items to arbitrary array positions.
  • Arrays have several useful methods:
    • The map method creates a new array with the results of calling a callback on every element.
    • The every and some methods determine whether all or some array items satisfy a certain criterion.
    • The find and filter methods find array items that satisfy a certain condition.
    • The sort method sorts an array in-place.
    • The reduce method aggregates all items in an array into a single value.
  • Maps are collections of key-value pairs. Whereas objects can only use strings and symbols as keys, maps can use anything as a key.
  • Sets are collections of distinct items. They’re effectively maps with only keys, no values.
  • Mutability refers to the ability to modify (“mutate”) a collection. Immutable collections are often preferred to avoid bugs from unexpected mutations.
    • Objects, arrays, maps, and sets are all mutable, but you can make them effectively immutable using TypeScript’s read-only types.
    • Immer allows you to create a modified copy of an immutable collection by applying your changes to a “draft,” which works like a mutable version of that collection.

FAQ

What makes JavaScript arrays different from arrays in many typed languages?JavaScript arrays are dynamic: items can be different types, the array size can change at any time, and arrays are also objects. Accessing an out-of-bounds index returns undefined instead of throwing an error.
How do you create arrays in JavaScript?You can create arrays with array literals like [] or with the built-in Array constructor. In most cases, array literals are preferred.
What is the difference between push, pop, shift, and unshift?push adds to the end, pop removes from the end, shift removes from the beginning, and unshift adds to the beginning of an array.
Why is using delete on an array item usually a bad idea?delete removes the item but leaves a hole in the array. The array length does not change, and iterators like forEach skip over the empty slot.
When should you use splice versus slice?splice changes the original array by removing and/or inserting items, while slice returns a copied portion of the array without modifying the original.
What is the difference between forEach, map, and flatMap?forEach is for side effects and returns nothing. map creates a new array by transforming each item. flatMap is like map, but each callback can return an array, which gets flattened into the result.
How do every and some help test array conditions?every returns true only if all items satisfy the callback condition. some returns true if at least one item satisfies the condition. Both can stop early.
Why are maps better than plain objects for some key-value data?Maps only contain the entries you explicitly add, and keys can be any type, including objects. Plain object keys are usually coerced to strings, which can cause limitations and collisions.
What is the main advantage of WeakMap and WeakSet?They hold weak references to their object keys/items, so entries can be garbage-collected when nothing else references those objects. This helps prevent memory leaks.
Why are immutable collections important, and how do TypeScript and Immer help?Immutable collections help avoid accidental mutations, which is especially important for state management such as in React. TypeScript can enforce read-only collections at compile time, and Immer lets you write mutation-like code while producing immutable copies under the hood.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Secrets of the JavaScript Ninja, Third Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Secrets of the JavaScript Ninja, Third Edition ebook for free