Quick reference

JavaScript reference

Syntax, built-ins, DOM and async patterns with runnable examples.

JavaScript is a single-threaded language with an event loop. Prefer const, keep functions small, handle errors where you can act on them, and remember that most DOM and network work is asynchronous. Every example below runs in the page console.

Read the full explanationJavaScript Foundations

Work through the guided lesson, then test yourself with a challenge.

Open course
308 entries

Arrays

array.at()

items.at(-1)

Reads an element by index and supports negative positions.

Open entry

array.concat()

a.concat(b)

Returns a new array with the inputs appended. Spread syntax is usually clearer.

Open entry

array.fill()

items.fill(value, start, end)

Overwrites a range with a value in place.

Open entry

array.findIndex()

items.findIndex(item => condition)

Returns the index of the first match, or -1.

Open entry

array.findLast()

items.findLast(item => condition)

Returns the last matching element, or undefined.

Open entry

array.flat()

items.flat(depth)

Flattens nested arrays by one level, or by the supplied depth.

Open entry

array.flatMap()

items.flatMap(item => list)

Maps and then flattens one level. Great for expanding one item into several.

Open entry

array.forEach()

items.forEach(fn)

Runs a callback for each element. It does not return a value and cannot be awaited meaningfully.

Open entry

Array.from()

Array.from(iterable, fn)

Creates an array from any iterable or array-like value, with an optional mapping function.

Open entry

array.includes()

items.includes(value)

Tests membership with SameValueZero, which finds NaN but cannot compare objects by value.

Open entry

array.indexOf()

items.indexOf(value)

Returns the first index of a value, or -1. Fails for NaN.

Open entry

Array.isArray()

Array.isArray(value)

The reliable way to test for an array. typeof returns "object".

Open entry

array.join()

items.join(separator)

Joins elements into a string. The default separator is a comma.

Open entry

array.keys() / values() / entries()

items.entries()

Iterators over indexes, values and index-value pairs.

Open entry

array.length

items.length

The number of elements. Assigning a smaller length truncates the array.

Open entry

array.pop()

items.pop()

Removes and returns the last element, or undefined when empty.

Open entry

array.push()

items.push(value)

Adds one or more values to the end and returns the new length.

Open entry

array.reverse()

items.reverse()

Reverses the array in place. Use toReversed() for a copy.

Open entry

array.shift()

items.shift()

Removes and returns the first element, or undefined when empty.

Open entry

array.slice()

items.slice(start, end)

Returns a shallow copy of part of an array without mutating the original.

Open entry

array.sort()

items.sort((a, b) => a - b)

Sorts in place and returns the same array. The default is lexicographic, which surprises with numbers.

Open entry

array.splice()

items.splice(start, deleteCount, …insert)

Removes, replaces or inserts elements in place and returns the removed items.

Open entry

array.toSorted()

items.toSorted((a, b) => a - b)

Returns a sorted copy without mutating the original.

Open entry

array.unshift()

items.unshift(value)

Adds one or more values to the start and returns the new length.

Open entry

filter

items.filter(item => condition)

Creates a new array with only the elements whose callback returns a truthy value.

Open entry

find

items.find(item => condition)

Returns the first matching element, or undefined.

Open entry

map

items.map(item => value)

Creates a new array by transforming every element. It never mutates the original.

Open entry

reduce

items.reduce((acc, item) => acc + item, 0)

Folds an array into a single value. Always pass an initial value when the type matters.

Open entry

some / every

items.some(fn) / items.every(fn)

Tests whether at least one or all elements match. Both short-circuit.

Open entry

Async JavaScript

AbortController

const c = new AbortController()

Cancels fetch requests and removable event listeners through its signal.

Open entry

async / await

async function name() { const value = await promise; }

An async function always returns a promise. await pauses it until another promise settles, then returns its value or throws its error.

Open entry

clearTimeout()

clearTimeout(id)

Cancels a pending timeout or interval. Clearing an already finished timer is safe.

Open entry

Event loop order

sync → microtask → task

Synchronous code runs first, then promise callbacks, then timers. Logging the order is the fastest way to remember it.

Open entry

fetch()

await fetch(url)

Starts an HTTP request and resolves with a Response. It rejects only on network failure, not on 404 or 500.

Open entry

Promise

new Promise((resolve, reject) => { … })

Represents a future value. Resolve with a value or reject with an Error.

Open entry

Promise.all()

Promise.all(tasks)

Waits for every promise. Resolves with all values, or rejects as soon as one rejects.

Open entry

Promise.allSettled()

Promise.allSettled(tasks)

Waits for every promise regardless of outcome and returns status and value or reason for each.

Open entry

Promise.any()

Promise.any(tasks)

Resolves with the first fulfilled promise and rejects only if every promise rejects.

Open entry

promise.catch()

promise.catch(onRejected)

Handles rejection. Put one catch at the end of a chain instead of a handler after every step.

Open entry

promise.finally()

promise.finally(fn)

Runs whether the promise settles or rejects, and passes the result through.

Open entry

Promise.race()

Promise.race(tasks)

Settles with the first promise to fulfil or reject. Useful for timeouts.

Open entry

promise.then()

promise.then(onFulfilled)

Runs when a promise fulfils. Return a value or another promise to chain further.

Open entry

queueMicrotask()

queueMicrotask(fn)

Schedules work after the current task but before the next render.

Open entry

response.json()

await response.json()

Reads and parses the response body as JSON. The body can be read only once.

Open entry

setInterval()

setInterval(fn, ms)

Repeats a function. Always keep the id so you can stop it.

Open entry

setTimeout()

setTimeout(fn, ms)

Runs a function once after a delay. The delay is a minimum, not a guarantee.

Open entry

try/catch with await

try { await task(); } catch (e) { … }

Await turns rejection into a thrown error, so the usual try/catch works.

Open entry

Collections, storage and utilities

bind / call / apply

fn.bind(thisArg)

Sets this explicitly. bind returns a new function; call and apply invoke immediately.

Open entry

Closure

outer variable captured by inner function

A function keeps access to variables from the scope where it was created, even after that scope returns.

Open entry

console methods

console.log / warn / error / table

Log values to the console. console.table is excellent for arrays of objects.

Open entry

crypto.randomUUID()

crypto.randomUUID()

Generates a cryptographically strong UUID. Available in secure contexts.

Open entry

Dynamic import()

await import("./module.js")

Loads a module at runtime and returns a promise. Use it for code splitting.

Open entry

Generator function

function* name() { yield value; }

Produces a sequence lazily. Each yield pauses the function until the next value is requested.

Open entry

Hoisting

declarations move to the top

Function declarations are hoisted with their body; let and const are hoisted but uninitialised until the declaration runs.

Open entry

Intl.NumberFormat

new Intl.NumberFormat(locale, options)

Locale-aware number, currency and percentage formatting.

Open entry

JSON.parse()

JSON.parse(text)

Parses JSON text. Wrap it in try/catch because malformed input throws.

Open entry

JSON.stringify()

JSON.stringify(value)

Serialises a value to JSON. Functions and undefined disappear from objects.

Open entry

localStorage

localStorage.setItem(key, value)

Stores strings per origin with no expiry. Serialise objects with JSON.

Open entry

Map object

new Map([[key, value]])

A keyed collection that accepts any key type and remembers insertion order.

Open entry

Module export

export function name() {}

Exports a value from a module. Modules are strict and scoped to their own file.

Open entry

Module import

import { name } from "./module.js"

Imports a named or default export. Paths need the file extension in browsers.

Open entry

sessionStorage

sessionStorage.setItem(key, value)

Like localStorage but cleared when the tab closes.

Open entry

Set

new Set(values)

A collection of unique values with fast membership tests. Iteration keeps insertion order.

Open entry

Symbol

Symbol("description")

A unique, non-string property key. Use it to avoid accidental collisions.

Open entry

this binding

obj.method()

Inside a normal function, this depends on how it is called. Arrow functions inherit this from their enclosing scope.

Open entry

URL

new URL(path, base)

Parses and builds URLs. Use it instead of string concatenation for query parameters.

Open entry

URLSearchParams

new URLSearchParams(query)

Reads and writes query strings safely, including encoding.

Open entry

WeakMap / WeakSet

new WeakMap()

Collections with weak keys that can be garbage-collected. They are not iterable and are used for private metadata.

Open entry

Dates and internationalisation

DOM and events

addEventListener

el.addEventListener(type, handler)

Attaches an event handler. Pass { once: true } for one-shot listeners or an AbortSignal to remove later.

Open entry

append

parent.append(child)

Inserts nodes or strings at the end of an element. Unlike appendChild it accepts several values.

Open entry

classList

el.classList.add("active")

Manages classes without touching the class attribute string. Supports add, remove, toggle and contains.

Open entry

closest

el.closest(selector)

Walks up the ancestor chain and returns the nearest matching element. Ideal for event delegation.

Open entry

createElement

document.createElement(tag)

Creates a detached element that you can configure and then insert.

Open entry

dataset

el.dataset.id

Reads data-* attributes as camel-cased properties.

Open entry

element.style

el.style.color = "red"

Sets inline styles. Prefer classes because inline styles win specificity and are hard to theme.

Open entry

Event delegation

list.addEventListener(type, handler)

Attach one listener to a container and read event.target to handle clicks on its children. Works for dynamic content.

Open entry

Event object

event.target

The event passed to a handler. target is where it started; currentTarget is the element with the listener.

Open entry

event.preventDefault()

event.preventDefault()

Cancels the browser’s default action, such as following a link or submitting a form.

Open entry

focus

el.focus()

Moves keyboard focus to an element. Use it deliberately, for example when opening a dialog.

Open entry

innerHTML

el.innerHTML = "…"

Reads or writes HTML markup. Dangerous with untrusted input because scripts and event handlers can execute.

Open entry

querySelector

document.querySelector(selector)

Returns the first element matching a CSS selector, or null.

Open entry

querySelectorAll

document.querySelectorAll(selector)

Returns a static NodeList of all matches. Convert with Array.from to use array methods.

Open entry

removeEventListener

el.removeEventListener(type, handler)

Removes a handler. It must be the same function reference that was added.

Open entry

setAttribute

el.setAttribute(name, value)

Sets any attribute, including ARIA attributes. Use the property when one exists.

Open entry

textContent

el.textContent = "…"

Reads or writes text safely. The browser escapes it, so it cannot inject markup.

Open entry

DOM APIs

document.createDocumentFragment()

document.createDocumentFragment()

A lightweight container for building DOM subtrees before a single insertion.

Open entry

document.getElementById()

document.getElementById(id)

Finds one element by its id. Prefer querySelector for consistency.

Open entry

element.appendChild()

parent.appendChild(child)

Adds a node as the last child and returns it. append() is the modern multi-node alternative.

Open entry

element.cloneNode()

el.cloneNode(deep)

Copies an element. Pass true to include descendants.

Open entry

element.getBoundingClientRect()

el.getBoundingClientRect()

Returns the element’s size and position relative to the viewport.

Open entry

element.insertAdjacentHTML()

el.insertAdjacentHTML(position, html)

Inserts HTML at beforebegin, afterbegin, beforeend or afterend. Dangerous with untrusted input.

Open entry

element.matches()

el.matches(selector)

Tests whether an element would be selected by a CSS selector.

Open entry

element.remove()

el.remove()

Removes the element from the DOM.

Open entry

element.replaceChildren()

el.replaceChildren(…nodes)

Replaces all children with a new set of nodes in one operation.

Open entry

element.scrollIntoView()

el.scrollIntoView(options)

Scrolls an element into view, optionally smoothly and aligned to start or center.

Open entry

element.toggleAttribute()

el.toggleAttribute(name, force)

Adds or removes a boolean attribute and returns the new state.

Open entry

history.pushState()

history.pushState(state, "", url)

Changes the URL without a reload. Listen for popstate to support back and forward.

Open entry

IntersectionObserver

new IntersectionObserver(callback)

Reports when elements enter or leave the viewport. Ideal for lazy loading.

Open entry

location.assign()

location.assign(url)

Navigates to a URL, adding a history entry. replace() navigates without one.

Open entry

matchMedia()

window.matchMedia(query)

Tests a CSS media query from JavaScript and lets you subscribe to changes.

Open entry

MutationObserver

new MutationObserver(callback)

Watches DOM changes and batches them into callback records.

Open entry

requestAnimationFrame()

requestAnimationFrame(fn)

Schedules a callback before the next repaint. The basis of smooth animation.

Open entry

ResizeObserver

new ResizeObserver(callback)

Reports size changes of an element, not just the window.

Open entry

Error types

Internationalisation

Language basics

Arrow function

(a, b) => a + b

A concise function expression. It does not bind its own this or arguments.

Open entry

Chained comparison

a >= min && a <= max

JavaScript has no chained comparison. Combine two comparisons explicitly.

Open entry

Comma operator

a = (b++, c)

Evaluates each expression and returns the last value. Rarely worth the confusion.

Open entry

Default parameter

function f(a = 1) { … }

Supplies a value when the argument is undefined.

Open entry

destructuring

const [a, b] = list; const { id } = user;

Unpacks arrays into positional names and objects into property names. Use a colon to rename and = for defaults.

Open entry

for…in

for (const key in object) { … }

Iterates enumerable property names, including inherited ones. Use Object.keys for own keys only.

Open entry

for…of

for (const item of iterable) { … }

Iterates values of arrays, strings, maps and sets. Prefer it over for…in for data.

Open entry

Function declaration

function name(args) { … }

A named function hoisted to the top of its scope. Good for top-level utilities.

Open entry

if / else

if (condition) { … } else { … }

Runs a block when a condition is truthy, with optional else branches.

Open entry

instanceof

value instanceof Class

Tests whether an object was created by a constructor and is therefore on its prototype chain.

Open entry

let / const

let count = 0; const name = "Ada";

Block-scoped declarations. Use const by default and let only when reassigning. Neither is hoisted to a usable value.

Open entry

Logical assignment

x ??= 1; x ||= 2; x &&= 3;

Assigns only when the operator’s condition passes. Useful for filling defaults.

Open entry

Nullish coalescing

value ?? fallback

Uses the fallback only when the left side is null or undefined, unlike || which also replaces 0 and "".

Open entry

Optional catch binding

try { … } catch { … }

Omits the error variable when the handler does not need it.

Open entry

Optional chaining

user?.address?.city

Stops evaluating and returns undefined when the value before ?. is null or undefined.

Open entry

Rest in objects

const { a, ...rest } = obj;

Copies an object while omitting named keys. Handy for updating immutable state.

Open entry

Rest parameter

function f(...items) { … }

Collects the remaining arguments into a real array.

Open entry

Spread syntax

[...a, ...b]

Expands an iterable into a new array, object or argument list without mutating the original.

Open entry

Strict equality

a === b

Compares without type coercion. Use it instead of == so 0, "", false and null stay distinct.

Open entry

Strict mode

"use strict"

Opts into stricter parsing and error rules. Modules are strict by default.

Open entry

Switch statement

switch (value) { case …: break; }

Branches on strict equality. Every case needs a break or a deliberate fallthrough comment.

Open entry

Template literal

`Hello, ${name}`

A string with interpolation and multi-line support. Use backticks, not quotes.

Open entry

Ternary operator

condition ? a : b

Chooses between two values. Keep it short; a full if statement is clearer for side effects.

Open entry

throw

throw new Error("message")

Stops execution and raises an exception. Throw Error objects, not strings.

Open entry

try / catch

try { … } catch (error) { … } finally { … }

Handles thrown errors. finally always runs, including when an error is thrown.

Open entry

typeof

typeof value

Returns a string describing the type. Arrays and null need their own checks.

Open entry

var

var x = 1;

Function-scoped and hoisted. Kept for legacy code; use let or const instead.

Open entry

Map and Set methods

map.clear()

map.clear()

Removes every entry.

Open entry

map.delete()

map.delete(key)

Removes a key and returns whether it existed.

Open entry

map.forEach()

map.forEach((value, key) => {})

Iterates entries in insertion order.

Open entry

map.get()

map.get(key)

Reads a value by key, or undefined when the key is absent.

Open entry

map.has()

map.has(key)

Tests whether a key exists, including keys mapped to undefined.

Open entry

map.keys() / values() / entries()

map.entries()

Iterators over keys, values or [key, value] pairs.

Open entry

map.set()

map.set(key, value)

Adds or replaces a value and returns the map for chaining.

Open entry

map.size

map.size

The number of entries. It is a property, not a method.

Open entry

set.clear()

set.clear()

Removes every value.

Open entry

set.delete()

set.delete(value)

Removes a value and returns whether it existed.

Open entry

set.difference()

a.difference(b)

Returns values in the first set that are not in the second.

Open entry

set.forEach()

set.forEach(value => {})

Iterates values in insertion order.

Open entry

set.has()

set.has(value)

Tests membership in constant time on average.

Open entry

set.intersection()

a.intersection(b)

Returns a new set with values present in both sets.

Open entry

set.isDisjointFrom()

a.isDisjointFrom(b)

Tests whether the sets share no values.

Open entry

set.isSubsetOf()

a.isSubsetOf(b)

Tests whether every value in a is also in b.

Open entry

set.isSupersetOf()

a.isSupersetOf(b)

Tests whether a contains every value in b.

Open entry

set.size

set.size

The number of values.

Open entry

set.symmetricDifference()

a.symmetricDifference(b)

Returns values that appear in exactly one set.

Open entry

set.union()

a.union(b)

Returns a new set with values from both sets.

Open entry

More array and object methods

array.copyWithin()

items.copyWithin(target, start, end)

Copies a slice to another position inside the same array.

Open entry

array.lastIndexOf()

items.lastIndexOf(value)

Returns the last index of a value, or -1.

Open entry

array.reduceRight()

items.reduceRight(fn, initial)

Like reduce but processes from the end to the start.

Open entry

array.toReversed()

items.toReversed()

Returns a reversed copy without mutating the original array.

Open entry

array.toSpliced()

items.toSpliced(start, deleteCount, …items)

Returns a spliced copy instead of mutating the original.

Open entry

array.with()

items.with(index, value)

Returns a copy with one index replaced. Negative indexes count from the end.

Open entry

Map.groupBy()

Map.groupBy(items, fn)

Groups items into a Map, so keys can be any value.

Open entry

Object.create()

Object.create(proto, descriptors)

Creates an object with a chosen prototype and optional property descriptors.

Open entry

Object.defineProperty()

Object.defineProperty(obj, key, descriptor)

Defines a property with precise control over value, writability, enumerability and getters.

Open entry

Object.fromEntries() with map

Object.fromEntries(map)

Turns a Map or entry list into a plain object.

Open entry

Object.getOwnPropertyDescriptor()

Object.getOwnPropertyDescriptor(obj, key)

Reads the full descriptor of one property.

Open entry

Object.getOwnPropertyNames()

Object.getOwnPropertyNames(obj)

Lists own string keys, including non-enumerable ones.

Open entry

Object.getPrototypeOf()

Object.getPrototypeOf(obj)

Returns the prototype of an object.

Open entry

Object.groupBy()

Object.groupBy(items, fn)

Groups items into an object keyed by the callback result.

Open entry

Object.is()

Object.is(a, b)

Compares values like === but treats NaN as equal and +0 as different from -0.

Open entry

Object.preventExtensions()

Object.preventExtensions(obj)

Prevents new properties but allows editing and deleting existing ones.

Open entry

Object.seal()

Object.seal(obj)

Prevents adding or removing properties while still allowing values to change.

Open entry

Object.setPrototypeOf()

Object.setPrototypeOf(obj, proto)

Replaces an object’s prototype. Slow; prefer Object.create for new objects.

Open entry

More dates

Numbers and Math

BigInt

9007199254740993n

An integer type for values beyond Number.MAX_SAFE_INTEGER. BigInt and Number cannot be mixed in arithmetic.

Open entry

BigInt.asIntN()

BigInt.asIntN(bits, value)

Wraps a BigInt into a signed integer of the given bit width.

Open entry

BigInt.asUintN()

BigInt.asUintN(bits, value)

Wraps a BigInt into an unsigned integer of the given bit width.

Open entry

Exponentiation

base ** exponent

Raises a number to a power. It has higher precedence than multiplication.

Open entry

Math.abs()

Math.abs(value)

Returns the absolute value.

Open entry

Math.atan2()

Math.atan2(y, x)

Returns the angle of a vector, handling all quadrants.

Open entry

Math.cbrt()

Math.cbrt(value)

Returns the cube root.

Open entry

Math.exp()

Math.exp(value)

Returns e raised to a power.

Open entry

Math.floor() / ceil()

Math.floor(value)

Rounds down or up to the nearest integer.

Open entry

Math.fround()

Math.fround(value)

Rounds a number to the nearest 32-bit float. Useful when interoperating with Float32Array.

Open entry

Math.hypot()

Math.hypot(...values)

Returns the square root of the sum of squares, without intermediate overflow.

Open entry

Math.log10()

Math.log10(value)

Returns the base-10 logarithm.

Open entry

Math.log2()

Math.log2(value)

Returns the base-2 logarithm.

Open entry

Math.min() / max()

Math.min(...values)

Returns the smallest or largest of the arguments.

Open entry

Math.PI / Math.E

Math.PI, Math.E

The constants pi and Euler’s number.

Open entry

Math.pow()

Math.pow(base, exponent)

Raises a number to a power. The ** operator is the modern equivalent.

Open entry

Math.random()

Math.random()

Returns a float from 0 up to but not including 1. Not cryptographically secure.

Open entry

Math.round()

Math.round(value)

Rounds to the nearest integer. Ties go towards positive infinity.

Open entry

Math.sign()

Math.sign(value)

Returns -1, 0 or 1 depending on the sign.

Open entry

Math.sin() / cos() / tan()

Math.sin(radians)

Trigonometric functions that take radians, not degrees.

Open entry

Math.sqrt()

Math.sqrt(value)

Returns the square root.

Open entry

Math.trunc()

Math.trunc(value)

Removes the fractional part without rounding.

Open entry

Number.EPSILON

Number.EPSILON

The smallest difference between 1 and the next representable number. Useful for float comparisons.

Open entry

Number.isFinite()

Number.isFinite(value)

True for finite numbers and false for Infinity, NaN and numeric strings.

Open entry

Number.isInteger()

Number.isInteger(value)

True only for finite whole numbers, not for numeric strings.

Open entry

Number.isNaN()

Number.isNaN(value)

True only when the value is the NaN number. The global isNaN coerces strings first.

Open entry

Number.isSafeInteger()

Number.isSafeInteger(value)

True when an integer can be represented exactly without precision loss.

Open entry

Number.MAX_SAFE_INTEGER

Number.MAX_SAFE_INTEGER

The largest integer that can be represented exactly in a double.

Open entry

Number.parseFloat()

Number.parseFloat(text)

Parses a decimal number from the start of a string.

Open entry

Number.parseInt()

Number.parseInt(text, radix)

Parses an integer with an explicit radix.

Open entry

Number.prototype.toExponential()

value.toExponential(digits)

Formats a number in exponential notation.

Open entry

Number.prototype.toPrecision()

value.toPrecision(digits)

Formats a number to a number of significant digits.

Open entry

Number()

Number(value)

Converts a value to a number. Empty strings become 0, which is often a trap.

Open entry

parseFloat()

parseFloat(value)

Parses a floating-point number from the start of a string.

Open entry

parseInt()

parseInt(value, 10)

Parses an integer from the start of a string. Always pass radix 10.

Open entry

toFixed()

value.toFixed(2)

Formats a number with fixed decimal places and returns a string.

Open entry

toLocaleString()

value.toLocaleString(locale)

Formats numbers, currency and percentages for a locale.

Open entry

Objects

Computed property

{ [key]: value }

Uses an expression as the property name.

Open entry

delete operator

delete object.key

Removes a property. Deleting array elements leaves holes; use splice or filter instead.

Open entry

for…of Object.entries()

for (const [k, v] of Object.entries(obj))

The clearest way to iterate own object properties with keys and values.

Open entry

in operator

"key" in object

Tests whether a property exists in an object or its prototype chain.

Open entry

Object.assign()

Object.assign({}, a, b)

Copies own enumerable properties into a target. Later sources win.

Open entry

Object.entries()

Object.entries(object)

Returns an array of [key, value] pairs.

Open entry

Object.freeze()

Object.freeze(object)

Prevents adding, removing or changing properties. It is shallow.

Open entry

Object.fromEntries()

Object.fromEntries(entries)

Builds an object from key-value pairs, the inverse of Object.entries.

Open entry

Object.hasOwn()

Object.hasOwn(object, key)

Safely checks for an own property, even when the object has a null prototype.

Open entry

Object.keys()

Object.keys(object)

Returns an array of own enumerable string keys.

Open entry

Object.values()

Object.values(object)

Returns an array of own enumerable values.

Open entry

Optional property access

obj?.key

Reads a property only when the object exists.

Open entry

Property shorthand

{ name }

When the variable name matches the key, write it once.

Open entry

structuredClone()

structuredClone(value)

Deep-copies objects, arrays, maps, sets and dates. Functions and DOM nodes cannot be cloned.

Open entry

Other globals and patterns

Currying

fn(a)(b)

Turns a multi-argument function into a chain of single-argument functions.

Open entry

Debounce

debounce(fn, ms)

Delays a function until calls stop, which is ideal for search inputs and resize handlers.

Open entry

decodeURIComponent()

decodeURIComponent(text)

Decodes an encoded URL component. Wrap it in try/catch for malformed input.

Open entry

encodeURI()

encodeURI(url)

Encodes a complete URL while leaving reserved characters such as / and ? intact.

Open entry

encodeURIComponent()

encodeURIComponent(text)

Encodes a string for use inside a URL component such as a query value.

Open entry

global isFinite()

isFinite(value)

Coerces the value before testing. Prefer Number.isFinite.

Open entry

global isNaN()

isNaN(value)

Coerces the value to a number before testing. Prefer Number.isNaN.

Open entry

Proxy

new Proxy(target, handler)

Wraps an object to intercept reads, writes and other operations.

Open entry

Reflect.get()

Reflect.get(target, key)

Performs the default property read, useful inside Proxy traps.

Open entry

Reflect.has()

Reflect.has(target, key)

The functional form of the in operator.

Open entry

Tagged template

tag`text ${value}`

A function receives the template strings and interpolated values separately, which enables safe HTML and CSS helpers.

Open entry

Throttle

throttle(fn, ms)

Runs a function at most once per interval, which is ideal for scroll handlers.

Open entry

void operator

void expression

Evaluates an expression and returns undefined. Sometimes used to trigger a function without a return value.

Open entry

Regular expressions

Strings

str.at()

str.at(-1)

Returns the character at an index and supports negative positions.

Open entry

str.charAt()

str.charAt(index)

Returns the character at an index, or an empty string when out of range.

Open entry

str.includes()

str.includes(term)

Tests whether a substring exists. Case-sensitive unless you normalise both sides.

Open entry

str.indexOf()

str.indexOf(term)

Returns the first position of a substring, or -1. Use includes when you only need a boolean.

Open entry

str.localeCompare()

a.localeCompare(b)

Compares strings using language-aware rules. Pass a locale for deterministic output.

Open entry

str.match()

str.match(regexp)

Returns the matches of a regular expression, including groups.

Open entry

str.normalize()

str.normalize("NFC")

Normalises Unicode so visually identical characters compare equal.

Open entry

str.padStart with numbers

String(n).padStart(2, "0")

Format a number with leading zeros for timers and dates.

Open entry

str.padStart() / padEnd()

str.padStart(length, pad)

Pads a string to a length. Useful for aligned numbers and codes.

Open entry

str.repeat()

str.repeat(count)

Repeats a string. The count must be a non-negative integer.

Open entry

str.replace()

str.replace(pattern, replacement)

Replaces the first match of a string or regular expression.

Open entry

str.replaceAll()

str.replaceAll(term, replacement)

Replaces every match. With a regexp, the global flag is still required.

Open entry

str.search()

str.search(regexp)

Returns the index of the first match, or -1.

Open entry

str.slice()

str.slice(start, end)

Extracts a substring. Negative indexes count from the end.

Open entry

str.split()

str.split(separator)

Splits a string into an array. Use an empty separator for characters or a regexp for patterns.

Open entry

str.startsWith() / endsWith()

str.startsWith(prefix)

Tests the beginning or end of a string. An optional position changes where the test starts.

Open entry

str.substring()

str.substring(start, end)

Like slice but swaps arguments when start is greater than end and does not accept negatives.

Open entry

str.toUpperCase() / toLowerCase()

str.toUpperCase()

Changes case. Be careful where case changes the meaning of identifiers.

Open entry

str.trim()

str.trim()

Removes whitespace from both ends. trimStart and trimEnd remove one side.

Open entry

String length

"text".length

Counts UTF-16 code units. Emoji outside the basic plane count as two.

Open entry

String()

String(value)

Converts a value to a string. Handles objects, null and undefined predictably.

Open entry

Typed arrays and encoding

Keep going

Turn the reference into recall.

Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.