Arrays and Sets in Javascript

Array, Object, Set, Map

what are they?

ArrayObjectSetMap
a "list" of stuffkey value pairsan unique Arrayan ordered Object
iterablenot iterableiterableiterable
orderednot orderedordered (insertion order)ordered (insertion order)
not uniqueuniqueuniqueunique

also

WeakSetWeakMap
garbage-collection friendly Setgarbage-collection friendly Map
not iterablenot iterable
not orderedordered (insertion order)
uniqueunique
-key in WeakMap must by type Object (not null)

speed concerns

*a collection is a "list" of stuff, in the english sense of the word. an Array of names is a collection of names.

cheatsheet ref

NameInsertAccessSearchDeleteComments
ArrayO(n)O(1)O(n)O(n)Insertion to the end is O(1). Details here.
HashMapO(1)O(1)O(1)O(1)Rehashing might affect insertion time. Details here.
Map (using Binary Search Tree)O(log(n))-O(log(n))O(log(n))Implemented using Binary Search Tree
Set (using HashMap)O(1)-O(1)O(1)Set using a HashMap implementation. Details here.
Set (using list)O(n)-O(n)O(n)Implemented using Binary Search Tree
Set (using Binary Search Tree)O(log(n))-O(log(n))O(log(n))Implemented using Binary Search Tree

When to use Arrays

When to use Objects

When to use Sets

When to use WeakSets

When to use Maps

When to use WeakMaps

// delete private data when user is gone
export let USER_1 = { name: 'John' }

const metadata = new WeakMap()
  .set(USER_1, {
    currentLocation: '...',
    personallyIdentifiableInformation: '...',
  })
  .set(/*...*/)

// somewhere down the line...

// user logout
USER_1 = null

note from v8

from v8.dev:

JavaScript objects mostly behave like dictionaries, with string keys and arbitrary objects as values. The specification does however treat integer-indexed properties and other properties differently during iteration. Other than that, the different properties behave mostly the same, independent of whether they are integer indexed or not.

further reading