Pseudo Random Nonsense Generator

Arrays and Sets in Javascript

· note

Array, Object, Set, Map

what are they?

Array Object Set Map
a “list” of stuff key value pairs an unique Array an ordered Object
iterable not iterable iterable iterable
ordered not ordered ordered (insertion order) ordered (insertion order)
not unique unique unique unique

also

WeakSet WeakMap
garbage-collection friendly Set garbage-collection friendly Map
not iterable not iterable
not ordered ordered (insertion order)
unique unique
- 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

Name Insert Access Search Delete Comments
Array O(n) O(1) O(n) O(n) Insertion to the end is O(1). Details here.
HashMap O(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 you need to iterate something
  • when you don’t

When to use Objects

When to use Sets

  • set union / intersection / difference
  • is an object in set?
  • iterate over set, knowing everything is unique
  • turn arrays into unique sets (like a normal use case in python)

When to use WeakSets

When to use Maps

  • for fast searching and looking up data. ref
  • for adding items to and removing items from the map. ref

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