JavaScript reference
Language syntax, classes, methods of arrays, strings and objects, promises, the DOM and browser APIs. You run every example with one click and see the new result in the console after you edit it.
211 entries
Syntax and statements
Variables, conditions, loops, functions, classes and operators.
- letDeclares a block-scoped variable whose value you can change later.
- constDeclares a block-scoped constant. A variable like this can’t be assigned a new value.
- varDeclares a function-scoped variable. This is the older way, replaced today by let and const.
- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
- Default parametersValues a function parameter gets when the argument is not passed or is undefined.
- Rest parameter (...rest)Collects all the remaining function arguments into a real array. You write it as ...name at the end of the parameter list.
- function*Declares a generator: a function that hands back successive values through yield and pauses between them.
- Iterators (Symbol.iterator)The iteration protocol: an object with a [Symbol.iterator]() method works with for...of, spread, and destructuring.
- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- switchCompares a value against a list of case labels and runs the code from the first match.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- for...inWalks the names of an object’s enumerable properties, including ones inherited from the prototype.
- whileRepeats a block of code while the condition is true. The condition is checked before every turn.
- do...whileRuns a block of code at least once, then repeats it while the condition is true.
- breakImmediately ends a loop or a switch statement and moves on to the code right after it.
- continueSkips the rest of the current loop turn and moves straight to the next one.
- returnEnds a function and passes a value back to the place where the function was called.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- throwThrows an exception: stops the current code and passes the error to the nearest catch block.
- ErrorThe built-in error object with a message and a stack trace. The basis for exceptions and custom error classes.
- classDefines a class: a template for creating objects that share the same fields and methods.
- importLoads values exported from another ES module: functions, classes, constants, or a whole module.
- exportMakes functions, classes, and values from a module available so other files can import them.
- typeofReturns a string with the name of a value’s type, e.g. "number", "string", or "object".
- ? :The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
- ?.The ?. (optional chaining) operator safely reads a property. When the object is null or undefined, it returns undefined instead of throwing.
- ??The ?? (nullish coalescing) operator returns the right side only when the left side is null or undefined. Ideal for default values.
- Template literalsText templates in backticks: insert values with ${} and span multiple lines.
- ===The strict equality operator compares values without type conversion: true only for the same type and the same value.
- &&, ||, !The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.
Arrays
Methods of the Array object: transforming, filtering, searching and sorting.
- Array.prototype.map()Creates a new array with the results of calling a function for every element.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
- Array.prototype.reduce()Reduces the whole array to a single value, such as a sum, an object, or a new array.
- Array.prototype.forEach()Calls a function for every element of the array.
- Array.prototype.find()Returns the first element that matches a condition, or undefined.
- Array.prototype.findIndex()Returns the index of the first element that matches a condition, or -1.
- Array.prototype.findLast()Returns the last element that matches a condition, searching the array from the end.
- Array.prototype.findLastIndex()Returns the index of the last element matching a condition, searching from the end, or -1.
- Array.prototype.some()Checks whether at least one element matches a condition.
- Array.prototype.every()Checks whether all elements match a condition.
- Array.prototype.includes()Checks whether an array contains the given value.
- Array.prototype.indexOf()Returns the index of the first occurrence of a value, or -1.
- Array.prototype.lastIndexOf()Returns the index of the last occurrence of a value in the array, or -1 when it isn’t there.
- Array.prototype.push()Adds elements to the end of an array and returns its new length.
- Array.prototype.pop()Removes the last element of an array and returns it.
- Array.prototype.shift()Removes the first element of an array and returns it.
- Array.prototype.unshift()Adds elements to the start of an array and returns its new length.
- Array.prototype.slice()Returns a copy of part of an array without changing the original.
- Array.prototype.splice()Removes, replaces, or inserts elements in place, changing the array.
- Array.prototype.toSpliced()Removes, inserts, or replaces elements in a copy of the array. The original is left unchanged.
- Array.prototype.sort()Sorts the array’s elements in place and returns the same array.
- Array.prototype.toSorted()Returns a sorted copy of the array, leaving the original unchanged.
- Array.prototype.reverse()Reverses the order of the array’s elements in place.
- Array.prototype.toReversed()Returns a new array with the elements in reverse order, without changing the original.
- Array.prototype.concat()Combines arrays and values into a new array.
- Array.prototype.join()Joins the array’s elements into a single string with a chosen separator.
- Array.prototype.flat()Flattens nested arrays down to the given depth.
- Array.prototype.flatMap()Maps every element and flattens the result by one level.
- Array.prototype.at()Returns the element at the given index, which can also be counted from the end.
- Array.prototype.with()Returns a copy of the array in which the element at the given index has a new value.
- Array.from()Creates an array from an iterable or "array-like" object.
- Array.of()Creates a new array from the given arguments, regardless of how many there are or their type.
- Array.isArray()Checks whether a value is an array.
- Array.prototype.fill()Fills an array (or part of it) with a single value.
- Array.prototype.lengthThe number of elements in the array, which you can also change.
Strings
Methods of the String object: slicing, replacing, splitting and formatting text.
- String.prototype.lengthThe length of a string, i.e. the number of UTF-16 code units. The property is read-only.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.substring()Returns a portion of a string between two indexes. Negative values are treated as 0, and reversed indexes are swapped.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
- String.prototype.replace()Returns a new string in which the first match of a pattern (or all matches, with the g flag) has been replaced with other text.
- String.prototype.replaceAll()Returns a new string in which every occurrence of a pattern has been replaced with the given text or the result of a function.
- String.prototype.toUpperCase()Returns a copy of the string converted to uppercase. Handles accented letters correctly.
- String.prototype.toLowerCase()Returns a copy of the string converted to lowercase. Useful for comparisons and normalizing data.
- String.prototype.trim()Removes whitespace from both ends of a string: spaces, tabs, and newline characters.
- String.prototype.trimStart()Removes whitespace only from the start of a string. The end of the text stays unchanged.
- String.prototype.trimEnd()Removes whitespace only from the end of a string, including trailing newline characters.
- String.prototype.includes()Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.
- String.prototype.startsWith()Checks whether a string starts with the given text. Returns true or false.
- String.prototype.endsWith()Checks whether a string ends with the given text. Returns true or false.
- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.lastIndexOf()Returns the index of the last occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- String.prototype.padEnd()Pads a string on the right with the given text until it reaches the specified length.
- String.prototype.repeat()Returns a new string made up of the given number of copies of the original.
- String.prototype.at()Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.
- String.prototype.charAt()Returns the character at the given index. Outside the valid range, it returns an empty string instead of undefined.
- String.prototype.match()Matches a string against a regular expression. Returns an array with the match or all matches, or null.
- String.prototype.matchAll()Returns an iterator over all the matches of a regular expression, each one together with its groups and position in the text.
- String.prototype.search()Returns the index of the first match of a regular expression in a string, or -1.
- String.prototype.localeCompare()Compares two strings according to language rules. Returns a negative number, zero, or a positive number, perfect for sorting.
Objects and classes
Object methods, classes, inheritance, getters and prototypes.
- Object.keys()Returns an array of an object’s own, enumerable property names.
- Object.values()Returns an array of an object’s own, enumerable property values.
- Object.entries()Returns an array of an object’s [key, value] pairs.
- Object.assign()Copies properties from one or more objects into a target object.
- Object.freeze()Freezes an object, blocking the addition, removal, and change of its properties.
- Object.fromEntries()Creates an object from a list of [key, value] pairs.
- Object.hasOwn()Checks whether an object has its own property with the given name.
- Object.is()Checks whether two values are the same. It differs from === only for NaN, and for 0 and -0.
- Object.groupBy()Groups elements by a key returned from a function.
- Object.create()Creates a new object with the given prototype.
- thisA keyword pointing to the object a function was called on.
- get / setProperties computed on read (get) and handled on write (set).
- extendsCreates a derived class that inherits another class’s methods and can extend or override them.
- superRefers to the base class: calls its constructor or its version of a method.
- staticMarks a field or method as belonging to the class itself, not to instances created with new.
- #fieldFields and methods prefixed with # are private: only code inside the class can access them.
- instanceofChecks whether an object was created by a given class, or by a class that inherits from it.
Numbers and Math
Conversions, rounding, random numbers and math functions.
- Number.parseInt()Converts the start of a string into an integer in a given numeral system.
- Number.parseFloat()Converts the start of a string into a floating-point number.
- Number.prototype.toFixed()Converts a number into a string with a given number of decimal places.
- Number.prototype.toString()Converts a number into a string, also in a different numeral system, e.g. binary or hexadecimal.
- Number.prototype.toLocaleString()Formats a number the way a given language and region write it: thousands separators, decimal marks, currencies, and percentages.
- Number.isNaN()Checks whether a value is exactly NaN.
- Number.isInteger()Checks whether a value is an integer.
- Number.isFinite()Checks whether a value is an ordinary, finite number, not NaN or infinity.
- BigIntA type for exact calculations on arbitrarily large integers. Literals end with the letter n.
- Math.round()Rounds a number to the nearest integer.
- Math.floor()Rounds a number down, to the nearest smaller integer.
- Math.ceil()Rounds a number up, to the nearest larger integer.
- Math.random()Returns a random number from 0 (inclusive) to 1 (exclusive).
- Math.max()Returns the largest of the given numbers.
- Math.min()Returns the smallest of the given numbers.
- Math.abs()Returns the absolute value of a number, that is, its distance from zero.
- Math.pow()Raises a number to a power.
- Math.sqrt()Returns the square root of a number.
- Math.trunc()Cuts off the fractional part of a number, leaving the integer part.
Asynchronous code
Promises, async/await, timers and fetch requests.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- Promise.prototype.then()Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
- Promise.prototype.finally()Registers a function that runs once the promise settles, whether it ends in success or failure.
- Promise.all()Waits for every promise to be fulfilled and returns an array of their results. Rejects at the first error.
- Promise.allSettled()Waits for every promise to settle and returns a description of each result, both successes and errors.
- Promise.race()Returns a promise that settles the same way as the first promise in the list to settle, whether with success or an error.
- Promise.any()Returns the result of the first promise to be fulfilled. Rejects only once all of them have failed.
- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- setTimeout()Runs a function once, after the given number of milliseconds has passed.
- setInterval()Calls a function repeatedly, at the given interval, until it’s stopped with clearInterval().
- fetch()Sends an HTTP request and returns a promise with the server’s response (a Response object).
Built-in objects
Map, Set, JSON, Date, Intl, RegExp and other objects built into the language.
- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
- SetA collection of unique values: each value can appear in the set only once.
- WeakMapA map with objects as keys that doesn’t keep them in memory: the entry disappears along with the unused object.
- WeakSetA set of objects that doesn’t keep them in memory. Used for marking objects, e.g. ones already handled.
- JSON.stringify()Converts a JavaScript value, such as an object or array, into a string in JSON format.
- JSON.parse()Converts a string in JSON format into a JavaScript value, such as an object or array.
- structuredClone()Creates a deep copy of a value, including nested objects, dates, Maps, and Sets.
- DateAn object representing a specific moment in time, with methods to read and change the date and time.
- Intl.NumberFormatFormats numbers according to a given language’s rules: separators, currencies, percentages, and units.
- Intl.DateTimeFormatFormats dates and times according to the rules of a chosen language and time zone.
- Intl.RelativeTimeFormatFormats relative time in the chosen language, e.g. "in 3 days", "2 hours ago", or "yesterday".
- Intl.PluralRulesPicks the correct grammatical category for a number in a given language, such as one, few, or many.
- RegExpA regular expression: a pattern for searching, validating, and replacing pieces of text.
- SymbolA primitive type for creating unique identifiers, such as property keys that never collide with others.
DOM and events
Finding and creating elements, events, classes, attributes and content.
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- document.querySelectorAll()Returns a static list (NodeList) of every element that matches a CSS selector.
- document.getElementById()Returns the element with the given identifier (the id attribute), or null when there isn’t one.
- EventTarget.addEventListener()Registers a function that’s called every time a given event occurs on an element, for example a click.
- Element.classListAn object for adding, removing, toggling, and checking an element’s CSS classes.
- Node.textContentReads or sets all of an element’s text, without HTML markup.
- Element.innerHTMLReads or replaces an element’s content as HTML code.
- document.createElement()Creates a new HTML element with the given tag name, ready to be inserted into the page.
- Element.append()Adds elements or text at the end of an element’s content.
- Element.remove()Removes an element from the document along with all of its content.
- Element.setAttribute()Sets the value of an element’s HTML attribute, or adds a new attribute.
- HTMLElement.datasetAn object with an element’s data-* attribute values, for reading and storing your own data.
- HTMLElement.styleAn object of styles set directly on an element (inline), for reading and changing individual CSS properties.
- Event.preventDefault()Blocks the browser’s default action for an event, for example submitting a form or following a link’s address.
- Event.targetThe element on which an event actually occurred, for example the clicked button inside a list.
- Element.closest()Returns the nearest ancestor (or the element itself) matching a CSS selector, or null.
- Element.insertAdjacentHTML()Parses a string as HTML and inserts the resulting elements at a chosen position relative to an element.
- EventTarget.removeEventListener()Detaches an event handler function added earlier with addEventListener(). Requires the same function and the same event type.
- Element.getBoundingClientRect()Returns an element’s size and its position relative to the viewport, as a DOMRect object.
- Element.scrollIntoView()Scrolls the page and any scrollable containers so the element appears on screen, either instantly or smoothly.
- Element.childrenA live collection of an element’s direct children. Together with parentElement and nextElementSibling, it’s used for moving around the DOM tree.
- Node.cloneNode()Creates a copy of a node. With the argument true, it also copies all the content, meaning every element and text inside.
- Element.replaceWith()Replaces an element in the document with other elements or text. The old element is removed from the page.
- Element.toggleAttribute()Adds an attribute when it’s missing, or removes it when it’s present. Works best for boolean attributes, such as hidden or disabled.
- HTMLElement.focus()Sets focus on an element, such as a form field, so it immediately receives keyboard input. The blur() method removes focus.
- EventTarget.dispatchEvent()Fires an event on an element from code. Together with CustomEvent, it lets you create custom events carrying extra data.
- getComputedStyle()Returns an element’s computed styles, meaning the CSS values the browser actually applied after taking every rule into account.
Browser APIs
Browser storage, URLs, history, the clipboard, observers and animation frames.
- localStorageBrowser storage for key-value pairs that survives page refreshes and browser restarts.
- sessionStorageBrowser storage for key-value pairs that works only in the current tab and disappears when it closes.
- URLAn object for creating, reading, and changing URLs. It breaks an address into parts: protocol, host, path, and parameters.
- URLSearchParamsAn object for reading and building query parameters in an address, the part after the ? character, e.g. ?course=js&page=2.
- history.pushState()Adds a new entry to the browser history and changes the address bar without reloading the page.
- locationAn object with information about the current page’s address. Lets you read its parts and navigate to a different address.
- navigator.clipboardAsynchronous access to the system clipboard. The writeText() method copies text, and readText() reads it back from the clipboard.
- IntersectionObserverWatches whether an element is visible within the window or a scrollable container, and calls a function whenever that changes.
- ResizeObserverCalls a function every time an observed element’s size changes, no matter the cause of the change.
- MutationObserverWatches for changes in the DOM tree: added and removed elements, attribute and text changes, and reports them in a single function.
- requestAnimationFrame()Schedules a function to run right before the next screen repaint. Used for smooth animations driven by JavaScript.
- matchMedia()Checks in JavaScript whether the page matches a CSS media query, e.g. (max-width: 600px), and lets you react to changes in the result.
- FormDataCollects form field values into name-value pairs. The ready-made object can be read or sent to the server with fetch().
- AbortControllerLets you cancel an asynchronous operation, e.g. a fetch() request, and detach many event handlers at once with a single abort() call.
- console.log()Prints values to the browser console. The console object also has warn(), error(), table(), group(), time(), count(), and assert() methods.
Comparisons
How similar methods and language constructs differ and when to pick each one.
- map() vs forEach()map() builds a new array from a function’s results, while forEach() only calls the function for every element and always returns undefined.
- let vs const vs varconst and let have block scope, while var has function scope. const doesn’t allow reassignment. In new code write const, and let only for values that change.
- for...in vs for...offor...of hands you the successive values of an iterable object, while for...in hands you the successive property names of an object as strings.
- slice() vs splice()slice() copies a section of the array without changing the original, while splice() removes, inserts, or replaces elements in place, mutating the array.
- find() vs filter()find() returns the first element that matches a condition, or undefined, while filter() returns a new array with every element that passed the test.
- () => {} vs functionA regular function has its own this and arguments, is hoisted, and can be called with new. An arrow function is shorter and takes this from its surroundings.
- localStorage vs sessionStoragelocalStorage and sessionStorage share the same methods, but localStorage survives closing the browser, while sessionStorage clears when the tab closes.
- innerHTML vs textContentinnerHTML reads and sets an element’s HTML markup, parsing the string into new elements, while textContent reads and sets plain text, with no markup.
- querySelector() vs getElementById()querySelector() accepts any CSS selector and returns the first matching element, while getElementById() only searches by the id attribute, but is simpler.
- Promise.all() vs Promise.allSettled()Promise.all() rejects at the first error and returns an array of results, while Promise.allSettled() waits for every promise and never rejects.
- async/await vs then()async/await lets you write asynchronous code like ordinary, sequential code, with errors in try...catch, while then() builds a chain of calls on the promise itself.
- setTimeout() vs setInterval()setTimeout() calls a function once after a set amount of time, while setInterval() calls it repeatedly until you stop it with clearInterval().