Skip to Content
Language reference

Standard library

Use the same built-ins for collections, binary data, and asynchronous work on both targets.

Portable modules use ECMAScript globals directly. Standard operations have the same observable behavior in typed source and in compiled JavaScript dependencies. Native overloads also use the static type information in typed code. Primitive types describes this distinction for Math.sqrt.

Maps and sets

Map and Set iterate in insertion order. Object keys use identity. Numeric keys use ECMAScript's SameValueZero equality, so NaN matches another NaN and both signs of zero refer to the same key.

const names = new Map<number, string>()
names.set(NaN, "unknown")
names.set(-0, "origin")

names.get(NaN)  // "unknown"
names.get(+0)   // "origin"

WeakMap ties a value to the lifetime of its key. A value that refers back to its key can still be collected once both are otherwise unreachable. Programs cannot rely on a particular collection time.

Binary data

ArrayBuffer owns bytes. Typed arrays and DataView read and write the bytes of the buffer they reference. A second view observes writes made through the first.

const buffer = new ArrayBuffer(4)
const view = new DataView(buffer)
const bytes = new Uint8Array(buffer)

view.setUint16(0, 0x1234, true)
bytes[0]  // 0x34, the low byte in little-endian order

Promises

The executor passed to new Promise runs during construction. An async function starts immediately and executes up to its first suspension. Calling .then on a fulfilled promise queues a reaction. Awaiting a fulfilled promise also resumes in a queued job.

const order: string[] = []
const ready = Promise.resolve(1)

ready.then(() => {
  order.push("A")
  ready.then(() => order.push("C"))
})
ready.then(() => order.push("B"))

Once those jobs have run, order contains ["A", "B", "C"]. The second reaction was already queued when the first reaction enqueued the third. A host chooses how to wake its queue and preserves the order of jobs within an agent. ECMAScript Promise objects.

On this page