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.
Work through the guided lesson, then test yourself with a challenge.
Open courseArrays
array.at()
items.at(-1)Reads an element by index and supports negative positions.
Open entryarray.concat()
a.concat(b)Returns a new array with the inputs appended. Spread syntax is usually clearer.
Open entryarray.fill()
items.fill(value, start, end)Overwrites a range with a value in place.
Open entryarray.findIndex()
items.findIndex(item => condition)Returns the index of the first match, or -1.
Open entryarray.findLast()
items.findLast(item => condition)Returns the last matching element, or undefined.
Open entryarray.flat()
items.flat(depth)Flattens nested arrays by one level, or by the supplied depth.
Open entryarray.flatMap()
items.flatMap(item => list)Maps and then flattens one level. Great for expanding one item into several.
Open entryarray.forEach()
items.forEach(fn)Runs a callback for each element. It does not return a value and cannot be awaited meaningfully.
Open entryArray.from()
Array.from(iterable, fn)Creates an array from any iterable or array-like value, with an optional mapping function.
Open entryarray.includes()
items.includes(value)Tests membership with SameValueZero, which finds NaN but cannot compare objects by value.
Open entryarray.indexOf()
items.indexOf(value)Returns the first index of a value, or -1. Fails for NaN.
Open entryArray.isArray()
Array.isArray(value)The reliable way to test for an array. typeof returns "object".
Open entryarray.join()
items.join(separator)Joins elements into a string. The default separator is a comma.
Open entryarray.keys() / values() / entries()
items.entries()Iterators over indexes, values and index-value pairs.
Open entryarray.length
items.lengthThe number of elements. Assigning a smaller length truncates the array.
Open entryarray.pop()
items.pop()Removes and returns the last element, or undefined when empty.
Open entryarray.push()
items.push(value)Adds one or more values to the end and returns the new length.
Open entryarray.reverse()
items.reverse()Reverses the array in place. Use toReversed() for a copy.
Open entryarray.shift()
items.shift()Removes and returns the first element, or undefined when empty.
Open entryarray.slice()
items.slice(start, end)Returns a shallow copy of part of an array without mutating the original.
Open entryarray.sort()
items.sort((a, b) => a - b)Sorts in place and returns the same array. The default is lexicographic, which surprises with numbers.
Open entryarray.splice()
items.splice(start, deleteCount, …insert)Removes, replaces or inserts elements in place and returns the removed items.
Open entryarray.toSorted()
items.toSorted((a, b) => a - b)Returns a sorted copy without mutating the original.
Open entryarray.unshift()
items.unshift(value)Adds one or more values to the start and returns the new length.
Open entryfilter
items.filter(item => condition)Creates a new array with only the elements whose callback returns a truthy value.
Open entryfind
items.find(item => condition)Returns the first matching element, or undefined.
Open entrymap
items.map(item => value)Creates a new array by transforming every element. It never mutates the original.
Open entryreduce
items.reduce((acc, item) => acc + item, 0)Folds an array into a single value. Always pass an initial value when the type matters.
Open entrysome / every
items.some(fn) / items.every(fn)Tests whether at least one or all elements match. Both short-circuit.
Open entryAsync JavaScript
AbortController
const c = new AbortController()Cancels fetch requests and removable event listeners through its signal.
Open entryasync / 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 entryclearTimeout()
clearTimeout(id)Cancels a pending timeout or interval. Clearing an already finished timer is safe.
Open entryEvent loop order
sync → microtask → taskSynchronous code runs first, then promise callbacks, then timers. Logging the order is the fastest way to remember it.
Open entryfetch()
await fetch(url)Starts an HTTP request and resolves with a Response. It rejects only on network failure, not on 404 or 500.
Open entryPromise
new Promise((resolve, reject) => { … })Represents a future value. Resolve with a value or reject with an Error.
Open entryPromise.all()
Promise.all(tasks)Waits for every promise. Resolves with all values, or rejects as soon as one rejects.
Open entryPromise.allSettled()
Promise.allSettled(tasks)Waits for every promise regardless of outcome and returns status and value or reason for each.
Open entryPromise.any()
Promise.any(tasks)Resolves with the first fulfilled promise and rejects only if every promise rejects.
Open entrypromise.catch()
promise.catch(onRejected)Handles rejection. Put one catch at the end of a chain instead of a handler after every step.
Open entrypromise.finally()
promise.finally(fn)Runs whether the promise settles or rejects, and passes the result through.
Open entryPromise.race()
Promise.race(tasks)Settles with the first promise to fulfil or reject. Useful for timeouts.
Open entrypromise.then()
promise.then(onFulfilled)Runs when a promise fulfils. Return a value or another promise to chain further.
Open entryqueueMicrotask()
queueMicrotask(fn)Schedules work after the current task but before the next render.
Open entryresponse.json()
await response.json()Reads and parses the response body as JSON. The body can be read only once.
Open entrysetInterval()
setInterval(fn, ms)Repeats a function. Always keep the id so you can stop it.
Open entrysetTimeout()
setTimeout(fn, ms)Runs a function once after a delay. The delay is a minimum, not a guarantee.
Open entrytry/catch with await
try { await task(); } catch (e) { … }Await turns rejection into a thrown error, so the usual try/catch works.
Open entryCollections, storage and utilities
bind / call / apply
fn.bind(thisArg)Sets this explicitly. bind returns a new function; call and apply invoke immediately.
Open entryClosure
outer variable captured by inner functionA function keeps access to variables from the scope where it was created, even after that scope returns.
Open entryconsole methods
console.log / warn / error / tableLog values to the console. console.table is excellent for arrays of objects.
Open entrycrypto.randomUUID()
crypto.randomUUID()Generates a cryptographically strong UUID. Available in secure contexts.
Open entryDynamic import()
await import("./module.js")Loads a module at runtime and returns a promise. Use it for code splitting.
Open entryGenerator function
function* name() { yield value; }Produces a sequence lazily. Each yield pauses the function until the next value is requested.
Open entryHoisting
declarations move to the topFunction declarations are hoisted with their body; let and const are hoisted but uninitialised until the declaration runs.
Open entryIntl.NumberFormat
new Intl.NumberFormat(locale, options)Locale-aware number, currency and percentage formatting.
Open entryJSON.parse()
JSON.parse(text)Parses JSON text. Wrap it in try/catch because malformed input throws.
Open entryJSON.stringify()
JSON.stringify(value)Serialises a value to JSON. Functions and undefined disappear from objects.
Open entrylocalStorage
localStorage.setItem(key, value)Stores strings per origin with no expiry. Serialise objects with JSON.
Open entryMap object
new Map([[key, value]])A keyed collection that accepts any key type and remembers insertion order.
Open entryModule export
export function name() {}Exports a value from a module. Modules are strict and scoped to their own file.
Open entryModule import
import { name } from "./module.js"Imports a named or default export. Paths need the file extension in browsers.
Open entrysessionStorage
sessionStorage.setItem(key, value)Like localStorage but cleared when the tab closes.
Open entrySet
new Set(values)A collection of unique values with fast membership tests. Iteration keeps insertion order.
Open entrySymbol
Symbol("description")A unique, non-string property key. Use it to avoid accidental collisions.
Open entrythis binding
obj.method()Inside a normal function, this depends on how it is called. Arrow functions inherit this from their enclosing scope.
Open entryURL
new URL(path, base)Parses and builds URLs. Use it instead of string concatenation for query parameters.
Open entryURLSearchParams
new URLSearchParams(query)Reads and writes query strings safely, including encoding.
Open entryWeakMap / WeakSet
new WeakMap()Collections with weak keys that can be garbage-collected. They are not iterable and are used for private metadata.
Open entryDates and internationalisation
Date arithmetic
date.getTime() + msDates compare and add through millisecond timestamps. Mutating methods such as setDate exist too.
Open entrydate.getFullYear()
date.getFullYear()Reads the local year. getMonth is zero-based, so January is 0.
Open entryDate.now()
Date.now()The current Unix timestamp in milliseconds. Useful for measuring elapsed time.
Open entrydate.toISOString()
date.toISOString()Formats the date as UTC ISO 8601. This is the format to store and transmit.
Open entrydate.toLocaleDateString()
date.toLocaleDateString(locale)Formats a date for a locale. Pass options to control the parts shown.
Open entryIntl.DateTimeFormat
new Intl.DateTimeFormat(locale, options)A reusable, locale-aware date formatter. Create it once and call format many times.
Open entrynew Date()
new Date()Creates a date for the current moment or from an ISO string or timestamp.
Open entryDOM 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 entryappend
parent.append(child)Inserts nodes or strings at the end of an element. Unlike appendChild it accepts several values.
Open entryclassList
el.classList.add("active")Manages classes without touching the class attribute string. Supports add, remove, toggle and contains.
Open entryclosest
el.closest(selector)Walks up the ancestor chain and returns the nearest matching element. Ideal for event delegation.
Open entrycreateElement
document.createElement(tag)Creates a detached element that you can configure and then insert.
Open entrydataset
el.dataset.idReads data-* attributes as camel-cased properties.
Open entryelement.style
el.style.color = "red"Sets inline styles. Prefer classes because inline styles win specificity and are hard to theme.
Open entryEvent 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 entryEvent object
event.targetThe event passed to a handler. target is where it started; currentTarget is the element with the listener.
Open entryevent.preventDefault()
event.preventDefault()Cancels the browser’s default action, such as following a link or submitting a form.
Open entryfocus
el.focus()Moves keyboard focus to an element. Use it deliberately, for example when opening a dialog.
Open entryinnerHTML
el.innerHTML = "…"Reads or writes HTML markup. Dangerous with untrusted input because scripts and event handlers can execute.
Open entryquerySelector
document.querySelector(selector)Returns the first element matching a CSS selector, or null.
Open entryquerySelectorAll
document.querySelectorAll(selector)Returns a static NodeList of all matches. Convert with Array.from to use array methods.
Open entryremoveEventListener
el.removeEventListener(type, handler)Removes a handler. It must be the same function reference that was added.
Open entrysetAttribute
el.setAttribute(name, value)Sets any attribute, including ARIA attributes. Use the property when one exists.
Open entrytextContent
el.textContent = "…"Reads or writes text safely. The browser escapes it, so it cannot inject markup.
Open entryDOM APIs
document.createDocumentFragment()
document.createDocumentFragment()A lightweight container for building DOM subtrees before a single insertion.
Open entrydocument.getElementById()
document.getElementById(id)Finds one element by its id. Prefer querySelector for consistency.
Open entryelement.appendChild()
parent.appendChild(child)Adds a node as the last child and returns it. append() is the modern multi-node alternative.
Open entryelement.cloneNode()
el.cloneNode(deep)Copies an element. Pass true to include descendants.
Open entryelement.getBoundingClientRect()
el.getBoundingClientRect()Returns the element’s size and position relative to the viewport.
Open entryelement.insertAdjacentHTML()
el.insertAdjacentHTML(position, html)Inserts HTML at beforebegin, afterbegin, beforeend or afterend. Dangerous with untrusted input.
Open entryelement.matches()
el.matches(selector)Tests whether an element would be selected by a CSS selector.
Open entryelement.remove()
el.remove()Removes the element from the DOM.
Open entryelement.replaceChildren()
el.replaceChildren(…nodes)Replaces all children with a new set of nodes in one operation.
Open entryelement.scrollIntoView()
el.scrollIntoView(options)Scrolls an element into view, optionally smoothly and aligned to start or center.
Open entryelement.toggleAttribute()
el.toggleAttribute(name, force)Adds or removes a boolean attribute and returns the new state.
Open entryhistory.pushState()
history.pushState(state, "", url)Changes the URL without a reload. Listen for popstate to support back and forward.
Open entryIntersectionObserver
new IntersectionObserver(callback)Reports when elements enter or leave the viewport. Ideal for lazy loading.
Open entrylocation.assign()
location.assign(url)Navigates to a URL, adding a history entry. replace() navigates without one.
Open entrymatchMedia()
window.matchMedia(query)Tests a CSS media query from JavaScript and lets you subscribe to changes.
Open entryMutationObserver
new MutationObserver(callback)Watches DOM changes and batches them into callback records.
Open entryrequestAnimationFrame()
requestAnimationFrame(fn)Schedules a callback before the next repaint. The basis of smooth animation.
Open entryResizeObserver
new ResizeObserver(callback)Reports size changes of an element, not just the window.
Open entryError types
AggregateError
new AggregateError(errors, message)Bundles several errors, used by Promise.any when every promise rejects.
Open entryerror.stack
error.stackA non-standard but widely supported stack trace string. Log it, but do not parse it in production.
Open entrynew Error()
new Error(message, { cause })Creates a general error with a message and optional cause.
Open entryRangeError
new RangeError(message)Signals a value outside the allowed range, such as an invalid array length.
Open entrySyntaxError
new SyntaxError(message)Signals malformed code or data, including invalid JSON.
Open entryTypeError
new TypeError(message)Signals that a value is not of the expected type.
Open entryInternationalisation
Intl.Collator
new Intl.Collator(locale)Compares strings with locale-aware sorting rules.
Open entryIntl.DateTimeFormat parts
new Intl.DateTimeFormat(locale).formatToParts(date)Returns the formatted date as labelled parts, useful for custom layouts.
Open entryIntl.ListFormat
new Intl.ListFormat(locale)Joins lists with the correct conjunctions for a locale.
Open entryIntl.NumberFormat currency
new Intl.NumberFormat(locale, { style: "currency", currency: "USD" })Formats money with the right symbol, separators and decimal places.
Open entryIntl.NumberFormat percent
new Intl.NumberFormat(locale, { style: "percent" })Formats a fraction as a percentage.
Open entryIntl.PluralRules
new Intl.PluralRules(locale)Selects the plural category for a number, which is essential for translations.
Open entryIntl.RelativeTimeFormat
new Intl.RelativeTimeFormat(locale)Formats relative times such as “3 days ago” for a locale.
Open entryIntl.Segmenter
new Intl.Segmenter(locale, { granularity: "word" })Splits text into graphemes, words or sentences using locale rules.
Open entryLanguage basics
Arrow function
(a, b) => a + bA concise function expression. It does not bind its own this or arguments.
Open entryChained comparison
a >= min && a <= maxJavaScript has no chained comparison. Combine two comparisons explicitly.
Open entryComma operator
a = (b++, c)Evaluates each expression and returns the last value. Rarely worth the confusion.
Open entryDefault parameter
function f(a = 1) { … }Supplies a value when the argument is undefined.
Open entrydestructuring
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 entryfor…in
for (const key in object) { … }Iterates enumerable property names, including inherited ones. Use Object.keys for own keys only.
Open entryfor…of
for (const item of iterable) { … }Iterates values of arrays, strings, maps and sets. Prefer it over for…in for data.
Open entryFunction declaration
function name(args) { … }A named function hoisted to the top of its scope. Good for top-level utilities.
Open entryif / else
if (condition) { … } else { … }Runs a block when a condition is truthy, with optional else branches.
Open entryinstanceof
value instanceof ClassTests whether an object was created by a constructor and is therefore on its prototype chain.
Open entrylet / 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 entryLogical assignment
x ??= 1; x ||= 2; x &&= 3;Assigns only when the operator’s condition passes. Useful for filling defaults.
Open entryNullish coalescing
value ?? fallbackUses the fallback only when the left side is null or undefined, unlike || which also replaces 0 and "".
Open entryOptional catch binding
try { … } catch { … }Omits the error variable when the handler does not need it.
Open entryOptional chaining
user?.address?.cityStops evaluating and returns undefined when the value before ?. is null or undefined.
Open entryRest in objects
const { a, ...rest } = obj;Copies an object while omitting named keys. Handy for updating immutable state.
Open entryRest parameter
function f(...items) { … }Collects the remaining arguments into a real array.
Open entrySpread syntax
[...a, ...b]Expands an iterable into a new array, object or argument list without mutating the original.
Open entryStrict equality
a === bCompares without type coercion. Use it instead of == so 0, "", false and null stay distinct.
Open entryStrict mode
"use strict"Opts into stricter parsing and error rules. Modules are strict by default.
Open entrySwitch statement
switch (value) { case …: break; }Branches on strict equality. Every case needs a break or a deliberate fallthrough comment.
Open entryTemplate literal
`Hello, ${name}`A string with interpolation and multi-line support. Use backticks, not quotes.
Open entryTernary operator
condition ? a : bChooses between two values. Keep it short; a full if statement is clearer for side effects.
Open entrythrow
throw new Error("message")Stops execution and raises an exception. Throw Error objects, not strings.
Open entrytry / catch
try { … } catch (error) { … } finally { … }Handles thrown errors. finally always runs, including when an error is thrown.
Open entrytypeof
typeof valueReturns a string describing the type. Arrays and null need their own checks.
Open entryvar
var x = 1;Function-scoped and hoisted. Kept for legacy code; use let or const instead.
Open entryMap and Set methods
map.clear()
map.clear()Removes every entry.
Open entrymap.delete()
map.delete(key)Removes a key and returns whether it existed.
Open entrymap.forEach()
map.forEach((value, key) => {})Iterates entries in insertion order.
Open entrymap.get()
map.get(key)Reads a value by key, or undefined when the key is absent.
Open entrymap.has()
map.has(key)Tests whether a key exists, including keys mapped to undefined.
Open entrymap.keys() / values() / entries()
map.entries()Iterators over keys, values or [key, value] pairs.
Open entrymap.set()
map.set(key, value)Adds or replaces a value and returns the map for chaining.
Open entrymap.size
map.sizeThe number of entries. It is a property, not a method.
Open entryset.clear()
set.clear()Removes every value.
Open entryset.delete()
set.delete(value)Removes a value and returns whether it existed.
Open entryset.difference()
a.difference(b)Returns values in the first set that are not in the second.
Open entryset.forEach()
set.forEach(value => {})Iterates values in insertion order.
Open entryset.has()
set.has(value)Tests membership in constant time on average.
Open entryset.intersection()
a.intersection(b)Returns a new set with values present in both sets.
Open entryset.isDisjointFrom()
a.isDisjointFrom(b)Tests whether the sets share no values.
Open entryset.isSubsetOf()
a.isSubsetOf(b)Tests whether every value in a is also in b.
Open entryset.isSupersetOf()
a.isSupersetOf(b)Tests whether a contains every value in b.
Open entryset.size
set.sizeThe number of values.
Open entryset.symmetricDifference()
a.symmetricDifference(b)Returns values that appear in exactly one set.
Open entryset.union()
a.union(b)Returns a new set with values from both sets.
Open entryMore array and object methods
array.copyWithin()
items.copyWithin(target, start, end)Copies a slice to another position inside the same array.
Open entryarray.lastIndexOf()
items.lastIndexOf(value)Returns the last index of a value, or -1.
Open entryarray.reduceRight()
items.reduceRight(fn, initial)Like reduce but processes from the end to the start.
Open entryarray.toReversed()
items.toReversed()Returns a reversed copy without mutating the original array.
Open entryarray.toSpliced()
items.toSpliced(start, deleteCount, …items)Returns a spliced copy instead of mutating the original.
Open entryarray.with()
items.with(index, value)Returns a copy with one index replaced. Negative indexes count from the end.
Open entryMap.groupBy()
Map.groupBy(items, fn)Groups items into a Map, so keys can be any value.
Open entryObject.create()
Object.create(proto, descriptors)Creates an object with a chosen prototype and optional property descriptors.
Open entryObject.defineProperty()
Object.defineProperty(obj, key, descriptor)Defines a property with precise control over value, writability, enumerability and getters.
Open entryObject.fromEntries() with map
Object.fromEntries(map)Turns a Map or entry list into a plain object.
Open entryObject.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptor(obj, key)Reads the full descriptor of one property.
Open entryObject.getOwnPropertyNames()
Object.getOwnPropertyNames(obj)Lists own string keys, including non-enumerable ones.
Open entryObject.getPrototypeOf()
Object.getPrototypeOf(obj)Returns the prototype of an object.
Open entryObject.groupBy()
Object.groupBy(items, fn)Groups items into an object keyed by the callback result.
Open entryObject.is()
Object.is(a, b)Compares values like === but treats NaN as equal and +0 as different from -0.
Open entryObject.preventExtensions()
Object.preventExtensions(obj)Prevents new properties but allows editing and deleting existing ones.
Open entryObject.seal()
Object.seal(obj)Prevents adding or removing properties while still allowing values to change.
Open entryObject.setPrototypeOf()
Object.setPrototypeOf(obj, proto)Replaces an object’s prototype. Slow; prefer Object.create for new objects.
Open entryMore dates
date.getDate()
date.getDate()The day of the month from 1 to 31.
Open entrydate.getDay()
date.getDay()The weekday from 0 (Sunday) to 6 (Saturday).
Open entrydate.getHours()
date.getHours()The local hour from 0 to 23. Use getUTCHours for UTC.
Open entrydate.getMinutes()
date.getMinutes()The local minutes from 0 to 59.
Open entrydate.getMonth()
date.getMonth()The month from 0 (January) to 11 (December).
Open entrydate.getTime()
date.getTime()Milliseconds since the Unix epoch. Dates compare through this value.
Open entryDate.parse()
Date.parse(text)Parses a date string and returns milliseconds, or NaN when invalid.
Open entrydate.setDate()
date.setDate(day)Changes the day of the month and returns the new timestamp.
Open entrydate.setFullYear()
date.setFullYear(year)Changes the year, optionally alongside month and day.
Open entrydate.toDateString()
date.toDateString()A readable local date without the time.
Open entrydate.toLocaleString()
date.toLocaleString(locale)Formats both date and time for a locale.
Open entrydate.toLocaleTimeString()
date.toLocaleTimeString(locale)Formats the time for a locale.
Open entryDate.UTC()
Date.UTC(year, month, day)Builds a timestamp from UTC parts without creating a Date.
Open entrydate.valueOf()
date.valueOf()Returns the numeric timestamp. It is what Date comparisons use.
Open entryNumbers and Math
BigInt
9007199254740993nAn integer type for values beyond Number.MAX_SAFE_INTEGER. BigInt and Number cannot be mixed in arithmetic.
Open entryBigInt.asIntN()
BigInt.asIntN(bits, value)Wraps a BigInt into a signed integer of the given bit width.
Open entryBigInt.asUintN()
BigInt.asUintN(bits, value)Wraps a BigInt into an unsigned integer of the given bit width.
Open entryExponentiation
base ** exponentRaises a number to a power. It has higher precedence than multiplication.
Open entryMath.abs()
Math.abs(value)Returns the absolute value.
Open entryMath.atan2()
Math.atan2(y, x)Returns the angle of a vector, handling all quadrants.
Open entryMath.cbrt()
Math.cbrt(value)Returns the cube root.
Open entryMath.exp()
Math.exp(value)Returns e raised to a power.
Open entryMath.floor() / ceil()
Math.floor(value)Rounds down or up to the nearest integer.
Open entryMath.fround()
Math.fround(value)Rounds a number to the nearest 32-bit float. Useful when interoperating with Float32Array.
Open entryMath.hypot()
Math.hypot(...values)Returns the square root of the sum of squares, without intermediate overflow.
Open entryMath.log10()
Math.log10(value)Returns the base-10 logarithm.
Open entryMath.log2()
Math.log2(value)Returns the base-2 logarithm.
Open entryMath.min() / max()
Math.min(...values)Returns the smallest or largest of the arguments.
Open entryMath.PI / Math.E
Math.PI, Math.EThe constants pi and Euler’s number.
Open entryMath.pow()
Math.pow(base, exponent)Raises a number to a power. The ** operator is the modern equivalent.
Open entryMath.random()
Math.random()Returns a float from 0 up to but not including 1. Not cryptographically secure.
Open entryMath.round()
Math.round(value)Rounds to the nearest integer. Ties go towards positive infinity.
Open entryMath.sign()
Math.sign(value)Returns -1, 0 or 1 depending on the sign.
Open entryMath.sin() / cos() / tan()
Math.sin(radians)Trigonometric functions that take radians, not degrees.
Open entryMath.sqrt()
Math.sqrt(value)Returns the square root.
Open entryMath.trunc()
Math.trunc(value)Removes the fractional part without rounding.
Open entryNumber.EPSILON
Number.EPSILONThe smallest difference between 1 and the next representable number. Useful for float comparisons.
Open entryNumber.isFinite()
Number.isFinite(value)True for finite numbers and false for Infinity, NaN and numeric strings.
Open entryNumber.isInteger()
Number.isInteger(value)True only for finite whole numbers, not for numeric strings.
Open entryNumber.isNaN()
Number.isNaN(value)True only when the value is the NaN number. The global isNaN coerces strings first.
Open entryNumber.isSafeInteger()
Number.isSafeInteger(value)True when an integer can be represented exactly without precision loss.
Open entryNumber.MAX_SAFE_INTEGER
Number.MAX_SAFE_INTEGERThe largest integer that can be represented exactly in a double.
Open entryNumber.parseFloat()
Number.parseFloat(text)Parses a decimal number from the start of a string.
Open entryNumber.parseInt()
Number.parseInt(text, radix)Parses an integer with an explicit radix.
Open entryNumber.prototype.toExponential()
value.toExponential(digits)Formats a number in exponential notation.
Open entryNumber.prototype.toPrecision()
value.toPrecision(digits)Formats a number to a number of significant digits.
Open entryNumber()
Number(value)Converts a value to a number. Empty strings become 0, which is often a trap.
Open entryparseFloat()
parseFloat(value)Parses a floating-point number from the start of a string.
Open entryparseInt()
parseInt(value, 10)Parses an integer from the start of a string. Always pass radix 10.
Open entrytoFixed()
value.toFixed(2)Formats a number with fixed decimal places and returns a string.
Open entrytoLocaleString()
value.toLocaleString(locale)Formats numbers, currency and percentages for a locale.
Open entryObjects
Computed property
{ [key]: value }Uses an expression as the property name.
Open entrydelete operator
delete object.keyRemoves a property. Deleting array elements leaves holes; use splice or filter instead.
Open entryfor…of Object.entries()
for (const [k, v] of Object.entries(obj))The clearest way to iterate own object properties with keys and values.
Open entryin operator
"key" in objectTests whether a property exists in an object or its prototype chain.
Open entryObject.assign()
Object.assign({}, a, b)Copies own enumerable properties into a target. Later sources win.
Open entryObject.entries()
Object.entries(object)Returns an array of [key, value] pairs.
Open entryObject.freeze()
Object.freeze(object)Prevents adding, removing or changing properties. It is shallow.
Open entryObject.fromEntries()
Object.fromEntries(entries)Builds an object from key-value pairs, the inverse of Object.entries.
Open entryObject.hasOwn()
Object.hasOwn(object, key)Safely checks for an own property, even when the object has a null prototype.
Open entryObject.keys()
Object.keys(object)Returns an array of own enumerable string keys.
Open entryObject.values()
Object.values(object)Returns an array of own enumerable values.
Open entryOptional property access
obj?.keyReads a property only when the object exists.
Open entryProperty shorthand
{ name }When the variable name matches the key, write it once.
Open entrystructuredClone()
structuredClone(value)Deep-copies objects, arrays, maps, sets and dates. Functions and DOM nodes cannot be cloned.
Open entryOther globals and patterns
Currying
fn(a)(b)Turns a multi-argument function into a chain of single-argument functions.
Open entryDebounce
debounce(fn, ms)Delays a function until calls stop, which is ideal for search inputs and resize handlers.
Open entrydecodeURIComponent()
decodeURIComponent(text)Decodes an encoded URL component. Wrap it in try/catch for malformed input.
Open entryencodeURI()
encodeURI(url)Encodes a complete URL while leaving reserved characters such as / and ? intact.
Open entryencodeURIComponent()
encodeURIComponent(text)Encodes a string for use inside a URL component such as a query value.
Open entryglobal isFinite()
isFinite(value)Coerces the value before testing. Prefer Number.isFinite.
Open entryglobal isNaN()
isNaN(value)Coerces the value to a number before testing. Prefer Number.isNaN.
Open entryProxy
new Proxy(target, handler)Wraps an object to intercept reads, writes and other operations.
Open entryReflect.get()
Reflect.get(target, key)Performs the default property read, useful inside Proxy traps.
Open entryReflect.has()
Reflect.has(target, key)The functional form of the in operator.
Open entryTagged template
tag`text ${value}`A function receives the template strings and interpolated values separately, which enables safe HTML and CSS helpers.
Open entryThrottle
throttle(fn, ms)Runs a function at most once per interval, which is ideal for scroll handlers.
Open entryvoid operator
void expressionEvaluates an expression and returns undefined. Sometimes used to trigger a function without a return value.
Open entryRegular expressions
/pattern/ literal
const re = /\d+/g;A regular expression literal compiles once and is the fastest way to write a pattern.
Open entryCapture groups
/(\w+)@(\w+)/Parenthesised groups capture parts of a match by number.
Open entryLookahead
x(?=y)Matches x only when it is followed by y, without consuming y.
Open entryLookbehind
(?<=y)xMatches x only when it is preceded by y.
Open entryNamed groups
/(?<year>\d{4})/Names a capture so you can read it from match.groups instead of by position.
Open entryregexp.exec()
re.exec(text)Returns the next match with groups and index, or null. Global patterns remember lastIndex.
Open entryregexp.flags
re.flagsThe flags enabled on a pattern, such as g, i, m, s, u and y.
Open entryregexp.test()
re.test(text)Tests whether a pattern appears. It returns a boolean and advances lastIndex for global patterns.
Open entryreplace with function
text.replace(re, (match, …groups) => value)A replacement function receives the match and captures, which makes conditional rewrites easy.
Open entrySticky flag
/pattern/yThe y flag anchors each match at lastIndex, which suits tokenisers.
Open entrystring.matchAll()
text.matchAll(re)Returns an iterator of every match, including capture groups. The pattern must be global.
Open entryUnicode flag
/\p{Letter}+/uThe u flag enables Unicode-aware escapes and code-point matching.
Open entryStrings
str.at()
str.at(-1)Returns the character at an index and supports negative positions.
Open entrystr.charAt()
str.charAt(index)Returns the character at an index, or an empty string when out of range.
Open entrystr.includes()
str.includes(term)Tests whether a substring exists. Case-sensitive unless you normalise both sides.
Open entrystr.indexOf()
str.indexOf(term)Returns the first position of a substring, or -1. Use includes when you only need a boolean.
Open entrystr.localeCompare()
a.localeCompare(b)Compares strings using language-aware rules. Pass a locale for deterministic output.
Open entrystr.match()
str.match(regexp)Returns the matches of a regular expression, including groups.
Open entrystr.normalize()
str.normalize("NFC")Normalises Unicode so visually identical characters compare equal.
Open entrystr.padStart with numbers
String(n).padStart(2, "0")Format a number with leading zeros for timers and dates.
Open entrystr.padStart() / padEnd()
str.padStart(length, pad)Pads a string to a length. Useful for aligned numbers and codes.
Open entrystr.repeat()
str.repeat(count)Repeats a string. The count must be a non-negative integer.
Open entrystr.replace()
str.replace(pattern, replacement)Replaces the first match of a string or regular expression.
Open entrystr.replaceAll()
str.replaceAll(term, replacement)Replaces every match. With a regexp, the global flag is still required.
Open entrystr.search()
str.search(regexp)Returns the index of the first match, or -1.
Open entrystr.slice()
str.slice(start, end)Extracts a substring. Negative indexes count from the end.
Open entrystr.split()
str.split(separator)Splits a string into an array. Use an empty separator for characters or a regexp for patterns.
Open entrystr.startsWith() / endsWith()
str.startsWith(prefix)Tests the beginning or end of a string. An optional position changes where the test starts.
Open entrystr.substring()
str.substring(start, end)Like slice but swaps arguments when start is greater than end and does not accept negatives.
Open entrystr.toUpperCase() / toLowerCase()
str.toUpperCase()Changes case. Be careful where case changes the meaning of identifiers.
Open entrystr.trim()
str.trim()Removes whitespace from both ends. trimStart and trimEnd remove one side.
Open entryString length
"text".lengthCounts UTF-16 code units. Emoji outside the basic plane count as two.
Open entryString()
String(value)Converts a value to a string. Handles objects, null and undefined predictably.
Open entryTyped arrays and encoding
ArrayBuffer
new ArrayBuffer(byteLength)A fixed-length block of raw bytes. Views such as Uint8Array read and write it.
Open entrybtoa() / atob()
btoa(text) / atob(encoded)Encodes and decodes Base64 for ASCII text. Use TextEncoder for Unicode.
Open entryDataView
new DataView(buffer)Reads and writes numbers of various widths and endianness from an ArrayBuffer.
Open entryFloat32Array
new Float32Array(values)A view of 32-bit floating point numbers.
Open entrytypedArray.set()
target.set(source, offset)Copies values from another array or typed array into a typed array.
Open entrytypedArray.slice()
view.slice(start, end)Copies part of a typed array into a new buffer.
Open entrytypedArray.subarray()
view.subarray(start, end)Returns a view over part of the same buffer without copying.
Open entryUint8Array
new Uint8Array(buffer)A view of bytes as unsigned 8-bit integers.
Open entryTurn the reference into recall.
Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.