05 — Data Structures — Arrays, Maps, Sets, and the Built-In Toolbox
"Arrays and objects, mostly" was my data-structures summary, and it undersold the toolbox. The idea that everything else hangs off: *JavaScript ships a small toolbox of collection types, and each one is purpose-built for a different shape of data — indexed sequences, keyed lookups, unique values, or raw bytes.* [1]
The framing that finally landed is grouping by shape, not by name. Once I stopped treating "array vs object" as the only choice, the right structure for a job became obvious:
Indexed collections: the array
The array is the workhorse — an ordered, dynamically-sized, indexed collection [2]. It holds any mix of types, grows and shrinks on demand, and ships a rich method set: push/pop (stack), shift/unshift (queue), and the functional trio map, filter, reduce for transformation without mutation.
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
const sum = nums.reduce((a, b) => a + b, 0); // 10That trio is the part I reach for daily. map transforms each element, filter keeps the ones that pass a test, reduce collapses the array into a single value. They compose — chaining filter().map() reads top-to-bottom and replaces most hand-written loops.
Keyed collections: Map, Set, and the Weak variants
When the key isn't a sequential integer, plain objects used to be the only answer — but objects have limits: keys are coerced to strings, insertion order isn't always preserved, and there's no easy way to ask "how many keys?". The keyed collections fix all of that [3][4].
- Map — key-value pairs where keys can be any type (including objects and functions). Remembers insertion order. map.set(k, v), map.get(k), map.has(k), map.size. Reach for Map when keys are dynamic or when you need ordered iteration.
- Set — a collection of unique values. The fastest way to dedupe: [...new Set(arr)]. Useful for membership checks (set.has(x) is O(1)) where arr.includes(x) is O(n).
- WeakMap / WeakSet — like Map/Set, but keys (WeakMap) or values (WeakSet) must be objects and are held weakly: when nothing else references the object, the garbage collector reclaims it and the entry disappears automatically [5]. The use case is associating extra data with an object without leaking it — private metadata, caches keyed by DOM nodes.
The "weak" part only matters for memory. If I want to attach a cache to a DOM element without keeping that element alive forever, a WeakMap keyed by the element is the right structure; a plain Map would pin it in memory and leak.
Typed arrays: raw binary
Typed arrays are array-like views over a fixed-length, fixed-type block of raw bytes [6]. Each variant — Int8Array, Uint8Array, Float32Array, Float64Array, and more — represents one numeric size and format. They're not for general-purpose lists; they're for binary data: file contents, image pixels, audio samples, network packets. Anywhere data arrives as bytes (WebGL buffers, the Fetch API's arrayBuffer(), FileReader), typed arrays are the interface.
const bytes = new Uint8Array([72, 105]); // two bytes
const view = new DataView(bytes.buffer); // read multi-byte values at offsetsThe key idea is the split between the buffer (the raw memory) and the view (how you read it). One buffer can be read through multiple views of different types — that's how binary file parsers work.
JSON and the built-in objects
Two more pieces of the toolbox round out the common case.
JSON (JavaScript Object Notation) isn't a data structure — it's a text format for representing structured data [7]. It's the lingua franca of web APIs and config files. The interface is two functions: JSON.stringify(obj) turns a JS value into a JSON string, JSON.parse(str) turns it back. The asymmetry to remember: JSON only carries strings, numbers, booleans, null, arrays, and plain objects — functions, undefined, Symbol, Map, and dates don't survive a round trip (dates become strings, the rest vanish).
The built-in objects — Math, Date, JSON itself, RegExp, Promise, Error, and all the global constructors — are always available without imports [8]. They're the standard library, small but sufficient: Math.max, Date.now(), RegExp for patterns, Promise for async work, Error for failure. Knowing they exist is half the battle; the other half is not reinventing what they already do.
How I use this
The decision tree is short. Ordered list of items → Array, and lean on map/filter/reduce. Key-value lookup with dynamic or non-string keys → Map. Need uniqueness or fast membership → Set. Attaching metadata to an object without leaking it → WeakMap. Raw bytes from a file, fetch, or canvas → TypedArray. Sending data over the wire → serialize to JSON. The wrong choice is almost always "reached for a plain object when a Map or Set was the right tool" — once I internalized that keyed collections exist, the code I wrote got noticeably shorter.
References
[1] Mozilla, "Indexed collections," MDN Web Docs, 2024. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections
[2] I. Kantor, "Arrays," The Modern JavaScript Tutorial, 2024. [Online]. Available: https://javascript.info/array
[3] Mozilla, "Keyed collections," MDN Web Docs, 2024. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections
[4] LogRocket, "ES6 keyed collections — Maps and sets," 2022. [Online]. Available: https://blog.logrocket.com/es6-keyed-collections-maps-and-sets/
[5] I. Kantor, "WeakMap and WeakSet," The Modern JavaScript Tutorial, 2024. [Online]. Available: https://javascript.info/weakmap-weakset
[6] Mozilla, "JavaScript typed arrays," MDN Web Docs, 2024. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
[7] Mozilla, "Working with JSON," MDN Web Docs, 2024. [Online]. Available: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
[8] Mozilla, "Standard built-in objects," MDN Web Docs, 2024. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
Knowledge check · Question 1 of 5
What's the fastest way to dedupe an array in modern JavaScript?
Comments
Leave a Comment
You must be signed in to comment
0 Comments
No comments yet. Be the first to comment!