Home >JavaScript >JavaScript reference – methods and objects

JavaScript reference – methods and objects

An overview of JavaScript methods and objects with examples: arrays, strings, objects, numbers, dates, Promise, fetch and working with the page (DOM). The outputs of the examples are real – they come from running the code in Node.js 24, examples for the page and examples where browsers differ were run in Chrome, Firefox and Safari (the WebKit engine); where the results differ, the entry says so. Each entry gives browser support according to MDN data.

Arrays 36 entries

Strings 34 entries

Numbers and Math 31 entries

  • BigInt A type for integers of any size, exact even above Number.MAX_SAFE_INTEGER.
  • isNaN() Converts the value to a number (like Number()) and returns true when the result is NaN.
  • Math.abs() Returns the absolute value of a number: it turns a negative number into a positive one and leaves a positive one as it is.
  • Math.cbrt() Returns the cube root of a number.
  • Math.ceil() Returns the smallest integer that is greater than or equal to x – it always rounds up.
  • Math.floor() Returns the largest integer that is less than or equal to x – it always rounds down.
  • Math.hypot() Returns √(a² + b² + …) – the length of the hypotenuse of a right triangle or the distance of points.
  • Math.log() Returns the natural logarithm (base e) of a positive number.
  • Math.log10() Returns the logarithm with the base 10 – the power to which 10 must be raised to get x.
  • Math.max() Returns the largest of the passed numbers.
  • Math.min() Returns the smallest of the passed numbers.
  • Math.PI The ratio of the circumference of a circle to its diameter, π ≈ 3.141592653589793.
  • Math.pow() Returns base raised to exponent.
  • Math.random() Returns a pseudo-random decimal number from 0 (inclusive) to 1 (exclusive).
  • Math.round() Rounds to the nearest integer.
  • Math.sign() Returns 1 for a positive number, -1 for a negative one and 0 for zero (-0 for negative zero).
  • Math.sqrt() Returns the square root of a non-negative number.
  • Math.trunc() Returns the integer part of a number – it only cuts off the decimal places, without rounding.
  • Number() Converts a value to a number.
  • Number.EPSILON The smallest difference between the number 1 and the nearest larger number that can be stored (about 2.2 × 10−16).
  • Number.isFinite() Returns true only for a number that is not NaN, Infinity or -Infinity.
  • Number.isInteger() Returns true when the value is a number without a decimal part.
  • Number.isNaN() Returns true only for the value NaN (“not a number”, the result of a failed conversion or calculation).
  • Number.isSafeInteger() Returns true for an integer in the range from -(253 − 1) to 253 − 1.
  • Number.MAX_SAFE_INTEGER The value 253 − 1 = 9,007,199,254,740,991.
  • Number.prototype.toFixed() Returns the number as a string with a fixed number of decimal places (it adds zeros or rounds).
  • Number.prototype.toLocaleString() Returns the number as a string in the form usual for the given language – in American English with commas between thousands and a decimal point, in German…
  • Number.prototype.toPrecision() Rounds the number to the given number of significant digits and returns it as a string.
  • Number.prototype.toString() Converts the number to a string.
  • parseFloat() Reads a decimal number (with a dot, possibly with an exponent) from the start of the string and ignores the rest.
  • parseInt() Reads digits from the start of the string as long as it can and returns an integer.

Objects 15 entries

  • Object.assign() Copies the own enumerable properties of the source objects to the target object and returns the target object.
  • Object.create() Creates a new object whose prototype (the object it inherits methods and properties from) is the given object.
  • Object.defineProperty() Defines a property with exact behavior: whether it can be written, whether it shows in Object.keys() and loops, or whether the value is calculated by a…
  • Object.entries() Returns an array of [key, value] pairs for the own enumerable properties of an object.
  • Object.freeze() Freezes an object – its properties cannot be changed or deleted and new ones cannot be added.
  • Object.fromEntries() The opposite of Object.entries(): it creates an object from an array (or another iterable source) of [key, value] pairs.
  • Object.getPrototypeOf() Returns the prototype of an object, that is the object it inherits methods from.
  • Object.groupBy() Splits elements into groups: it calls a function for each element and sorts it into a group by the returned key.
  • Object.hasOwn() Returns true when the object has the property directly (not inherited from the prototype).
  • Object.is() Checks whether two values are the same.
  • Object.keys() Returns an array of the names of the own enumerable properties of an object.
  • Object.seal() Seals an object – new properties cannot be added and existing ones cannot be deleted, but the values of existing properties can still be changed.
  • Object.values() Returns an array of the values of the own enumerable properties of an object in the same order as Object.keys().
  • structuredClone() Creates a full (deep) copy of a value: it copies nested objects and arrays too.
  • Symbol Creates a unique value – each call of Symbol() gives a different one, even with the same description.

Map, Set and RegExp 17 entries

  • Map A collection of key–value pairs.
  • Map.prototype.delete() Removes the entry with the given key. clear() empties the whole Map.
  • Map.prototype.get() Returns the value for the key.
  • Map.groupBy() Like Object.groupBy(), but the result is a Map – so the group key can also be an object or a number, and the groups stay in the order in which they were…
  • Map.prototype.has() Returns true when the Map contains the key – even when the value stored under it is undefined.
  • Map.prototype.set() Stores a value under the given key.
  • RegExp A regular expression describes a text pattern.
  • RegExp.prototype.exec() Finds the next match with the pattern and returns it as an array with the groups and the index, input and groups properties.
  • RegExp.prototype.test() Returns true when the string contains a match with the pattern.
  • Set A collection in which each value occurs at most once.
  • Set.prototype.add() Adds a value to the Set.
  • Set.prototype.difference() Returns a new Set with the values that are in a, but not in b.
  • Set.prototype.has() Returns true when the Set contains the value.
  • Set.prototype.intersection() Returns a new Set with the values that are in both sets at once.
  • Set.prototype.isSubsetOf() Returns true when every value from a is also contained in b.
  • Set.prototype.union() Returns a new Set with all values that are in at least one of the sets.
  • WeakMap Similar to a Map, but only objects can be keys and the WeakMap does not keep them in memory – when the object disappears elsewhere, its entry disappears…

Date and time 23 entries

JSON and Intl 9 entries

  • Intl.Collator Creates a string comparer by the alphabet of a language.
  • Intl.DateTimeFormat Creates a date and time formatter.
  • Intl.ListFormat Joins the items of an array into a string with the correct commas and conjunction of the given language.
  • Intl.NumberFormat Creates a number formatter for the given language.
  • Intl.PluralRules Returns the plural category of a number by the rules of the language.
  • Intl.RelativeTimeFormat Formats a relative time (“5 minutes ago”, “tomorrow”) with the correct word forms of the given language.
  • Intl.Segmenter Splits text into parts by the rules of Unicode and the language: into characters as a person sees them (including combined emoji), into words or into sentences.
  • JSON.parse() Reads a string in the JSON format and returns the matching value – an object, an array, a string, a number, true/false or null.
  • JSON.stringify() Converts a value to a JSON string – for sending to a server, saving to localStorage or printing.

Syntax and operators 10 entries

  • Arrow functions (=>) A shorter way to write a function.
  • class A syntax for creating objects with shared methods. new Name() creates an instance, extends takes over the properties and methods of another class.
  • Destructuring A syntax that takes values out of an array or an object straight into variables.
  • Exponentiation (**) Returns the base raised to the exponent – the same as Math.pow(), but shorter.
  • instanceof Returns true when ClassName.prototype is in the prototype chain of the object – the object is an instance of the class or of a class derived from it.
  • Nullish coalescing operator (??) Returns the left side if it is neither null nor undefined, otherwise the right one.
  • Optional chaining (?.) When the value before ?. is null or undefined, the expression ends with the result undefined instead of an error.
  • Remainder (%) Returns the remainder after dividing a by the number b.
  • Spread syntax (...) Three dots before an array, a string or an object “expand” it into single elements – into a new array, into a new object or as function arguments.
  • typeof Returns a string with the type of the value: "string", "number", "bigint", "boolean", "undefined", "symbol", "function" or "object".

Functions and errors 7 entries

  • console.log() Prints values to the console (in the browser F12 → Console, in Node.js to the terminal).
  • Error An error object with the properties message, name (the type), stack (where it was created) and optionally cause (the original error).
  • Function.prototype.apply() Like call(), but the arguments are passed as one array.
  • Function.prototype.bind() Returns a new function that, when called, uses the given this and puts the given arguments before its own arguments.
  • Function.prototype.call() Calls the function right away, with this set to the first argument and with the other arguments passed one by one.
  • throw Throws an exception: it stops the execution of the function and looks for the nearest catch in the calling code.
  • try...catch Runs the code in the try block; when an error occurs in it, execution jumps to catch.

Promises and async/await 11 entries

  • async function A function marked async always returns a Promise: whatever return returns is the fulfillment value, a thrown error is the rejection.
  • await Pauses the async function until the Promise settles and returns its value.
  • Promise An object for the result of an asynchronous operation (loading data, a timer).
  • Promise.all() Waits for all Promises concurrently.
  • Promise.allSettled() Waits until all Promises end and returns an array of objects { status: 'fulfilled', value } or { status: 'rejected', reason }.
  • Promise.any() It is fulfilled with the result of the first successful Promise.
  • Promise.prototype.catch() Calls a function when the Promise (or any step of the chain before it) is rejected.
  • Promise.prototype.finally() Calls a function however the Promise ends.
  • Promise.race() It ends the same way as the first settled Promise – fulfilled or rejected.
  • Promise.prototype.then() Calls a function when the Promise is fulfilled and returns a new Promise with whatever the function returns.
  • Promise.withResolvers() Creates a Promise and returns it together with the resolve and reject functions.

Network, timers and storage 17 entries

  • AbortController Creates a signal that can cancel an operation.
  • AbortSignal.timeout() Returns a signal that aborts by itself after the given number of milliseconds.
  • clearTimeout() Cancels a timer created with setTimeout() if it has not run yet.
  • decodeURIComponent() The opposite of encodeURIComponent(): converts %XX sequences back to the original characters.
  • document.cookie Reading returns all available cookies as one string a=1; b=2.
  • encodeURIComponent() Converts characters that have a special meaning in an address or are not allowed there (a space, &, ?, /, accented letters…) to %XX codes.
  • fetch() Sends an HTTP request and returns a Promise with a Response object.
  • localStorage A key–string storage in the browser.
  • requestAnimationFrame() Calls a function just before the browser repaints the page (usually 60 times a second or more).
  • Response.json() Reads the whole body of the response and converts it from JSON to an object or array (like JSON.parse()).
  • Response.text() Reads the whole body of the response as a string (in UTF-8).
  • sessionStorage The same interface as localStorage, but the data belong to one tab only and disappear when it is closed.
  • setInterval() Calls a function repeatedly, each time after the interval, until you stop it with clearInterval(id).
  • setTimeout() Schedules one call of a function after the given number of milliseconds.
  • URL Splits an address into parts and lets you read and change them.
  • URL.canParse() Returns true when the address could be created with new URL().
  • URLSearchParams Works with the parameters of an address (the query string): reads them, changes them and joins them back into a string with correct encoding of characters.

DOM 40 entries

  • classList.add() Adds the given classes to an element.
  • classList.contains() Returns true when the element has the given class.
  • classList.remove() Removes the given classes from an element.
  • classList.toggle() When the element does not have the class, it adds it; when it has it, it removes it.
  • HTMLDialogElement.showModal() Opens a <dialog> as a modal window: the rest of the page is inactive, the focus moves into the dialog and the Escape key closes it.
  • Document.createElement() Creates a new element that is not on the page yet.
  • Document.getElementById() Returns the element with the given id, or null.
  • Document.querySelector() Returns the first element that matches a CSS selector, or null.
  • Document.querySelectorAll() Returns a list (NodeList) of all elements that match the selector, in the order in which they appear on the page.
  • Element.after() Inserts elements or texts into the parent right after the given element.
  • Element.animate() Runs an animation of an element according to the given keyframes – just like @keyframes in CSS, but controlled from JavaScript.
  • Element.append() Inserts one or more elements or texts as the last children of an element.
  • Element.before() Inserts elements or texts into the parent right before the given element.
  • Element.children Returns a live list (HTMLCollection) of the direct children that are elements.
  • Element.classList The list of classes of an element (DOMTokenList) with the methods add(), remove(), toggle(), contains() and replace().
  • Element.closest() Goes from the element up the page tree (the element, its parent, grandparent…) and returns the first one that matches the selector.
  • Element.getAttribute() Returns the value of an attribute exactly as it is written in the HTML, or null when the attribute is missing.
  • Element.getBoundingClientRect() Returns the rectangle of the element – x, y, width, height, top, left, right, bottom – in pixels relative to the visible part of the window (including…
  • Element.hasAttribute() Returns true when the element has the attribute – regardless of its value (even an empty one).
  • Element.innerHTML Reading returns the content of the element as HTML code.
  • Element.insertAdjacentHTML() Parses text as HTML and inserts it before the element, at the start, at the end or after the element.
  • Element.matches() Returns true when the element matches a CSS selector – including pseudo-classes such as :checked, :disabled or :hover.
  • Element.prepend() Inserts elements or texts as the first children of an element (before the existing content).
  • Element.remove() Removes the element (with its content) from the page.
  • Element.removeAttribute() Removes an attribute from an element.
  • Element.replaceWith() Removes the element and inserts the given elements or texts in its place.
  • Element.scrollIntoView() Scrolls the page (and all scrollable ancestors) so that the element gets into view.
  • Element.setAttribute() Sets an attribute to the given value (converting it to text), or adds it when it is missing.
  • Element.toggleAttribute() Switches an attribute without a value: when it is missing, it adds it (empty), when it exists, it removes it.
  • getComputedStyle() Returns the values of all CSS properties as the browser actually used them after processing the styles.
  • HTMLElement.dataset An object with all data-* attributes of an element.
  • HTMLElement.focus() Moves the focus to the element – typing on the keyboard then goes into it.
  • HTMLElement.hidden Corresponds to the hidden attribute.
  • HTMLElement.style Access to the style attribute of an element.
  • Node.appendChild() Inserts one node (an element, a text node, a fragment) as the last child and returns it.
  • Node.cloneNode() Returns a copy of the element with its attributes.
  • Node.parentElement Returns the parent of the element, if it is an element.
  • Node.textContent Reading returns the text of the element and all its descendants (without tags).
  • NodeList.prototype.forEach() Calls a function for every element of a NodeList (the result of querySelectorAll() or childNodes) – the same way as forEach() of an array.
  • HTMLTemplateElement.content The content of a <template> element is neither displayed nor run – it serves as a template. content is a DocumentFragment from which a copy is made for…

Events and forms 16 entries

  • EventTarget.addEventListener() Registers a function that is called every time the given event happens on the element (or on the window or document).
  • change event For text fields it fires when the user leaves the field with a changed value.
  • checkValidity() Validates fields by the rules in the HTML (required, type="email", min, max, pattern…).
  • click event Fires after a click with the primary mouse button, after a tap on a touch screen, and for buttons and links also after activation from the keyboard (Enter…
  • CustomEvent Creates a custom event that carries any data in the detail property.
  • EventTarget.dispatchEvent() Sends an event (Event, CustomEvent, KeyboardEvent…) to an element.
  • DOMContentLoaded event Fires as soon as the browser parses the whole HTML and builds the element tree – it does not wait for images and styles (the load event of the window waits…
  • Event.preventDefault() Cancels the default browser behavior for the event – the form is not submitted, the link does not open, the key does not type a character.
  • Event.stopPropagation() An event first runs on the target element and then bubbles up through all parents to the document. stopPropagation() stops it, so the listeners of the…
  • Event.target target is the element on which the event started (where the user clicked). currentTarget is the element whose listener is running right now.
  • FormData Reads all fields of a form (with the name attribute) as name–value pairs.
  • HTMLInputElement.value The current value of a form field as a string.
  • input event Fires right after every change of the value of a field – after typing a character, pasting text, choosing from a list or checking a box.
  • keydown event Fires when a key is pressed (and repeatedly while it is held down). e.key is the meaning of the key ('a', 'Enter', 'Escape'), e.code the physical key ('KeyA')…
  • EventTarget.removeEventListener() Removes a listener added with addEventListener().
  • submit event Fires when the user submits a form – with a button or with the Enter key in a field.

Browser and observers 10 entries

  • navigator.clipboard.writeText() Writes text to the clipboard and returns a Promise.
  • crypto.randomUUID() Returns a random version 4 UUID (36 characters, for example 3b241101-e2bb-4255-8caf-4136c566a962) from a cryptographically secure generator.
  • history.pushState() Adds a new entry with a different URL (on the same domain) to the browser history – the page does not reload.
  • IntersectionObserver Calls a function when an observed element enters or leaves the visible part of the window (or of another element).
  • window.location Describes the URL of the current page.
  • window.matchMedia() Evaluates an @media query from CSS and returns an object with the matches property.
  • MutationObserver Calls a function after changes in the page tree – when elements are added or removed, an attribute or text changes.
  • navigator.language Returns the language set in the browser as a BCP 47 code, for example en-US or de-DE. navigator.languages returns all languages in the order of preference.
  • ResizeObserver Calls a function when the size of the observed element changes – because of the window, the content or CSS.
  • window.scrollTo() Scrolls the page so that the given point is at the top left. scrollBy() scrolls by the given distance from the current position.