JavaScript Reference
Every JavaScript statement, operator, built-in object, method and the most-used DOM and Web APIs in one place. Concise, accurate pages with live examples, syntax, parameters, return values and browser support.
Global Functions and Values
-
parseInt()Parses a string into an integer. -
parseFloat()Parses a string into a floating-point number. -
isNaN()Tests whether a value is NaN after conversion. -
isFinite()Tests whether a value is a finite number after conversion. -
encodeURIComponent()Encodes a URI component. -
decodeURIComponent()Decodes a URI component. -
encodeURI()Encodes a whole URI. -
decodeURI()Decodes a whole URI. -
structuredClone()Deep-copies a value with the structured clone algorithm. -
queueMicrotask()Queues a microtask. -
globalThisThe global object in every environment. -
undefinedThe undefined value and property. -
NaNThe not-a-number value. -
InfinityThe positive infinity value. -
eval()Evaluates JavaScript code in a string (and why to avoid it).
Statements and Declarations
-
varDeclares a function-scoped variable. -
letDeclares a block-scoped variable. -
constDeclares a block-scoped constant binding. -
if...elseRuns code conditionally. -
switchSelects code by matching values. -
forThe classic loop with three expressions. -
for...inLoops over enumerable property names. -
for...ofLoops over iterable values. -
for await...ofLoops over async iterables. -
whileLoops while a condition holds. -
do...whileLoops at least once. -
breakExits a loop, switch or labeled block. -
continueSkips to the next iteration. -
labelLabels a statement for break and continue. -
returnReturns a value from a function. -
throwThrows an exception. -
try...catch...finallyHandles exceptions. -
functionDeclares a function. -
async functionDeclares an async function. -
function*Declares a generator function. -
classDeclares a class. -
importImports bindings from a module. -
exportExports bindings from a module. -
debuggerInvokes the debugger. -
block and empty statementsGroups statements and the empty statement. -
usingDeclares a resource that is disposed at scope end (check support). -
"use strict"Enables strict mode.
Operators
-
arithmetic operators+, -, *, /, %, **, ++ and --. -
assignment operators=, +=, -=, ??=, ||=, &&= and friends. -
comparison operators==, ===, !=, !==, <, >, <=, >=. -
logical operators&&, || and !. -
??The nullish coalescing operator. -
?.The optional chaining operator. -
?:The conditional (ternary) operator. -
bitwise operators&, |, ^, ~, <<, >>, >>>. -
typeofReturns the type of a value. -
instanceofTests the prototype chain. -
inTests whether a property exists. -
deleteRemoves a property. -
voidEvaluates and returns undefined. -
newCreates an object from a constructor. -
... (spread and rest)Expands iterables and collects arguments. -
,The comma operator. -
( )The grouping operator. -
destructuring assignmentUnpacks arrays and objects. -
operator precedenceThe precedence and associativity table. -
template literalsBacktick strings, interpolation and tags. -
=>Arrow function expressions. -
new.targetDetects constructor calls. -
import.metaModule metadata. -
thisThe this keyword in all contexts. -
superCalls parent constructors and methods. -
awaitWaits for a promise. -
yieldPauses a generator.
Object
-
Object.assign()Copies enumerable properties onto a target. -
Object.create()Creates an object with a given prototype. -
Object.defineProperty()Defines or modifies a property descriptor. -
Object.defineProperties()Defines several properties at once. -
Object.entries()Returns an array of [key, value] pairs. -
Object.fromEntries()Builds an object from key-value pairs. -
Object.freeze()Makes an object immutable (shallow). -
Object.getOwnPropertyDescriptor()Reads a property descriptor. -
Object.getOwnPropertyNames()Lists own property names. -
Object.getPrototypeOf()Returns an object's prototype. -
Object.groupBy()Groups items by a key function. -
Object.hasOwn()Tests for an own property. -
Object.is()Compares with SameValue semantics. -
Object.isFrozen()Tests whether an object is frozen. -
Object.keys()Returns own enumerable property names. -
Object.preventExtensions()Prevents adding properties. -
Object.seal()Prevents adding and removing properties. -
Object.setPrototypeOf()Changes an object's prototype. -
Object.values()Returns own enumerable values. -
Object.prototype.hasOwnProperty()Tests for an own property (legacy form). -
Object.prototype.toString()Returns a string tag for an object. -
Object.prototype.propertyIsEnumerable()Tests whether a property is enumerable. -
prototypes and the prototype chainHow inheritance works. -
property descriptorswritable, enumerable, configurable, get and set.
Function
-
Function.prototype.bind()Returns a function with a fixed this and arguments. -
Function.prototype.call()Calls a function with a given this. -
Function.prototype.apply()Calls a function with this and an array of arguments. -
Function.lengthThe number of declared parameters. -
Function.nameThe function's name. -
Function.prototype.toString()Returns the source text of a function. -
argumentsThe array-like arguments object. -
default parametersParameter default values. -
rest parametersCollecting remaining arguments. -
closuresFunctions that remember their scope (concept page). -
hoistingHow declarations are hoisted (concept page). -
IIFEImmediately invoked function expressions (concept page).
Array
-
Array.from()Creates an array from an iterable or array-like. -
Array.isArray()Tests whether a value is an array. -
Array.of()Creates an array from arguments. -
Array.prototype.at()Returns the element at an index (negative allowed). -
Array.prototype.concat()Merges arrays. -
Array.prototype.copyWithin()Copies part of an array onto itself. -
Array.prototype.entries()Returns an iterator of [index, value]. -
Array.prototype.every()Tests whether all elements pass a test. -
Array.prototype.fill()Fills elements with a value. -
Array.prototype.filter()Keeps elements that pass a test. -
Array.prototype.find()Returns the first matching element. -
Array.prototype.findIndex()Returns the index of the first match. -
Array.prototype.findLast()Returns the last matching element. -
Array.prototype.findLastIndex()Returns the index of the last match. -
Array.prototype.flat()Flattens nested arrays. -
Array.prototype.flatMap()Maps and flattens one level. -
Array.prototype.forEach()Runs a function for each element. -
Array.prototype.includes()Tests whether an array contains a value. -
Array.prototype.indexOf()Returns the first index of a value. -
Array.prototype.join()Joins elements into a string. -
Array.prototype.keys()Returns an iterator of indexes. -
Array.prototype.lastIndexOf()Returns the last index of a value. -
Array.prototype.map()Transforms each element. -
Array.prototype.pop()Removes the last element. -
Array.prototype.push()Adds elements at the end. -
Array.prototype.reduce()Reduces an array to one value. -
Array.prototype.reduceRight()Reduces from right to left. -
Array.prototype.reverse()Reverses an array in place. -
Array.prototype.shift()Removes the first element. -
Array.prototype.slice()Returns a shallow copy of a portion. -
Array.prototype.some()Tests whether any element passes. -
Array.prototype.sort()Sorts an array in place. -
Array.prototype.splice()Adds or removes elements in place. -
Array.prototype.toReversed()Returns a reversed copy. -
Array.prototype.toSorted()Returns a sorted copy. -
Array.prototype.toSpliced()Returns a spliced copy. -
Array.prototype.with()Returns a copy with one element replaced. -
Array.prototype.unshift()Adds elements at the start. -
Array.prototype.values()Returns an iterator of values. -
Array.prototype.lengthThe number of elements. -
Array.prototype.toString()Converts an array to a string. -
Map.groupBy() and array groupingGrouping array items into a Map. -
array destructuring and sparse arraysHoles, sparse arrays and destructuring (concept page).
String
-
String.fromCharCode()Creates a string from UTF-16 code units. -
String.fromCodePoint()Creates a string from code points. -
String.raw()The tag for raw template strings. -
String.prototype.at()Returns the character at an index. -
String.prototype.charAt()Returns the character at an index. -
String.prototype.charCodeAt()Returns a UTF-16 code unit. -
String.prototype.codePointAt()Returns a code point. -
String.prototype.concat()Concatenates strings. -
String.prototype.endsWith()Tests the end of a string. -
String.prototype.includes()Tests whether a substring exists. -
String.prototype.indexOf()Returns the first index of a substring. -
String.prototype.isWellFormed()Tests for lone surrogates. -
String.prototype.lastIndexOf()Returns the last index of a substring. -
String.prototype.localeCompare()Compares strings by locale. -
String.prototype.match()Matches a regular expression. -
String.prototype.matchAll()Returns all regular expression matches. -
String.prototype.normalize()Normalizes Unicode. -
String.prototype.padEnd()Pads the end of a string. -
String.prototype.padStart()Pads the start of a string. -
String.prototype.repeat()Repeats a string. -
String.prototype.replace()Replaces a pattern once. -
String.prototype.replaceAll()Replaces every match. -
String.prototype.search()Finds a match index with a regular expression. -
String.prototype.slice()Extracts part of a string. -
String.prototype.split()Splits a string into an array. -
String.prototype.startsWith()Tests the start of a string. -
String.prototype.substring()Extracts part of a string. -
String.prototype.toLowerCase()Converts to lower case. -
String.prototype.toUpperCase()Converts to upper case. -
String.prototype.toLocaleUpperCase()Locale-aware upper casing. -
String.prototype.toWellFormed()Replaces lone surrogates. -
String.prototype.trim()Removes whitespace from both ends. -
String.prototype.trimStart()Removes leading whitespace. -
String.prototype.trimEnd()Removes trailing whitespace. -
String.prototype.lengthThe length in UTF-16 code units. -
String.prototype[Symbol.iterator]()Iterating code points. -
strings and UnicodeUTF-16, code points and graphemes.
Number and BigInt
-
Number.EPSILONThe smallest difference between two numbers. -
Number.MAX_SAFE_INTEGERThe largest safe integer. -
Number.MAX_VALUE and MIN_VALUEThe largest and smallest positive values. -
Number.isInteger()Tests for an integer. -
Number.isSafeInteger()Tests for a safe integer. -
Number.isFinite()Tests for a finite number without coercion. -
Number.isNaN()Tests for NaN without coercion. -
Number.parseFloat()Parses a floating-point number. -
Number.parseInt()Parses an integer. -
Number.prototype.toFixed()Formats with fixed decimals. -
Number.prototype.toPrecision()Formats with significant digits. -
Number.prototype.toExponential()Formats in exponential notation. -
Number.prototype.toString()Converts to a string in a radix. -
Number.prototype.toLocaleString()Formats by locale. -
Number()Converts values to numbers. -
floating-point numbersWhy 0.1 + 0.2 is not 0.3. -
BigIntArbitrary-precision integers. -
BigInt.asIntN() and asUintN()Wraps BigInts to a width.
Math
-
Math.abs()Returns the absolute value. -
Math.ceil()Rounds up. -
Math.floor()Rounds down. -
Math.round()Rounds to the nearest integer. -
Math.trunc()Removes the fractional part. -
Math.sign()Returns the sign of a number. -
Math.max()Returns the largest value. -
Math.min()Returns the smallest value. -
Math.pow() and **Raises to a power. -
Math.sqrt()Square root. -
Math.cbrt()Cube root. -
Math.hypot()Length of a hypotenuse. -
Math.random()Returns a pseudo-random number. -
Math.log()Natural logarithm. -
Math.log2() and log10()Base-2 and base-10 logarithms. -
Math.exp()e raised to a power. -
Math.sin(), cos(), tan()Trigonometric functions. -
Math.asin(), acos(), atan(), atan2()Inverse trigonometric functions. -
Math.sinh(), cosh(), tanh()Hyperbolic functions. -
Math.fround() and clz32()Low-level numeric helpers. -
Math.PI, E and other constantsThe Math constants. -
Math.sumPrecise()Precise summation (check support).
Date and Intl
-
new Date()Creates date objects. -
Date.now()Returns the current timestamp. -
Date.parse() and Date.UTC()Parses and builds timestamps. -
Date.prototype.getFullYear()Reads the year (and the other getters). -
Date.prototype.getTime()Returns the timestamp in milliseconds. -
Date.prototype.setDate()Sets the day of the month (and the other setters). -
Date.prototype.toISOString()Formats as ISO 8601. -
Date.prototype.toLocaleDateString()Formats a date by locale. -
Date.prototype.toLocaleTimeString()Formats a time by locale. -
Date.prototype.toString() and friendsOther string conversions. -
Date.prototype.getTimezoneOffset()The time zone offset. -
date arithmeticAdding days, differences and pitfalls (concept page). -
Intl.NumberFormatFormats numbers, currency and units. -
Intl.DateTimeFormatFormats dates and times. -
Intl.RelativeTimeFormatFormats relative times. -
Intl.PluralRulesSelects plural forms. -
Intl.ListFormatFormats lists. -
Intl.CollatorCompares strings by locale. -
Intl.SegmenterSplits text into graphemes, words and sentences. -
TemporalThe Temporal API (check support).
RegExp
-
RegExpCreating regular expressions. -
test()Tests a string against a pattern. -
exec()Runs a match and returns details. -
flagsg, i, m, s, u, v, y, d. -
capture groupsNumbered, named and non-capturing groups. -
lookahead and lookbehindZero-width assertions. -
quantifiers*, +, ? , {n,m} and lazy forms. -
character classes\d, \w, \s, [...] and Unicode property escapes. -
anchors and boundaries^, $, \b and \B. -
backreferences\1 and \k<name>. -
lastIndexState in global and sticky regular expressions. -
RegExp.escape()Escapes text for patterns (check support).
Collections
-
MapKey-value collection with any key type. -
get() and set()Reading and writing entries. -
has() and delete()Testing and removing entries. -
Map iterationforEach, keys, values and entries. -
sizeThe number of entries. -
Map.groupBy()Groups items into a Map. -
SetA collection of unique values. -
add(), has(), delete()The core Set methods. -
set operationsThe set algebra methods (check support). -
Set iterationforEach, values and entries. -
WeakMapMaps with weakly held object keys. -
WeakSetSets of weakly held objects. -
WeakRef and FinalizationRegistryWeak references and cleanup callbacks.
Promises and Async
-
PromiseThe Promise constructor and states. -
Promise.prototype.then()Chains a fulfillment handler. -
Promise.prototype.catch()Handles rejection. -
Promise.prototype.finally()Runs cleanup either way. -
Promise.all()Waits for all promises. -
Promise.allSettled()Waits for all to settle. -
Promise.race()Settles with the first to settle. -
Promise.any()Fulfills with the first fulfilled. -
Promise.resolve() and reject()Creating settled promises. -
Promise.withResolvers()Creates a promise with exposed resolvers. -
async and awaitPromise syntax in depth. -
the event loopTasks, microtasks and ordering. -
setTimeout()Runs code after a delay. -
setInterval()Runs code repeatedly. -
clearTimeout() and clearInterval()Cancels timers. -
AbortControllerCancels async operations. -
requestAnimationFrame()Runs code before the next paint. -
requestIdleCallback()Runs code when the browser is idle.
Iterators, Generators and Symbols
-
iterator protocolnext(), done and value. -
iterable protocolSymbol.iterator. -
Generator objectsnext(), return() and throw(). -
async generatorsAsync iteration. -
Iterator helpersIterator.prototype.map, filter, take and friends. -
SymbolUnique primitive values. -
Symbol.for()The global symbol registry. -
Symbol.iteratorThe well-known iteration symbol. -
Symbol.toPrimitiveCustomizes conversion. -
well-known symbolsSymbol.asyncIterator, hasInstance, toStringTag and others.
JSON, Errors and Reflection
-
JSON.parse()Parses JSON text. -
JSON.stringify()Serializes a value to JSON. -
toJSON()Customizing serialization. -
ErrorThe Error object and its properties. -
Error causeChaining errors. -
TypeError, RangeError, SyntaxError and othersThe built-in error types. -
AggregateErrorGroups several errors. -
ProxyIntercepts object operations. -
Proxy handler trapsThe list of traps. -
ReflectMethods for interceptable operations. -
decoratorsDecorator syntax status (check support).
Typed Arrays and Binary Data
-
ArrayBufferRaw binary buffers. -
typed arraysUint8Array, Float64Array and friends. -
DataViewReading and writing binary values. -
SharedArrayBuffer and AtomicsShared memory and atomic operations. -
TextEncoder and TextDecoderEncoding strings to bytes and back. -
Blob and FileBinary objects and files. -
btoa() and atob()Base64 encoding of strings.
Classes and Modules
-
class fields and private membersPublic, private and static fields. -
getters and settersAccessor properties. -
static membersStatic methods, fields and blocks. -
extends and inheritanceSubclassing. -
private methods and #x in objPrivate methods and brand checks. -
ES modulesimport, export and module semantics. -
dynamic import()Loading modules on demand. -
CommonJS vs ES modulesThe module systems compared (concept page). -
strict modeWhat strict mode changes (concept page). -
scope and thisScope chain and how this is bound (concept page).
DOM: Document and Elements
-
document.querySelector()Finds the first matching element. -
document.querySelectorAll()Finds all matching elements. -
document.getElementById()Finds an element by id. -
document.createElement()Creates an element. -
document.createTextNode()Creates a text node. -
Element.append() and prepend()Inserts nodes inside an element. -
Element.before() and after()Inserts nodes beside an element. -
Element.remove()Removes an element. -
Element.replaceWith()Replaces an element. -
Node.cloneNode()Copies a node. -
Element.insertAdjacentHTML()Inserts HTML at a position. -
Element.innerHTMLGets or sets HTML (and its dangers). -
Node.textContentGets or sets text. -
HTMLElement.innerTextRendered text. -
Element.classListManipulates classes. -
getAttribute() and setAttribute()Reads and writes attributes. -
HTMLElement.datasetReads data-* attributes. -
HTMLElement.styleInline styles. -
window.getComputedStyle()Reads computed styles. -
Element.closest()Finds the nearest matching ancestor. -
Element.matches()Tests a selector. -
Node.contains()Tests for descendants. -
parentElement, children and siblingsTree navigation properties. -
getBoundingClientRect()Size and position. -
Element.scrollIntoView()Scrolls an element into view. -
HTMLElement.focus()Moves focus. -
template elementCloning HTML templates. -
DocumentFragmentBatching DOM insertions. -
MutationObserverWatches DOM changes. -
IntersectionObserverWatches visibility. -
ResizeObserverWatches element size. -
custom elementsDefining your own elements. -
shadow DOMEncapsulated DOM trees. -
HTMLDialogElementshowModal(), show() and close(). -
popover APIshowPopover() and hidePopover(). -
FormDataReads form values. -
constraint validation APIcheckValidity() and setCustomValidity(). -
Selection and RangeText selection APIs.
DOM: Events
-
EventTarget.addEventListener()Registers an event handler. -
EventTarget.removeEventListener()Removes an event handler. -
EventTarget.dispatchEvent()Dispatches an event. -
CustomEventCreates custom events. -
Event.preventDefault()Cancels default behavior. -
Event.stopPropagation()Stops bubbling. -
Event.target and currentTargetWhich element received the event. -
event delegationHandling events on a parent. -
event bubbling and capturingPropagation phases. -
click and pointer eventsMouse and pointer events. -
keyboard eventskeydown, keyup and KeyboardEvent. -
input and change eventsForm input events. -
submit eventForm submission. -
focus and blur eventsFocus events. -
scroll and wheel eventsScroll events. -
touch and gesture eventsTouch events. -
drag and drop eventsThe HTML drag and drop events. -
DOMContentLoaded and loadPage lifecycle events. -
hashchange and popstateNavigation events. -
resize eventWindow resize. -
visibilitychangePage visibility. -
beforeunloadWarns before leaving. -
message eventMessages between windows and workers. -
passive listenersThe passive option. -
the once and signal optionsListener options.
Browser and Web APIs
-
locationReading and changing the URL. -
historyThe History API. -
navigatorBrowser and device information. -
window.open()Opens windows. -
alert(), confirm(), prompt()Dialog boxes. -
window.matchMedia()Evaluates media queries. -
window.scrollTo() and scroll positionScrolling the window. -
screen and devicePixelRatioScreen information. -
fetch()Makes HTTP requests. -
Request and ResponseThe fetch objects. -
HeadersHTTP headers. -
URLParsing and building URLs. -
URLSearchParamsQuery strings. -
localStoragePersistent key-value storage. -
sessionStoragePer-tab storage. -
IndexedDBClient-side database. -
document.cookieCookies. -
Clipboard APIReading and writing the clipboard. -
Geolocation APIReading the position. -
Notifications APIShowing notifications. -
Web WorkersBackground threads. -
Service WorkersOffline and caching. -
WebSocketTwo-way connections. -
EventSourceServer-sent events. -
BroadcastChannelMessaging between tabs. -
Canvas 2D contextDrawing on canvas. -
Web Audio APIAudio processing. -
MediaDevices.getUserMedia()Camera and microphone. -
Fullscreen APIFullscreen mode. -
performance.now() and Performance APITiming and measurement. -
consoleconsole.log, table, group, time and more. -
Web Share APISharing content. -
Vibration and other device APIsSmall device APIs. -
Page visibility and lifecycleVisibility and lifecycle APIs (concept page). -
same-origin policy and CORSBrowser security basics (concept page). -
Content Security PolicyCSP basics (concept page).
Practical Pages
-
ECMAScript versionsES2015 to ES2025 features by year (concept page). -
data types and conversionPrimitives, objects and coercion rules (concept page). -
equality comparison==, === and Object.is (concept page). -
truthy and falsy valuesThe falsy list (concept page). -
immutability patternsCopying and freezing (concept page). -
error handling patternstry/catch, async errors and guards (concept page). -
performance tipsCommon performance pitfalls (concept page). -
deprecated and legacy featureswith, arguments.callee, escape() and friends (concept page).
Không có kết quả nào khớp với “”. Hãy thử tìm kiếm trên trang.
Không có kết quả nào khớp với “”. Hãy thử tìm kiếm trên trang.