diff --git a/src/WebView.js b/src/WebView.js index 92e0eeb..a1b5e4e 100644 --- a/src/WebView.js +++ b/src/WebView.js @@ -1,6 +1,8 @@ import WebKit from "gi://WebKit"; import GObject from "gi://GObject"; import GLib from "gi://GLib"; +import Gio from "gi://Gio"; +import { decode } from "./util.js"; import Template from "./WebView.blp" with { type: "uri" }; @@ -32,7 +34,19 @@ class WebView extends WebKit.WebView { #disablePageSidebar() { const user_content_manager = this.get_user_content_manager(); - const stylesheet = new WebKit.UserStyleSheet( + const data = Gio.File.new_for_path("src/devdoc_styles.css").load_contents( + null, + )[1]; + const css = decode(data); + let stylesheet = new WebKit.UserStyleSheet( + css, // source + WebKit.UserContentInjectedFrames.ALL_FRAMES, // injected_frames + WebKit.UserStyleLevel.USER, // level + null, + null, + ); + user_content_manager.add_style_sheet(stylesheet); + stylesheet = new WebKit.UserStyleSheet( ".devhelp-hidden { display: none; }", // source WebKit.UserContentInjectedFrames.ALL_FRAMES, // injected_frames WebKit.UserStyleLevel.USER, // level diff --git a/src/devdoc_styles.css b/src/devdoc_styles.css new file mode 100644 index 0000000..6784a08 --- /dev/null +++ b/src/devdoc_styles.css @@ -0,0 +1,6563 @@ +/*! + * Copyright 2013-2023 Thibaut Courouble and other contributors + * + * This source code is licensed under the terms of the Mozilla + * Public License, v. 2.0, a copy of which may be obtained at: + * http://mozilla.org/MPL/2.0/ + */ +html._theme-default { + --absolute: black; + --documentBackground: #f3f3f3; + --contentBackground: #fff; + --textColor: #333; + --textColorLight: #666; + --textColorLighter: #888; + --externalsBackground: #fff; + --inputFocusBorder: #35b5f4; + --focusBackground: #e5e5e5; + --focusBorder: #d4d4d4; + --focusText: #000; + --loadingText: #ccc; + --selectionBackground: #398df0; + --selectionBorder: #196fc2; + --highlightBackground: #fffdcd; + --linkColor: #3377c0; + --linkColorHover: #2f6cb6; + --linkTextDecoration: none; + --headerBackground: #eee; + --headerBorder: #d7d7d7; + --searchTagBackground: #e1e1e1; + --searchBorder: #d2d2d2; + --sidebarBackground: #f9f9f9; + --transparentSidebarBackground: rgba(249, 249, 249, 0); + --sidebarBorder: #e1e1e1; + --scrollbarColor: #ccc; + --scrollbarColorHover: #999; + --pathBackground: var(--sidebarBackground); + --pathBorder: var(--sidebarBorder); + --noticeBackground: #faf9e2; + --noticeBorder: #e2e2c1; + --boxBackground: #fafafa; + --boxBorder: #d8d8d8; + --boxBorderLight: #e5e5e5; + --boxHeaderColor: var(--textColor); + --boxHeaderBackground: #f5f5f5; + --noteBackground: #f8f8dd; + --noteBorder: #d3d952; + --noteGreenBackground: #e7f8e1; + --noteGreenBorder: #89da70; + --noteBlueBackground: #d4f3fd; + --noteBlueBorder: #94bbeb; + --noteOrangeBackground: #fbe6d1; + --noteOrangeBorder: #ec8b01; + --noteRedBackground: #fed5d3; + --noteRedBorder: #dc7874; + --labelBackground: #f4f4f4; + --notifBackground: rgba(51, 51, 51, 0.85); + --notifBorder: none; + --tipBackground: rgba(255, 253, 205, 0.95); + --tipBorder: 1px solid #e7dca9; +} +html._theme-dark { + --absolute: white; + --documentBackground: #222; + --contentBackground: #33373a; + --textColor: #cbd0d0; + --textColorLight: #9da5ad; + --textColorLighter: #77787a; + --externalsBackground: #fff; + --inputFocusBorder: transparent; + --focusBackground: #3f4042; + --focusBorder: #000; + --focusText: #f7f2f2; + --loadingText: #5d6164; + --selectionBackground: #007acc; + --selectionBorder: #000; + --highlightBackground: #64675f; + --linkColor: var(--textColor); + --linkColorHover: white; + --linkTextDecoration: underline; + --headerBackground: #1c1c1c; + --headerBorder: #000; + --searchTagBackground: #0f0f0f; + --searchBorder: black; + --sidebarBackground: #24282a; + --transparentSidebarBackground: rgba(36, 40, 42, 0); + --sidebarBorder: #000; + --scrollbarColor: #6c6c6f; + --scrollbarColorHover: #949697; + --pathBackground: var(--headerBackground); + --pathBorder: var(--headerBorder); + --noticeBackground: var(--sidebarBackground); + --noticeBorder: var(--sidebarBorder); + --boxBackground: var(--sidebarBackground); + --boxBorder: var(--headerBorder); + --boxBorderLight: var(--headerBorder); + --boxHeaderColor: #dbe4e4; + --boxHeaderBackground: var(--sidebarBackground); + --noteBackground: #45474b; + --noteBorder: #000; + --noteGreenBackground: #284a2a; + --noteGreenBorder: #000; + --noteBlueBackground: #2a4151; + --noteBlueBorder: #000; + --noteOrangeBackground: #563322; + --noteOrangeBorder: #000; + --noteRedBackground: #603033; + --noteRedBorder: #000; + --labelBackground: var(--boxBackground); + --notifBackground: rgba(85, 85, 85, 0.95); + --notifBorder: 1px solid #000; + --tipBackground: var(--notifBackground); + --tipBorder: var(--notifBorder); +} +html { + --baseFont: -apple-system, BlinkMacSystemFont, San Francisco, Segoe UI, Roboto, + Ubuntu, Helvetica Neue, Arial, sans-serif; + --monoFont: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, + Courier, monospace; + --boldFontWeight: 500; + --bolderFontWeight: 600; + --textColorRed: #f44336; + --splashText: var(--loadingText); + --selectionText: #fff; + --transparentSelectionText: rgba(255, 255, 255, 0.9); + --notifColor: #fff; + --notifColorLight: #ccc; + --maxWidth: 80rem; + --headerHeight: 3rem; + --sidebarWidth: 20rem; + --sidebarMediumWidth: 16rem; + --focusBackground: #e5e5e5; + --focusBorder: #d4d4d4; + --focusText: #000; + --contentZ: 1; + --sidebarZ: 2; + --headerZ: 3; + --noticeZ: 4; + --hoverZ: 5; +} +._header-btn > svg, +._search > svg, +._search-clear > svg, +._notif-close > svg, +._settings-btn > svg, +._pre-clip > svg { + display: inline-block; + vertical-align: top; + width: 1rem; + height: 1rem; + pointer-events: none; + fill: currentColor; +} +._list-item:before, +._docs-name:before, +._path-item:first-child:before { + content: ""; + display: block; + width: 1rem; + height: 1rem; + background-image: url("/assets/sprites/docs-73bdf7a2fe73f98a000193f664bf8a9bb459730b0c60fb6c84a4f9d742fb202e.png"); + background-size: 15rem 15rem; +} +@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) { + ._list-item:before, + ._docs-name:before, + ._path-item:first-child:before { + background-image: url("/assets/sprites/docs@2x-32fdd54fc149c9fceac698929db8f41d85036cf099df87daff159162e329d69e.png"); + } +} +html._theme-dark ._icon-apache_http_server:before, +html._theme-dark ._icon-astro:before, +html._theme-dark ._icon-backbone:before, +html._theme-dark ._icon-coffeescript:before, +html._theme-dark ._icon-crystal:before, +html._theme-dark ._icon-date_fns:before, +html._theme-dark ._icon-django_rest_framework:before, +html._theme-dark ._icon-eigen3:before, +html._theme-dark ._icon-fastapi:before, +html._theme-dark ._icon-gnu_make:before, +html._theme-dark ._icon-gnu_cobol:before, +html._theme-dark ._icon-handlebars:before, +html._theme-dark ._icon-haskell:before, +html._theme-dark ._icon-immutable:before, +html._theme-dark ._icon-influxdata:before, +html._theme-dark ._icon-jinja:before, +html._theme-dark ._icon-joi:before, +html._theme-dark ._icon-jq:before, +html._theme-dark ._icon-julia:before, +html._theme-dark ._icon-kubectl:before, +html._theme-dark ._icon-latex:before, +html._theme-dark ._icon-lua:before, +html._theme-dark ._icon-markdown:before, +html._theme-dark ._icon-meteor:before, +html._theme-dark ._icon-moment:before, +html._theme-dark ._icon-nim:before, +html._theme-dark ._icon-nokogiri:before, +html._theme-dark ._icon-pandas:before, +html._theme-dark ._icon-prettier:before, +html._theme-dark ._icon-ramda:before, +html._theme-dark ._icon-react:before, +html._theme-dark ._icon-react_router:before, +html._theme-dark ._icon-redux:before, +html._theme-dark ._icon-rust:before, +html._theme-dark ._icon-saltstack:before, +html._theme-dark ._icon-terraform:before, +html._theme-dark ._icon-underscore:before, +html._theme-dark ._icon-vulkan:before, +html._theme-dark ._icon-wagtail:before, +html._theme-dark ._icon-wordpress:before { + filter: invert(100%) grayscale(100%); + -webkit-filter: invert(100%) grayscale(100%); +} +._icon-angular:before { + background-position: -0rem -0rem; +} +._icon-angularjs:before { + background-position: -1rem -0rem; +} +._icon-ansible:before { + background-position: -2rem -0rem; +} +._icon-apache_http_server:before { + background-position: -3rem -0rem; +} +._icon-apache_pig:before { + background-position: -4rem -0rem; +} +._icon-astro:before { + background-position: -5rem -0rem; +} +._icon-async:before { + background-position: -6rem -0rem; +} +._icon-axios:before { + background-position: -7rem -0rem; +} +._icon-babel:before { + background-position: -8rem -0rem; +} +._icon-backbone:before { + background-position: -9rem -0rem; +} +._icon-bash:before { + background-position: -10rem -0rem; +} +._icon-bluebird:before { + background-position: -11rem -0rem; +} +._icon-bootstrap:before { + background-position: -12rem -0rem; +} +._icon-bottle:before { + background-position: -13rem -0rem; +} +._icon-bower:before { + background-position: -14rem -0rem; +} +._icon-c:before { + background-position: -0rem -1rem; +} +._icon-cpp:before { + background-position: -1rem -1rem; +} +._icon-cakephp:before { + background-position: -2rem -1rem; +} +._icon-chai:before { + background-position: -3rem -1rem; +} +._icon-chef:before { + background-position: -4rem -1rem; +} +._icon-clojure:before { + background-position: -5rem -1rem; +} +._icon-cmake:before { + background-position: -6rem -1rem; +} +._icon-codeception:before { + background-position: -7rem -1rem; +} +._icon-codeceptjs:before { + background-position: -8rem -1rem; +} +._icon-codeigniter:before { + background-position: -9rem -1rem; +} +._icon-coffeescript:before { + background-position: -10rem -1rem; +} +._icon-composer:before { + background-position: -11rem -1rem; +} +._icon-cordova:before { + background-position: -12rem -1rem; +} +._icon-crystal:before { + background-position: -13rem -1rem; +} +._icon-css:before { + background-position: -14rem -1rem; +} +._icon-cypress:before { + background-position: -0rem -2rem; +} +._icon-d:before { + background-position: -1rem -2rem; +} +._icon-d3:before { + background-position: -2rem -2rem; +} +._icon-dart:before { + background-position: -3rem -2rem; +} +._icon-date_fns:before { + background-position: -4rem -2rem; +} +._icon-deno:before { + background-position: -5rem -2rem; +} +._icon-django:before { + background-position: -6rem -2rem; +} +._icon-django_rest_framework:before { + background-position: -7rem -2rem; +} +._icon-docker:before { + background-position: -8rem -2rem; +} +._icon-dojo:before { + background-position: -9rem -2rem; +} +._icon-drupal:before { + background-position: -10rem -2rem; +} +._icon-eigen3:before { + background-position: -11rem -2rem; +} +._icon-electron:before { + background-position: -12rem -2rem; +} +._icon-elisp:before { + background-position: -13rem -2rem; +} +._icon-elixir:before { + background-position: -14rem -2rem; +} +._icon-ember:before { + background-position: -0rem -3rem; +} +._icon-enzyme:before { + background-position: -5rem -7rem; +} +._icon-erlang:before { + background-position: -1rem -3rem; +} +._icon-esbuild:before { + background-position: -2rem -3rem; +} +._icon-eslint:before { + background-position: -3rem -3rem; +} +._icon-express:before { + background-position: -4rem -3rem; +} +._icon-falcon:before { + background-position: -5rem -3rem; +} +._icon-fastapi:before { + background-position: -6rem -3rem; +} +._icon-fish:before { + background-position: -7rem -3rem; +} +._icon-flask:before { + background-position: -8rem -3rem; +} +._icon-flow:before { + background-position: -9rem -3rem; +} +._icon-fluture:before { + background-position: -10rem -3rem; +} +._icon-gcc:before { + background-position: -11rem -3rem; +} +._icon-git:before { + background-position: -12rem -3rem; +} +._icon-gnu_fortran:before { + background-position: -13rem -3rem; +} +._icon-gnu_make:before { + background-position: -14rem -3rem; +} +._icon-gnu_cobol:before { + background-position: -0rem -4rem; +} +._icon-gnuplot:before { + background-position: -1rem -4rem; +} +._icon-go:before { + background-position: -2rem -4rem; +} +._icon-godot:before { + background-position: -3rem -4rem; +} +._icon-graphite:before { + background-position: -5rem -7rem; +} +._icon-groovy:before { + background-position: -4rem -4rem; +} +._icon-grunt:before { + background-position: -5rem -4rem; +} +._icon-gtk:before { + background-position: -6rem -4rem; +} +._icon-handlebars:before { + background-position: -7rem -4rem; +} +._icon-hapi:before { + background-position: -8rem -4rem; +} +._icon-haproxy:before { + background-position: -9rem -4rem; +} +._icon-haskell:before { + background-position: -10rem -4rem; +} +._icon-haxe:before { + background-position: -11rem -4rem; +} +._icon-homebrew:before { + background-position: -12rem -4rem; +} +._icon-html:before { + background-position: -13rem -4rem; +} +._icon-http:before { + background-position: -14rem -4rem; +} +._icon-i3:before { + background-position: -0rem -5rem; +} +._icon-immutable:before { + background-position: -1rem -5rem; +} +._icon-influxdata:before { + background-position: -2rem -5rem; +} +._icon-jasmine:before { + background-position: -3rem -5rem; +} +._icon-javascript:before { + background-position: -4rem -5rem; +} +._icon-jekyll:before { + background-position: -5rem -5rem; +} +._icon-jest:before { + background-position: -6rem -5rem; +} +._icon-jinja:before { + background-position: -7rem -5rem; +} +._icon-joi:before { + background-position: -8rem -5rem; +} +._icon-jq:before { + background-position: -9rem -5rem; +} +._icon-jquery:before { + background-position: -10rem -5rem; +} +._icon-jquerymobile:before { + background-position: -11rem -5rem; +} +._icon-jqueryui:before { + background-position: -12rem -5rem; +} +._icon-jsdoc:before { + background-position: -5rem -7rem; +} +._icon-julia:before { + background-position: -13rem -5rem; +} +._icon-knockout:before { + background-position: -14rem -5rem; +} +._icon-koa:before { + background-position: -5rem -7rem; +} +._icon-kotlin:before { + background-position: -0rem -6rem; +} +._icon-kubectl:before { + background-position: -1rem -6rem; +} +._icon-kubernetes:before { + background-position: -2rem -6rem; +} +._icon-laravel:before { + background-position: -3rem -6rem; +} +._icon-latex:before { + background-position: -4rem -6rem; +} +._icon-leaflet:before { + background-position: -5rem -6rem; +} +._icon-less:before { + background-position: -6rem -6rem; +} +._icon-liquid:before { + background-position: -7rem -6rem; +} +._icon-lodash:before { + background-position: -8rem -6rem; +} +._icon-lua:before { + background-position: -9rem -6rem; +} +._icon-love:before { + background-position: -10rem -6rem; +} +._icon-mariadb:before { + background-position: -11rem -6rem; +} +._icon-marionette:before { + background-position: -12rem -6rem; +} +._icon-markdown:before { + background-position: -13rem -6rem; +} +._icon-matplotlib:before { + background-position: -14rem -6rem; +} +._icon-meteor:before { + background-position: -0rem -7rem; +} +._icon-mocha:before { + background-position: -1rem -7rem; +} +._icon-modernizr:before { + background-position: -2rem -7rem; +} +._icon-moment:before { + background-position: -3rem -7rem; +} +._icon-moment_timezone:before { + background-position: -4rem -7rem; +} +._icon-mongoose:before { + background-position: -5rem -7rem; +} +._icon-nginx:before { + background-position: -6rem -7rem; +} +._icon-nginx_lua_module:before { + background-position: -5rem -7rem; +} +._icon-nim:before { + background-position: -7rem -7rem; +} +._icon-nix:before { + background-position: -8rem -7rem; +} +._icon-node:before { + background-position: -9rem -7rem; +} +._icon-nokogiri:before { + background-position: -10rem -7rem; +} +._icon-npm:before { + background-position: -11rem -7rem; +} +._icon-numpy:before { + background-position: -12rem -7rem; +} +._icon-nushell:before { + background-position: -13rem -7rem; +} +._icon-ocaml:before { + background-position: -14rem -7rem; +} +._icon-octave:before { + background-position: -0rem -8rem; +} +._icon-openjdk:before { + background-position: -1rem -8rem; +} +._icon-opentsdb:before { + background-position: -2rem -8rem; +} +._icon-padrino:before { + background-position: -3rem -8rem; +} +._icon-pandas:before { + background-position: -4rem -8rem; +} +._icon-perl:before { + background-position: -5rem -8rem; +} +._icon-phalcon:before { + background-position: -6rem -8rem; +} +._icon-phaser:before { + background-position: -7rem -8rem; +} +._icon-phoenix:before { + background-position: -8rem -8rem; +} +._icon-php:before { + background-position: -9rem -8rem; +} +._icon-phpunit:before { + background-position: -10rem -8rem; +} +._icon-point_cloud_library:before { + background-position: -11rem -8rem; +} +._icon-pony:before { + background-position: -12rem -8rem; +} +._icon-postgresql:before { + background-position: -13rem -8rem; +} +._icon-prettier:before { + background-position: -14rem -8rem; +} +._icon-pug:before { + background-position: -0rem -9rem; +} +._icon-puppeteer:before { + background-position: -1rem -9rem; +} +._icon-pygame:before { + background-position: -2rem -9rem; +} +._icon-python:before { + background-position: -3rem -9rem; +} +._icon-pytorch:before { + background-position: -4rem -9rem; +} +._icon-q:before { + background-position: -5rem -9rem; +} +._icon-qt:before { + background-position: -6rem -9rem; +} +._icon-qunit:before { + background-position: -7rem -9rem; +} +._icon-r:before { + background-position: -8rem -9rem; +} +._icon-ramda:before { + background-position: -9rem -9rem; +} +._icon-react:before { + background-position: -10rem -9rem; +} +._icon-react_bootstrap:before { + background-position: -11rem -9rem; +} +._icon-react_native:before { + background-position: -12rem -9rem; +} +._icon-react_router:before { + background-position: -13rem -9rem; +} +._icon-reactivex:before { + background-position: -14rem -9rem; +} +._icon-redis:before { + background-position: -0rem -10rem; +} +._icon-redux:before { + background-position: -1rem -10rem; +} +._icon-relay:before { + background-position: -2rem -10rem; +} +._icon-requests:before { + background-position: -3rem -10rem; +} +._icon-requirejs:before { + background-position: -4rem -10rem; +} +._icon-rethinkdb:before { + background-position: -5rem -10rem; +} +._icon-ruby:before { + background-position: -6rem -10rem; +} +._icon-minitest:before { + background-position: -5rem -7rem; +} +._icon-rails:before { + background-position: -7rem -10rem; +} +._icon-rust:before { + background-position: -8rem -10rem; +} +._icon-rxjs:before { + background-position: -9rem -10rem; +} +._icon-saltstack:before { + background-position: -10rem -10rem; +} +._icon-sanctuary:before { + background-position: -11rem -10rem; +} +._icon-sanctuary_def:before { + background-position: -12rem -10rem; +} +._icon-sanctuary_type_classes:before { + background-position: -13rem -10rem; +} +._icon-sass:before { + background-position: -14rem -10rem; +} +._icon-scala:before { + background-position: -0rem -11rem; +} +._icon-scikit_image:before { + background-position: -1rem -11rem; +} +._icon-scikit_learn:before { + background-position: -2rem -11rem; +} +._icon-sequelize:before { + background-position: -3rem -11rem; +} +._icon-sinon:before { + background-position: -4rem -11rem; +} +._icon-socketio:before { + background-position: -5rem -11rem; +} +._icon-spring_boot:before { + background-position: -6rem -11rem; +} +._icon-sqlite:before { + background-position: -7rem -11rem; +} +._icon-statsmodels:before { + background-position: -8rem -11rem; +} +._icon-browser_support_tables:before { + background-position: -5rem -7rem; +} +._icon-svelte:before { + background-position: -9rem -11rem; +} +._icon-svg:before { + background-position: -10rem -11rem; +} +._icon-symfony:before { + background-position: -11rem -11rem; +} +._icon-tailwindcss:before { + background-position: -12rem -11rem; +} +._icon-tcl_tk:before { + background-position: -5rem -7rem; +} +._icon-tensorflow:before { + background-position: -13rem -11rem; +} +._icon-tensorflow_cpp:before { + background-position: -14rem -11rem; +} +._icon-terraform:before { + background-position: -0rem -12rem; +} +._icon-trio:before { + background-position: -1rem -12rem; +} +._icon-twig:before { + background-position: -2rem -12rem; +} +._icon-typescript:before { + background-position: -3rem -12rem; +} +._icon-underscore:before { + background-position: -4rem -12rem; +} +._icon-vagrant:before { + background-position: -5rem -12rem; +} +._icon-varnish:before { + background-position: -6rem -12rem; +} +._icon-vite:before { + background-position: -7rem -12rem; +} +._icon-vitest:before { + background-position: -8rem -12rem; +} +._icon-vue:before { + background-position: -9rem -12rem; +} +._icon-vue_router:before { + background-position: -10rem -12rem; +} +._icon-vueuse:before { + background-position: -11rem -12rem; +} +._icon-vuex:before { + background-position: -12rem -12rem; +} +._icon-vulkan:before { + background-position: -13rem -12rem; +} +._icon-wagtail:before { + background-position: -14rem -12rem; +} +._icon-dom:before { + background-position: -0rem -13rem; +} +._icon-web_extensions:before { + background-position: -5rem -7rem; +} +._icon-webpack:before { + background-position: -1rem -13rem; +} +._icon-werkzeug:before { + background-position: -2rem -13rem; +} +._icon-wordpress:before { + background-position: -3rem -13rem; +} +._icon-xslt_xpath:before { + background-position: -5rem -7rem; +} +._icon-yarn:before { + background-position: -4rem -13rem; +} +._icon-yii:before { + background-position: -5rem -13rem; +} +._icon-zig:before { + background-position: -6rem -13rem; +} +input, +button, +._app, +._header, +._search, +._notif, +._sidebar, +._list, +._list-hover.clone, +._settings-legend, +._settings-btn, +._container, +._content, +._page iframe, +._fail, +._coffeescript > .code > pre { + -moz-box-sizing: border-box; + box-sizing: border-box; +} +._search-clear, +._notif-close, +label, +._header, +._notif, +._sidebar, +._splash-title, +._rdoc a.method-click-advice, +._scala .source-link { + -webkit-user-select: none; + -moz-user-select: -moz-none; + -ms-user-select: none; + user-select: none; +} +._search-clear, +._notif-close { + white-space: nowrap; + overflow: hidden; + text-indent: 100%; + word-wrap: normal; + overflow-wrap: normal; +} +._search-tag, +._list-item, +._list-text { + overflow: hidden; + white-space: nowrap; + word-wrap: normal; + overflow-wrap: normal; + text-overflow: ellipsis; +} +pre, +._jq .manual-example table td, +._redis > .example, +._scala .related-types, +._toc, +._docs-links, +._bootstrap a.thumbnail, +._scala .links { + background: var(--boxBackground); + border: 1px solid var(--boxBorder); + border-radius: 3px; +} +._block-heading, +._simple h2, +._angular h2, +._apache h2, +._async h2, +._bootstrap h2, +._cakephp h2, +._codeception h2, +._coffeescript h2, +._cordova h2, +._crystal h2, +._cypress h2, +._dart h2, +._dojo h2, +._elixir h2, +._ember h2, +._erlang h2, +._express h2, +._fluture h2, +._github h2, +._gnuplot h2, +._go h2, +._graphite h2, +._hapi h2, +._jekyll h2, +._joi h2, +._jq h2, +._julia h2, +._kubectl h2, +._kubernetes h2, +._liquid h2, +._love h2, +._lua h2, +._mariadb h2, +._meteor h2, +._npm h2, +._nushell h2, +._octave h2, +._openjdk h2, +._perl h2, +._phalcon h2, +._phaser h2, +._phpunit h2, +._pug h2, +._pygame h2, +._qt h2, +._ramda h2, +._react_native h2, +._reactivex h2, +._rethinkdb h2, +._rubydoc h2, +._rust h2, +._rxjs h2, +._sanctuary h2, +._sanctuary_def h2, +._sanctuary_type_classes h2, +._scala h2, +._sinon h2, +._sphinx_simple h2, +._sqlite h2, +._tcl_tk h2, +._tensorflow h2, +._terraform h2, +._typescript h2, +._vue h2, +._webpack h2, +._wordpress h2, +._yard h2, +._yii h2, +._angularjs h2, +._cppref > h2, +._cppref > h3, +._clojure h2:not([id]), +._d h2, +._d3 > h2, +._drupal h3, +._fastapi > h2, +._git > h2, +._groovy h2, +._gtk h2, +._haproxy h2, +._haskell-api > h2, +._jasmine .subsection-title, +._jasmine h2, +._jquery .section-title, +._jquery .entry-wrapper > h3, +._jquery .underline, +._knockout > h2, +._kotlin h2, +._laravel h2, +._mdn > h2, +._mkdocs h2, +._modernizr h2, +._moment > h2, +._nginx h4, +._node > h2, +._octave .footnotes-heading, +._php h2, +._php h3.title, +._postgres h2, +._rdoc > .description > h2, +._rdoc header > h3, +._rdoc > h2, +._redis > h2, +._rfc-pre > h2, +._python h2, +._sphinx h2, +._support_tables h2, +._underscore > h2, +._pre-heading, +._angular .pre-title, +._bootstrap div.bs-example, +._ember .pre-title, +._liquid p.code-label, +._rxjs .pre-title, +th, +._bootstrap p.bs-example { + color: var(--boxHeaderColor); + background: var(--boxHeaderBackground); + border: 1px solid var(--boxBorder); + border-radius: 3px; +} +._block-heading, +._simple h2, +._angular h2, +._apache h2, +._async h2, +._bootstrap h2, +._cakephp h2, +._codeception h2, +._coffeescript h2, +._cordova h2, +._crystal h2, +._cypress h2, +._dart h2, +._dojo h2, +._elixir h2, +._ember h2, +._erlang h2, +._express h2, +._fluture h2, +._github h2, +._gnuplot h2, +._go h2, +._graphite h2, +._hapi h2, +._jekyll h2, +._joi h2, +._jq h2, +._julia h2, +._kubectl h2, +._kubernetes h2, +._liquid h2, +._love h2, +._lua h2, +._mariadb h2, +._meteor h2, +._npm h2, +._nushell h2, +._octave h2, +._openjdk h2, +._perl h2, +._phalcon h2, +._phaser h2, +._phpunit h2, +._pug h2, +._pygame h2, +._qt h2, +._ramda h2, +._react_native h2, +._reactivex h2, +._rethinkdb h2, +._rubydoc h2, +._rust h2, +._rxjs h2, +._sanctuary h2, +._sanctuary_def h2, +._sanctuary_type_classes h2, +._scala h2, +._sinon h2, +._sphinx_simple h2, +._sqlite h2, +._tcl_tk h2, +._tensorflow h2, +._terraform h2, +._typescript h2, +._vue h2, +._webpack h2, +._wordpress h2, +._yard h2, +._yii h2, +._angularjs h2, +._cppref > h2, +._cppref > h3, +._clojure h2:not([id]), +._d h2, +._d3 > h2, +._drupal h3, +._fastapi > h2, +._git > h2, +._groovy h2, +._gtk h2, +._haproxy h2, +._haskell-api > h2, +._jasmine .subsection-title, +._jasmine h2, +._jquery .section-title, +._jquery .entry-wrapper > h3, +._jquery .underline, +._knockout > h2, +._kotlin h2, +._laravel h2, +._mdn > h2, +._mkdocs h2, +._modernizr h2, +._moment > h2, +._nginx h4, +._node > h2, +._octave .footnotes-heading, +._php h2, +._php h3.title, +._postgres h2, +._rdoc > .description > h2, +._rdoc header > h3, +._rdoc > h2, +._redis > h2, +._rfc-pre > h2, +._python h2, +._sphinx h2, +._support_tables h2, +._underscore > h2 { + line-height: 1.25rem; + margin: 2em 0 1em; + padding: 0.5em 0.75em; + font-size: 1rem; + overflow: hidden; +} +._pre-heading, +._angular .pre-title, +._bootstrap div.bs-example, +._ember .pre-title, +._liquid p.code-label, +._rxjs .pre-title { + margin: 0; + padding: 0.375rem 0.625rem; + font-size: inherit; + font-weight: normal; + line-height: 1.5; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} +._pre-heading + pre, +._angular .pre-title + pre, +._bootstrap div.bs-example + pre, +._ember .pre-title + pre, +._liquid p.code-label + pre, +._rxjs .pre-title + pre { + border-top-left-radius: 0; + border-top-right-radius: 0; + border-top: 0; + margin-top: 0; +} +._intro-message, +._note, +._simple blockquote, +._angular blockquote, +._apache blockquote, +._async blockquote, +._bootstrap blockquote, +._cakephp blockquote, +._codeception blockquote, +._coffeescript blockquote, +._cordova blockquote, +._crystal blockquote, +._cypress blockquote, +._dart blockquote, +._dojo blockquote, +._elixir blockquote, +._ember blockquote, +._erlang blockquote, +._express blockquote, +._fluture blockquote, +._github blockquote, +._gnuplot blockquote, +._go blockquote, +._graphite blockquote, +._hapi blockquote, +._jekyll blockquote, +._joi blockquote, +._jq blockquote, +._julia blockquote, +._kubectl blockquote, +._kubernetes blockquote, +._liquid blockquote, +._love blockquote, +._lua blockquote, +._mariadb blockquote, +._meteor blockquote, +._npm blockquote, +._nushell blockquote, +._octave blockquote, +._openjdk blockquote, +._perl blockquote, +._phalcon blockquote, +._phaser blockquote, +._phpunit blockquote, +._pug blockquote, +._pygame blockquote, +._qt blockquote, +._ramda blockquote, +._react_native blockquote, +._reactivex blockquote, +._rethinkdb blockquote, +._rubydoc blockquote, +._rust blockquote, +._rxjs blockquote, +._sanctuary blockquote, +._sanctuary_def blockquote, +._sanctuary_type_classes blockquote, +._scala blockquote, +._sinon blockquote, +._sphinx_simple blockquote, +._sqlite blockquote, +._tcl_tk blockquote, +._tensorflow blockquote, +._terraform blockquote, +._typescript blockquote, +._vue blockquote, +._webpack blockquote, +._wordpress blockquote, +._yard blockquote, +._yii blockquote, +._angular .breadcrumbs, +._angularjs .alert, +._apache .note, +._apache .warning, +._bootstrap .bs-callout, +._cppref .fmbox, +._cakephp .info, +._codeception .warning, +._codeception .alert, +._cordova .alert, +._d3 blockquote, +._drupal .signature, +._erlang .note, +._erlang .warning, +._express .doc-box, +._fastapi .admonition, +._git > .callout, +._git > h1 + .sectionbody, +._gtk .note, +._gtk .warning, +._haskell-api .warning, +._jquery #quick-nav, +._jquery .warning, +._julia .footnote, +._julia .note, +._knockout .liveExample, +._knockout blockquote, +._kotlin .api-docs-breadcrumbs, +._laravel blockquote, +._love .note, +._mariadb .graybox, +._mariadb .product, +._mdn > .note, +._mdn .notecard, +._mdn .notice, +._mdn .warning, +._mdn .overheadIndicator, +._mdn .blockIndicator, +._mdn .syntaxbox, +._mdn .twopartsyntaxbox, +._mdn .inheritsbox, +._mdn .eval:first-of-type, +._mdn .htmlelt, +._mdn .cssprop, +._meteor .note, +._meteor .warning, +._meteor .subtitle-page, +._mkdocs blockquote, +._modernizr blockquote, +._nginx .note, +._node .api_stability_0, +._node .api_stability_1, +._node .api_stability_2, +._node .api_stability_3, +._node .api_stability_4, +._node .api_stability_5, +._openjdk > .inheritance, +._openjdk > ul.inheritance, +._phaser .deprecated-notice, +._php .classsynopsis, +._php .description > .constructorsynopsis, +._php .description > .methodsynopsis, +._php .description > .fieldsynopsis, +._php blockquote.note, +._php div.warning, +._php div.caution, +._php div.tip, +._phpunit .warning, +._phpunit .alert, +._postgres blockquote.note, +._postgres blockquote.important, +._postgres blockquote.tip, +._postgres blockquote.caution, +._pug .alert, +._pygame .line-block, +._pygame .warning, +._rdoc > .meta, +._rdoc .note, +._rdoc .info, +._rdoc .warning, +._react_native .deprecated, +._redis > .metadata, +._rubydoc p.note, +._rust div.information, +._rust div.important-traits, +._rxjs .breadcrumbs, +._python .note, +._sphinx .note, +._python .admonition, +._sphinx .admonition, +._python div.versionadded, +._sphinx div.versionadded, +._python div.versionchanged, +._sphinx div.versionchanged, +._python .deprecated-removed, +._sphinx .deprecated-removed, +._python .deprecated, +._sphinx .deprecated, +._python .topic, +._sphinx .topic, +._sphinx_simple .admonition, +._sqlite .todo, +._terraform .note, +._terraform .alert, +._vue p.tip, +._vue .custom-block, +._wordpress .callout-warning, +._wordpress .callout-alert { + margin: 1.5rem 0; + padding: 0.5rem 0.875rem; + background: var(--noteBackground); + border: 1px solid var(--noteBorder); + border-radius: 3px; +} +._simple h3, +._angular h3, +._apache h3, +._async h3, +._bootstrap h3, +._cakephp h3, +._codeception h3, +._coffeescript h3, +._cordova h3, +._crystal h3, +._cypress h3, +._dart h3, +._dojo h3, +._elixir h3, +._ember h3, +._erlang h3, +._express h3, +._fluture h3, +._github h3, +._gnuplot h3, +._go h3, +._graphite h3, +._hapi h3, +._jekyll h3, +._joi h3, +._jq h3, +._julia h3, +._kubectl h3, +._kubernetes h3, +._liquid h3, +._love h3, +._lua h3, +._mariadb h3, +._meteor h3, +._npm h3, +._nushell h3, +._octave h3, +._openjdk h3, +._perl h3, +._phalcon h3, +._phaser h3, +._phpunit h3, +._pug h3, +._pygame h3, +._qt h3, +._ramda h3, +._react_native h3, +._reactivex h3, +._rethinkdb h3, +._rubydoc h3, +._rust h3, +._rxjs h3, +._sanctuary h3, +._sanctuary_def h3, +._sanctuary_type_classes h3, +._scala h3, +._sinon h3, +._sphinx_simple h3, +._sqlite h3, +._tcl_tk h3, +._tensorflow h3, +._terraform h3, +._typescript h3, +._vue h3, +._webpack h3, +._wordpress h3, +._yard h3, +._yii h3, +._angularjs .defs > li > h3:first-child, +._bash dl > dt > code, +._bash dl > dt > kbd, +._cppref > h4, +._cakephp h4, +._clojure h2[id], +._clojure h3, +._codeception h4, +._d h3, +._d .d_decl, +._d3 > h3, +._d3 > h6, +._dart dl:not(.dl-horizontal) dt, +._dart .multi-line-signature, +._elisp dl > dt, +._fastapi > h3, +._github h4, +._graphite dl > dt, +._groovy h3, +._gtk h3, +._haproxy h3, +._haproxy h4, +._haproxy .keyword, +._haskell-api > h3, +._haskell-api p.src, +._jasmine h4, +._jquery .signature > .name, +._jquery .api-item > h3, +._knockout > h3, +._kotlin h3, +._laravel h3, +._gnu_make dl dt, +._mdn > h3, +._mkdocs h3, +._mkdocs h4, +._modernizr h3, +._moment > h3, +._node > h3, +._node > h4, +._node h3, +._node h4, +._octave dl:not([compact]) > dt, +._octave dl[compact] > dt, +._perl > dl > dt, +._postgres .variablelist dt, +._pygame dl.class > dt, +._pygame dl.function > dt, +._pygame dl.method > dt, +._pygame dl.attribute > dt, +._pygame dl.exception > dt, +._pygame dl.data > dt, +._rdoc .method-heading, +._rfc-pre > h3, +._rfc-pre > h4, +._rust h4, +._sinon h4, +._python h3, +._sphinx h3, +._python > dl:not(.docutils) > dt, +._sphinx > dl:not(.docutils) > dt, +._python dd > dl:not(.docutils) > dt, +._sphinx dd > dl:not(.docutils) > dt, +._python .class > dt, +._sphinx .class > dt, +._python #main-interface .function > dt, +._sphinx #main-interface .function > dt, +._sqlite dt, +._tensorflow h4, +._shortcut-code, +._label, +._simple p > code, +._angular p > code, +._apache p > code, +._async p > code, +._bootstrap p > code, +._cakephp p > code, +._codeception p > code, +._coffeescript p > code, +._cordova p > code, +._crystal p > code, +._cypress p > code, +._dart p > code, +._dojo p > code, +._elixir p > code, +._ember p > code, +._erlang p > code, +._express p > code, +._fluture p > code, +._github p > code, +._gnuplot p > code, +._go p > code, +._graphite p > code, +._hapi p > code, +._jekyll p > code, +._joi p > code, +._jq p > code, +._julia p > code, +._kubectl p > code, +._kubernetes p > code, +._liquid p > code, +._love p > code, +._lua p > code, +._mariadb p > code, +._meteor p > code, +._npm p > code, +._nushell p > code, +._octave p > code, +._openjdk p > code, +._perl p > code, +._phalcon p > code, +._phaser p > code, +._phpunit p > code, +._pug p > code, +._pygame p > code, +._qt p > code, +._ramda p > code, +._react_native p > code, +._reactivex p > code, +._rethinkdb p > code, +._rubydoc p > code, +._rust p > code, +._rxjs p > code, +._sanctuary p > code, +._sanctuary_def p > code, +._sanctuary_type_classes p > code, +._scala p > code, +._sinon p > code, +._sphinx_simple p > code, +._sqlite p > code, +._tcl_tk p > code, +._tensorflow p > code, +._terraform p > code, +._typescript p > code, +._vue p > code, +._webpack p > code, +._wordpress p > code, +._yard p > code, +._yii p > code, +._simple li > code, +._angular li > code, +._apache li > code, +._async li > code, +._bootstrap li > code, +._cakephp li > code, +._codeception li > code, +._coffeescript li > code, +._cordova li > code, +._crystal li > code, +._cypress li > code, +._dart li > code, +._dojo li > code, +._elixir li > code, +._ember li > code, +._erlang li > code, +._express li > code, +._fluture li > code, +._github li > code, +._gnuplot li > code, +._go li > code, +._graphite li > code, +._hapi li > code, +._jekyll li > code, +._joi li > code, +._jq li > code, +._julia li > code, +._kubectl li > code, +._kubernetes li > code, +._liquid li > code, +._love li > code, +._lua li > code, +._mariadb li > code, +._meteor li > code, +._npm li > code, +._nushell li > code, +._octave li > code, +._openjdk li > code, +._perl li > code, +._phalcon li > code, +._phaser li > code, +._phpunit li > code, +._pug li > code, +._pygame li > code, +._qt li > code, +._ramda li > code, +._react_native li > code, +._reactivex li > code, +._rethinkdb li > code, +._rubydoc li > code, +._rust li > code, +._rxjs li > code, +._sanctuary li > code, +._sanctuary_def li > code, +._sanctuary_type_classes li > code, +._scala li > code, +._sinon li > code, +._sphinx_simple li > code, +._sqlite li > code, +._tcl_tk li > code, +._tensorflow li > code, +._terraform li > code, +._typescript li > code, +._vue li > code, +._webpack li > code, +._wordpress li > code, +._yard li > code, +._yii li > code, +._simple td > code, +._angular td > code, +._apache td > code, +._async td > code, +._bootstrap td > code, +._cakephp td > code, +._codeception td > code, +._coffeescript td > code, +._cordova td > code, +._crystal td > code, +._cypress td > code, +._dart td > code, +._dojo td > code, +._elixir td > code, +._ember td > code, +._erlang td > code, +._express td > code, +._fluture td > code, +._github td > code, +._gnuplot td > code, +._go td > code, +._graphite td > code, +._hapi td > code, +._jekyll td > code, +._joi td > code, +._jq td > code, +._julia td > code, +._kubectl td > code, +._kubernetes td > code, +._liquid td > code, +._love td > code, +._lua td > code, +._mariadb td > code, +._meteor td > code, +._npm td > code, +._nushell td > code, +._octave td > code, +._openjdk td > code, +._perl td > code, +._phalcon td > code, +._phaser td > code, +._phpunit td > code, +._pug td > code, +._pygame td > code, +._qt td > code, +._ramda td > code, +._react_native td > code, +._reactivex td > code, +._rethinkdb td > code, +._rubydoc td > code, +._rust td > code, +._rxjs td > code, +._sanctuary td > code, +._sanctuary_def td > code, +._sanctuary_type_classes td > code, +._scala td > code, +._sinon td > code, +._sphinx_simple td > code, +._sqlite td > code, +._tcl_tk td > code, +._tensorflow td > code, +._terraform td > code, +._typescript td > code, +._vue td > code, +._webpack td > code, +._wordpress td > code, +._yard td > code, +._yii td > code, +._simple blockquote > code, +._angular blockquote > code, +._apache blockquote > code, +._async blockquote > code, +._bootstrap blockquote > code, +._cakephp blockquote > code, +._codeception blockquote > code, +._coffeescript blockquote > code, +._cordova blockquote > code, +._crystal blockquote > code, +._cypress blockquote > code, +._dart blockquote > code, +._dojo blockquote > code, +._elixir blockquote > code, +._ember blockquote > code, +._erlang blockquote > code, +._express blockquote > code, +._fluture blockquote > code, +._github blockquote > code, +._gnuplot blockquote > code, +._go blockquote > code, +._graphite blockquote > code, +._hapi blockquote > code, +._jekyll blockquote > code, +._joi blockquote > code, +._jq blockquote > code, +._julia blockquote > code, +._kubectl blockquote > code, +._kubernetes blockquote > code, +._liquid blockquote > code, +._love blockquote > code, +._lua blockquote > code, +._mariadb blockquote > code, +._meteor blockquote > code, +._npm blockquote > code, +._nushell blockquote > code, +._octave blockquote > code, +._openjdk blockquote > code, +._perl blockquote > code, +._phalcon blockquote > code, +._phaser blockquote > code, +._phpunit blockquote > code, +._pug blockquote > code, +._pygame blockquote > code, +._qt blockquote > code, +._ramda blockquote > code, +._react_native blockquote > code, +._reactivex blockquote > code, +._rethinkdb blockquote > code, +._rubydoc blockquote > code, +._rust blockquote > code, +._rxjs blockquote > code, +._sanctuary blockquote > code, +._sanctuary_def blockquote > code, +._sanctuary_type_classes blockquote > code, +._scala blockquote > code, +._sinon blockquote > code, +._sphinx_simple blockquote > code, +._sqlite blockquote > code, +._tcl_tk blockquote > code, +._tensorflow blockquote > code, +._terraform blockquote > code, +._typescript blockquote > code, +._vue blockquote > code, +._webpack blockquote > code, +._wordpress blockquote > code, +._yard blockquote > code, +._yii blockquote > code, +._simple dd > code, +._angular dd > code, +._apache dd > code, +._async dd > code, +._bootstrap dd > code, +._cakephp dd > code, +._codeception dd > code, +._coffeescript dd > code, +._cordova dd > code, +._crystal dd > code, +._cypress dd > code, +._dart dd > code, +._dojo dd > code, +._elixir dd > code, +._ember dd > code, +._erlang dd > code, +._express dd > code, +._fluture dd > code, +._github dd > code, +._gnuplot dd > code, +._go dd > code, +._graphite dd > code, +._hapi dd > code, +._jekyll dd > code, +._joi dd > code, +._jq dd > code, +._julia dd > code, +._kubectl dd > code, +._kubernetes dd > code, +._liquid dd > code, +._love dd > code, +._lua dd > code, +._mariadb dd > code, +._meteor dd > code, +._npm dd > code, +._nushell dd > code, +._octave dd > code, +._openjdk dd > code, +._perl dd > code, +._phalcon dd > code, +._phaser dd > code, +._phpunit dd > code, +._pug dd > code, +._pygame dd > code, +._qt dd > code, +._ramda dd > code, +._react_native dd > code, +._reactivex dd > code, +._rethinkdb dd > code, +._rubydoc dd > code, +._rust dd > code, +._rxjs dd > code, +._sanctuary dd > code, +._sanctuary_def dd > code, +._sanctuary_type_classes dd > code, +._scala dd > code, +._sinon dd > code, +._sphinx_simple dd > code, +._sqlite dd > code, +._tcl_tk dd > code, +._tensorflow dd > code, +._terraform dd > code, +._typescript dd > code, +._vue dd > code, +._webpack dd > code, +._wordpress dd > code, +._yard dd > code, +._yii dd > code, +._angularjs p > code, +._angularjs li > code, +._angularjs td > code, +._bash code, +._bootstrap h4 > code, +._bootstrap h5 > code, +._bootstrap strong > code, +._bootstrap .text-danger, +._cppref code, +._cppref .t-mark, +._cppref .t-mark-rev, +._cakephp code, +._cakephp p > .label, +._cakephp dt > .label, +._cakephp div > .label, +._crystal a.signature, +._crystal .superclass > a, +._d p > code, +._d li > code, +._d td > code, +._d dd > code, +._d3 code, +._drupal span.api-deprecated, +._erlang code.code, +._fastapi code, +._git code, +._haskell-api dt > code, +._haskell-api .complexity, +._haskell-api .version, +._jquery p > code, +._jquery li > code, +._knockout p > code, +._kotlin code, +._laravel p > code, +._laravel h4 > code, +._love .label, +._love dt > code, +._mdn p > code, +._mdn li > code, +._mdn .inlineIndicator, +._meteor dt > code, +._mkdocs p > code, +._mkdocs li > code, +._modernizr code, +._moment code, +._nginx dt > code, +._node p > code, +._node li > code, +._node .type, +._node .api_metadata, +._php strong > code, +._php dt > code, +._postgres p > code, +._pug h4 > code, +._redis p > code, +._rubydoc span.note, +._rust em.stab, +._rust span.stab, +._python p > code, +._sphinx p > code, +._python li > code, +._sphinx li > code, +._python dd > code, +._sphinx dd > code, +._python .docutils > dt > code, +._sphinx .docutils > dt > code, +._sphinx_simple code, +._support_tables code, +._underscore .header + code { + margin: 0 1px; + padding: 1px 4px 2px; + background: var(--labelBackground); + border-radius: 3px; +} +._simple h3, +._angular h3, +._apache h3, +._async h3, +._bootstrap h3, +._cakephp h3, +._codeception h3, +._coffeescript h3, +._cordova h3, +._crystal h3, +._cypress h3, +._dart h3, +._dojo h3, +._elixir h3, +._ember h3, +._erlang h3, +._express h3, +._fluture h3, +._github h3, +._gnuplot h3, +._go h3, +._graphite h3, +._hapi h3, +._jekyll h3, +._joi h3, +._jq h3, +._julia h3, +._kubectl h3, +._kubernetes h3, +._liquid h3, +._love h3, +._lua h3, +._mariadb h3, +._meteor h3, +._npm h3, +._nushell h3, +._octave h3, +._openjdk h3, +._perl h3, +._phalcon h3, +._phaser h3, +._phpunit h3, +._pug h3, +._pygame h3, +._qt h3, +._ramda h3, +._react_native h3, +._reactivex h3, +._rethinkdb h3, +._rubydoc h3, +._rust h3, +._rxjs h3, +._sanctuary h3, +._sanctuary_def h3, +._sanctuary_type_classes h3, +._scala h3, +._sinon h3, +._sphinx_simple h3, +._sqlite h3, +._tcl_tk h3, +._tensorflow h3, +._terraform h3, +._typescript h3, +._vue h3, +._webpack h3, +._wordpress h3, +._yard h3, +._yii h3, +._angularjs .defs > li > h3:first-child, +._bash dl > dt > code, +._bash dl > dt > kbd, +._cppref > h4, +._cakephp h4, +._clojure h2[id], +._clojure h3, +._codeception h4, +._d h3, +._d .d_decl, +._d3 > h3, +._d3 > h6, +._dart dl:not(.dl-horizontal) dt, +._dart .multi-line-signature, +._elisp dl > dt, +._fastapi > h3, +._github h4, +._graphite dl > dt, +._groovy h3, +._gtk h3, +._haproxy h3, +._haproxy h4, +._haproxy .keyword, +._haskell-api > h3, +._haskell-api p.src, +._jasmine h4, +._jquery .signature > .name, +._jquery .api-item > h3, +._knockout > h3, +._kotlin h3, +._laravel h3, +._gnu_make dl dt, +._mdn > h3, +._mkdocs h3, +._mkdocs h4, +._modernizr h3, +._moment > h3, +._node > h3, +._node > h4, +._node h3, +._node h4, +._octave dl:not([compact]) > dt, +._octave dl[compact] > dt, +._perl > dl > dt, +._postgres .variablelist dt, +._pygame dl.class > dt, +._pygame dl.function > dt, +._pygame dl.method > dt, +._pygame dl.attribute > dt, +._pygame dl.exception > dt, +._pygame dl.data > dt, +._rdoc .method-heading, +._rfc-pre > h3, +._rfc-pre > h4, +._rust h4, +._sinon h4, +._python h3, +._sphinx h3, +._python > dl:not(.docutils) > dt, +._sphinx > dl:not(.docutils) > dt, +._python dd > dl:not(.docutils) > dt, +._sphinx dd > dl:not(.docutils) > dt, +._python .class > dt, +._sphinx .class > dt, +._python #main-interface .function > dt, +._sphinx #main-interface .function > dt, +._sqlite dt, +._tensorflow h4 { + display: block; + line-height: 1.375rem; + margin: 2em 0 1em; + padding-left: 0.5em; + padding-right: 0.5em; + overflow: hidden; + font-size: inherit; + color: var(--boxHeaderColor); + border: 1px solid var(--boxBorder); + border-radius: 2px; +} +._cakephp p > .label, +._cakephp dt > .label, +._cakephp div > .label { + background: var(--noteBackground); + border-color: var(--noteBorder); +} +._intro-message, +._note-green, +._angular .banner, +._angularjs .alert-success, +._cypress .note.success, +._fastapi .admonition.tip, +._git > .callout, +._git > h1 + .sectionbody, +._gtk .note, +._love .note-green, +._node .api_stability_3, +._node .api_stability_4, +._php div.tip, +._postgres blockquote.tip, +._redis > .metadata, +._rxjs .banner, +._python .hint, +._sphinx .hint, +._sphinx_simple .admonition.tip, +._vue .custom-block.tip, +._angular code.stable, +._cppref .t-mark, +._cppref .t-mark-rev, +._groovy .element, +._groovy .field, +._haskell-api .complexity, +._haskell-api .version, +._love .label-green, +._perl > dl > dt.variable, +._pygame dl.attribute > dt, +._pygame dl.exception > dt, +._pygame dl.data > dt, +._rxjs code.stable { + background: var(--noteGreenBackground); + border-color: var(--noteGreenBorder); +} +._angular .alert.is-helpful, +._angular .breadcrumbs, +._bootstrap .bs-callout-info, +._cypress .note.info, +._d3 blockquote, +._drupal .signature, +._fastapi .admonition.note, +._jekyll .note.info, +._jquery #quick-nav, +._laravel blockquote.tip, +._mdn .htmlelt, +._mdn .cssprop, +._meteor .subtitle-page, +._node .api_stability_5, +._openjdk > ul.inheritance, +._php .classsynopsis, +._php .description > .constructorsynopsis, +._php .description > .methodsynopsis, +._php .description > .fieldsynopsis, +._rdoc > .meta, +._rdoc .info, +._rxjs .alert.is-helpful, +._rxjs .breadcrumbs, +._vue .custom-block.info, +._webpack blockquote.tip, +._simple h3, +._angular h3, +._apache h3, +._async h3, +._bootstrap h3, +._cakephp h3, +._codeception h3, +._coffeescript h3, +._cordova h3, +._crystal h3, +._cypress h3, +._dart h3, +._dojo h3, +._elixir h3, +._ember h3, +._erlang h3, +._express h3, +._fluture h3, +._github h3, +._gnuplot h3, +._go h3, +._graphite h3, +._hapi h3, +._jekyll h3, +._joi h3, +._jq h3, +._julia h3, +._kubectl h3, +._kubernetes h3, +._liquid h3, +._love h3, +._lua h3, +._mariadb h3, +._meteor h3, +._npm h3, +._nushell h3, +._octave h3, +._openjdk h3, +._perl h3, +._phalcon h3, +._phaser h3, +._phpunit h3, +._pug h3, +._pygame h3, +._qt h3, +._ramda h3, +._react_native h3, +._reactivex h3, +._rethinkdb h3, +._rubydoc h3, +._rust h3, +._rxjs h3, +._sanctuary h3, +._sanctuary_def h3, +._sanctuary_type_classes h3, +._scala h3, +._sinon h3, +._sphinx_simple h3, +._sqlite h3, +._tcl_tk h3, +._tensorflow h3, +._terraform h3, +._typescript h3, +._vue h3, +._webpack h3, +._wordpress h3, +._yard h3, +._yii h3, +._angularjs .defs > li > h3:first-child, +._bash dl > dt > code, +._bash dl > dt > kbd, +._cppref > h4, +._clojure h2[id], +._clojure h3, +._d h3, +._d .d_decl, +._d3 > h6, +._elisp dl > dt, +._fastapi > h3, +._graphite dl > dt, +._groovy .constructor, +._groovy .method, +._gtk h3, +._haproxy .keyword, +._haskell-api p.src, +._jasmine h4, +._jquery .signature > .name, +._jquery .api-item > h3, +._knockout > h3, +._kotlin h3, +._laravel h3, +._gnu_make dl dt, +._mdn > h3, +._mkdocs h3, +._modernizr h3, +._moment > h3, +._node > h3, +._node h3, +._octave dl:not([compact]) > dt, +._perl > dl > dt.function, +._postgres .variablelist dt, +._pygame dl.function > dt, +._pygame dl.method > dt, +._rdoc .method-heading, +._rfc-pre > h3, +._python > dl:not(.docutils) > dt, +._sphinx > dl:not(.docutils) > dt, +._python .class > dt, +._sphinx .class > dt, +._python #main-interface .function > dt, +._sphinx #main-interface .function > dt, +._sqlite dt { + background: var(--noteBlueBackground); + border-color: var(--noteBlueBorder); +} +._gtk .warning, +._jekyll .note.unreleased, +._php div.caution, +._postgres blockquote.caution, +._pug .alert-danger, +._react_native .deprecated, +._rethinkdb .infobox-alert, +._python .important, +._sphinx .important, +._sphinx_simple .admonition.warning, +._wordpress .callout-alert, +._angular code.experimental, +._groovy .enum_constant, +._mdn .nonStandard, +._mdn .projectSpecific, +._mdn .experimental, +._pygame dl.class > dt, +._rust em.stab.unstable, +._rust span.stab.unstable, +._rxjs code.experimental { + background: var(--noteOrangeBackground); + border-color: var(--noteOrangeBorder); +} +._angular .alert.is-important, +._angularjs .alert-error, +._apache .warning, +._bootstrap .bs-callout-danger, +._codeception .alert-danger, +._cypress .note.danger, +._erlang .warning, +._express .doc-warn, +._jekyll .note.warning, +._love .note-red, +._mdn .warning, +._meteor .warning, +._node .api_stability_0, +._node .api_stability_1, +._php div.warning, +._phpunit .alert-danger, +._pygame .warning, +._rdoc .warning, +._rxjs .alert.is-important, +._python .warning, +._sphinx .warning, +._python .deprecated-removed, +._sphinx .deprecated-removed, +._python .deprecated, +._sphinx .deprecated, +._sqlite .todo, +._wordpress .callout-warning, +._angular code.deprecated, +._bootstrap .text-danger, +._drupal span.api-deprecated, +._love .label-red, +._mdn .deprecated, +._mdn .obsolete, +._rubydoc span.note.private, +._rxjs code.deprecated, +._scala .deprecated, +._typescript .deprecated { + background: var(--noteRedBackground); + border-color: var(--noteRedBorder); +} +._list-link:after, +._page a[href^="http:"]:after, +._page a[href^="https:"]:after { + content: ""; + display: inline-block; + vertical-align: top; + width: 0.5rem; + height: 0.5rem; + margin: 0.125rem 0 0 0.125rem; + background-size: 0.5rem 0.5rem; + pointer-events: none; + background-image: url(data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMjAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzMzNzdjMCIgZD0iTTE1LDE1SDJWNmgyLjU5NWMwLDAsMC42ODktMC44OTYsMi4xNy0ySDFDMC40NDcsNCwwLDQuNDQ5LDAsNXYxMWMwLDAuNTUzLDAuNDQ3LDEsMSwxaDE1YzAuNTUzLDAsMS0wLjQ0NywxLTF2LTMuNzQ2IGwtMiwxLjY0NVYxNXogTTEzLjM2MSw4LjA1djMuNTUxTDIwLDYuNGwtNi42MzktNC45OTl2My4xMzFDNS4zLDQuNTMyLDUuMywxMi41LDUuMywxMi41QzcuNTgyLDguNzUyLDguOTg2LDguMDUsMTMuMzYxLDguMDV6Ii8+PC9zdmc+); +} +html._theme-dark ._list-link:after, +html._theme-dark ._page a[href^="http:"]:after, +._page html._theme-dark a[href^="http:"]:after, +html._theme-dark ._page a[href^="https:"]:after, +._page html._theme-dark a[href^="https:"]:after { + background-image: url(data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMjAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iI2NiZDBkMCIgZD0iTTE1LDE1SDJWNmgyLjU5NWMwLDAsMC42ODktMC44OTYsMi4xNy0ySDFDMC40NDcsNCwwLDQuNDQ5LDAsNXYxMWMwLDAuNTUzLDAuNDQ3LDEsMSwxaDE1YzAuNTUzLDAsMS0wLjQ0NywxLTF2LTMuNzQ2IGwtMiwxLjY0NVYxNXogTTEzLjM2MSw4LjA1djMuNTUxTDIwLDYuNGwtNi42MzktNC45OTl2My4xMzFDNS4zLDQuNTMyLDUuMywxMi41LDUuMywxMi41QzcuNTgyLDguNzUyLDguOTg2LDguMDUsMTMuMzYxLDguMDV6Ii8+PC9zdmc+); +} +._toc-link:after, +._links-link:after, +._attribution-link:after, +._jquery .name > a:after, +._jquery .version-details > a:after, +._mdn .syntaxbox a:after, +._mdn .twopartsyntaxbox a:after, +._mdn .inlineIndicator > a:after { + content: none !important; +} +html { + height: 100%; + font-size: 100%; + background: #fff; + background: var(--documentBackground); +} +@media (max-width: 800px) { + html { + font-size: 93.75%; + } +} +@media print { + html { + background: none; + } +} +@media print { + html ._header, + html ._sidebar, + html ._path, + html ._notif, + html ._toc, + html ._pre-clip, + html ._notice, + html ._links { + display: none !important; + } + html body, + html ._app, + html ._container, + html ._content { + margin: 0; + padding: 0; + height: initial; + background: none; + } + html body:after, + html ._app:after, + html ._container:after, + html ._content:after { + content: ""; + clear: both; + } + html ::-webkit-scrollbar { + display: none; + } + html ._list-link:after, + html ._page a[href^="http:"]:after, + ._page html a[href^="http:"]:after, + html ._page a[href^="https:"]:after, + ._page html a[href^="https:"]:after { + display: none; + } + html ._attribution-p { + background: none; + border: 2px solid var(--boxBorder); + } + html ._attribution:last-child:after { + content: "Exported from DevDocs \2014 https://devdocs.io"; + display: block; + margin-top: 1rem; + font-weight: var(--bolderFontWeight); + } + html ._attribution { + page-break-inside: avoid; + } + html h1, + html h2, + html h3, + html h4, + html h5, + html h6 { + page-break-inside: avoid; + page-break-after: avoid; + } + html pre { + page-break-before: avoid; + orphans: 5; + widows: 5; + } + html p { + orphans: 2; + widows: 2; + } +} +html._theme-default { + color-scheme: light only; +} +html._theme-dark { + color-scheme: dark only; +} +body { + height: 100%; + margin: 0; + overflow: auto; + font-size: 1em; + font-weight: normal; + font-family: -apple-system, BlinkMacSystemFont, "San Francisco", "Segoe UI", + Roboto, Ubuntu, "Helvetica Neue", Arial, sans-serif; + line-height: 1.7; + color: #333; + color: var(--textColor); + word-wrap: break-word; + overflow-wrap: break-word; + background: var(--contentBackground); + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} +a { + color: var(--linkColor); + text-decoration: var(--linkTextDecoration); +} +a:hover { + color: var(--linkColorHover); + text-decoration: underline; +} +img { + max-width: 100%; + height: auto; + border: 0; +} +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 1.5em 0 1em; + line-height: 1.3; + font-weight: var(--bolderFontWeight); +} +h1 { + font-size: 1.5em; +} +h2 { + font-size: 1.375em; +} +h3 { + font-size: 1.25em; +} +h4 { + font-size: 1.125em; +} +h5, +h6 { + font-size: 1em; +} +p { + margin: 0 0 1em; +} +p:last-child { + margin-bottom: 0; +} +b, +strong { + font-weight: var(--boldFontWeight); +} +small { + font-size: 0.9em; +} +ul, +ol { + margin: 1.5em 0; + padding: 0 0 0 2em; + list-style: disc outside; +} +ul ul { + list-style-type: circle; +} +ol { + list-style-type: decimal; +} +ol ol { + list-style-type: lower-alpha; +} +ol ol ol { + list-style-type: lower-roman; +} +li + li { + margin-top: 0.25em; +} +li > ul, +li > ol, +dd > ul, +dd > ol { + margin: 0.5em 0; +} +li > p { + margin-bottom: 0.25em; +} +dl { + margin: 1.5em 0; +} +dt { + font-weight: var(--boldFontWeight); +} +dd { + margin: 0.375em; + padding-left: 1em; +} +dd + dt { + margin-top: 1em; +} +abbr, +acronym, +dfn { + cursor: help; + border-bottom: 1px dotted var(--textColor); +} +pre, +code, +samp, +._jq .manual-example table td, +._redis > .example, +._scala .related-types, +._code, +._cppref .t-cc, +._crystal .signature, +._d .d_decl, +._haskell-api .src, +._ramda code, +._rfc-pre, +._rust .code-header { + font-family: var(--monoFont); + font-weight: normal; + font-style: normal; + font-size: 0.9em; + color: var(--textColor); + white-space: pre-wrap; + direction: ltr; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +pre, +._jq .manual-example table td, +._redis > .example, +._scala .related-types { + position: relative; + margin: 1.5em 0; + padding: 0.375rem 0.625rem; + line-height: 1.5; + overflow: auto; +} +a > code { + color: inherit; +} +table { + margin: 1.5em 0; + background: none; + border: 1px solid var(--boxBorder); + border-collapse: separate; + border-spacing: 0; + border-radius: 3px; + display: inline-block; + overflow-x: auto; + max-width: 100%; +} +caption { + font-weight: var(--boldFontWeight); + padding: 0 0.7em 0.3em; +} +th, +td { + vertical-align: top; + padding: 0.3em 0.7em; + padding-bottom: -webkit-calc(0.3em + 1px); + padding-bottom: calc(0.3em + 1px); + text-align: left; + white-space: normal !important; +} +th { + font-weight: var(--boldFontWeight); + border: 0; + border-bottom: 1px solid var(--boxBorder); + border-radius: 0; +} +th:empty { + background: none; +} +th + th, +th + td { + border-left: 1px solid var(--boxBorder); +} +tr:first-child > th:first-child { + border-top-left-radius: 3px; +} +tr:first-child > th:last-child { + border-top-right-radius: 3px; +} +tr:last-child > th:first-child { + border-bottom-left-radius: 3px; +} +thead > tr:last-child > th:first-child { + border-bottom-left-radius: 0; +} +tr:last-child > th { + border-bottom-width: 0; +} +thead > tr:last-child > th { + border-bottom-width: 1px; +} +td { + background: var(--contentBackground); + border-bottom: 1px solid var(--boxBorderLight); +} +td + td { + border-left: 1px solid var(--boxBorderLight); +} +tr:last-child > td { + border-bottom: 0; +} +td > pre:only-child, +td > p:only-child, +td > ul:only-child, +td > ol:only-child { + margin-top: 0; + margin-bottom: 0; +} +td > pre:first-child, +td > p:first-child, +td > ul:first-child, +td > ol:first-child { + margin-top: 0; +} +td > pre:last-child, +td > p:last-child, +td > ul:last-child, +td > ol:last-child { + margin-bottom: 0; +} +section, +main { + display: block; + outline: 0; +} +label { + display: block; +} +input, +button { + display: inline-block; + margin: 0; + font-family: inherit; + font-size: 100%; + color: var(--textColor); + line-height: normal; +} +input[type="checkbox"] { + width: 1rem; + height: 1rem; + cursor: pointer; +} +button { + padding: 0; + background: none; + border: 0; + cursor: pointer; +} +button, +input[type="search"] { + -webkit-appearance: none; + appearance: none; +} +button:focus { + outline: 1px dotted; + outline: -webkit-focus-ring-color auto 5px; +} +img, +iframe { + background: var(--externalsBackground); +} +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} +::-ms-clear { + display: none; +} +::-moz-focus-inner { + padding: 0 !important; + border: 0 !important; +} +::-webkit-input-placeholder { + color: var(--textColorLighter); +} +::-moz-placeholder { + color: var(--textColorLighter); + opacity: 1; +} +:-ms-input-placeholder { + color: var(--textColorLighter); +} +body:not(._native-scrollbars) *::-webkit-scrollbar { + -webkit-appearance: none; +} +body:not(._native-scrollbars) *::-webkit-scrollbar:vertical { + width: 16px; +} +body:not(._native-scrollbars) *::-webkit-scrollbar:horizontal { + height: 16px; +} +body:not(._native-scrollbars) *::-webkit-scrollbar-button, +body:not(._native-scrollbars) *::-webkit-scrollbar-corner { + display: none; +} +body:not(._native-scrollbars) *::-webkit-scrollbar-track { + background: var(--contentBackground); + border: 1px solid var(--contentBackground); +} +body:not(._native-scrollbars) *::-webkit-scrollbar-track:hover { + background: var(--sidebarBackground); + border-color: var(--sidebarBorder); +} +body:not(._native-scrollbars) *::-webkit-scrollbar-track:vertical { + border-width: 0 0 0 1px; +} +body:not(._native-scrollbars) + *::-webkit-scrollbar-track:vertical:corner-present { + border-width: 0 0 1px 1px; + border-radius: 0 0 0 2px; +} +body:not(._native-scrollbars) *::-webkit-scrollbar-track:horizontal { + border-width: 1px 1px 0 1px; + border-radius: 2px 2px 0 0; +} +body:not(._native-scrollbars) *::-webkit-scrollbar-thumb { + min-height: 2rem; + background: var(--scrollbarColor); + background-clip: padding-box; + border: 5px solid transparent; + border-radius: 10px; +} +body:not(._native-scrollbars) *::-webkit-scrollbar-thumb:hover, +body:not(._native-scrollbars) *::-webkit-scrollbar-thumb:active { + background-color: var(--scrollbarColorHover); + border-width: 4px; +} +html._booting { + background: var(--contentBackground); +} +body._max-width { + background: none; +} +html._booting body._max-width { + background: var(--documentBackground); +} +._app { + position: relative; + z-index: 1; + height: 100%; + overflow: hidden; + -webkit-transition: opacity 0.2s; + transition: opacity 0.2s; +} +._booting ._app { + opacity: 0; +} +._max-width ._app { + margin: 0 auto; + max-width: var(--maxWidth); + background: var(--contentBackground); + box-shadow: + 1px 0 var(--headerBorder), + -1px 0 var(--headerBorder); +} +._header { + position: absolute; + z-index: var(--headerZ); + top: 0; + left: 0; + display: -ms-flexbox; + display: flex; + width: var(--sidebarWidth); + height: var(--headerHeight); + background: var(--headerBackground); + border-bottom: 1px solid var(--headerBorder); + border-right: 1px solid var(--headerBorder); +} +@media (max-width: 800px) { + ._header { + width: var(--sidebarMediumWidth); + } +} +._header-left { + float: left; + height: 100%; +} +._header-right { + float: right; + height: 100%; +} +._header-btn { + position: relative; + flex: 0 0 auto; + width: 2.25rem; + height: 100%; + color: var(--textColorLight); + text-align: center; +} +._header-btn[hidden] { + display: none; +} +._header-btn[disabled] { + opacity: 0.3; + cursor: not-allowed; +} +._header-btn > svg { + width: 1.5rem; + height: 1.5rem; +} +._menu { + position: absolute; + z-index: 1; + top: 0.25rem; + right: 0.25rem; + width: 8.5rem; + height: calc(2.25rem * 6 + 2.5rem + 1px); + white-space: nowrap; + word-wrap: normal; + overflow-wrap: normal; + font-size: 0.875rem; + background: var(--contentBackground); + border: 1px solid var(--headerBorder); + border-radius: 3px; + box-shadow: -1px 1px 1px rgba(0, 0, 0, 0.05); + transition: all 0ms cubic-bezier(0.23, 1, 0.32, 1) 1ms; + opacity: 0; + -webkit-transform: scale(0, 0); + transform: scale(0, 0); + -webkit-transform-origin: 100% 0; + transform-origin: 100% 0; +} +._menu.active { + transition-duration: 250ms; + opacity: 1; + -webkit-transform: scale(1, 1); + transform: scale(1, 1); +} +._menu:focus-within, +._menu-btn:focus + ._menu { + transition-duration: 250ms; + opacity: 1; + -webkit-transform: scale(1, 1); + transform: scale(1, 1); +} +._menu-title { + margin: 0; + line-height: 1.5rem; + font-size: 1rem; + font-weight: var(--boldFontWeight); + letter-spacing: -0.5px; + background: var(--sidebarBackground); + border-bottom: 1px solid var(--sidebarBorder); + border-radius: 2px 2px 0 0; +} +._menu-title-link, +._menu-title-link:hover { + display: block; + padding: 0.5rem 1rem; + color: var(--focusText); + text-decoration: none; +} +._menu-link { + display: block; + padding: 0 1rem; + line-height: 2.25rem; + color: inherit; + text-decoration: none; +} +._menu-link:hover { + color: var(--focusText); + text-decoration: none; + background: var(--sidebarBackground); +} +._menu-link:last-child { + border-radius: 0 0 2px 2px; +} +._search { + -ms-flex: 1 1 auto; + flex: 1 1 auto; + position: relative; + height: 100%; + padding: 0.5rem 0 0.5rem 0.5rem; +} +._search > svg { + position: absolute; + z-index: 1; + top: 0.875rem; + left: 0.875rem; + width: 1.25rem; + height: 1.25rem; + opacity: 0.42; + fill: var(--absolute); +} +._search-input { + position: relative; + display: block; + width: 100%; + height: 100%; + padding: 0 0.75rem 1px 1.75rem; + font-size: 0.875rem; + background: var(--contentBackground); + border: 1px solid; + border-color: var(--searchBorder); + border-radius: 3px; +} +._search-input:focus { + outline: 0; + border-color: var(--inputFocusBorder); + box-shadow: 0 0 1px var(--inputFocusBorder); +} +._search-input[disabled] { + background: var(--sidebarBackground); + cursor: not-allowed; +} +._search-clear { + display: none; + position: absolute; + top: 0.5em; + right: 0; + width: 1.75rem; + height: 2rem; + opacity: 0.42; +} +._search-clear:hover { + opacity: 0.7; +} +._search-clear > svg { + position: absolute; + top: 0.5rem; + left: 0.375rem; + fill: var(--absolute); +} +._search-active > ._search-clear { + display: block; +} +._search-tag { + display: none; + position: absolute; + z-index: 2; + top: 0.875rem; + left: 0.875rem; + padding: 0 0.375rem; + line-height: 1.25rem; + max-width: 50%; + font-size: 0.8125rem; + color: var(--textColorLight); + background: var(--searchTagBackground); + border-radius: 2px; + cursor: pointer; +} +._notif { + position: absolute; + z-index: 2; + top: 1rem; + right: 1rem; + width: 25rem; + max-width: 90%; + padding: 0.625rem 1rem; + font-size: 0.75rem; + color: var(--notifColor); + background: var(--notifBackground); + border: var(--notifBorder); + border-radius: 0.25rem; + transition: opacity 0.2s; + opacity: 0; + cursor: default; +} +._notif._in { + opacity: 1; +} +._notif-title { + margin: 0 0 0.5rem; + line-height: 1rem; + font-size: inherit; +} +._notif-text { + margin-bottom: 0; +} +._notif-text + ._notif-text { + margin-top: 0.25rem; +} +._notif-info { + float: right; + color: var(--notifColorLight); +} +._notif-link, +._notif-link:hover { + color: inherit; + text-decoration: underline; + cursor: pointer; +} +._notif-close { + position: absolute; + top: 0; + right: 0; + width: 2.25rem; + height: 2.25rem; + opacity: 0.9; +} +._notif-close > svg { + position: absolute; + top: 0.625rem; + left: 0.625rem; + fill: white; +} +._notif-close:hover { + opacity: 1; +} +._notif-content { + max-height: calc(50vh - 4.5rem); + margin: 0 -0.25rem 0 0; + padding-right: 0.75rem; + overflow-y: auto; +} +._notif-content::-webkit-scrollbar { + width: 10px !important; +} +._notif-content::-webkit-scrollbar-track { + background: var(--notifBackground) !important; + border: 0 !important; + border-radius: 5px !important; +} +._notif-content::-webkit-scrollbar-thumb { + border: 3px solid var(--notifBackground) !important; +} +._notif-content::-webkit-scrollbar-thumb:hover, +._notif-content::-webkit-scrollbar-thumb:active { + border-width: 2px !important; +} +._notif-content > ._notif-title { + margin-bottom: 0.5rem; + text-align: center; +} +._notif-news > ._news-row { + line-height: 1.125rem; + font-size: 0.6875rem; + color: var(--notifColorLight); + margin-bottom: 0.25rem; +} +._notif-news > ._news-row + ._news-row { + margin-top: 0.625rem; +} +._notif-news ._news-title { + display: block; + margin-bottom: 0.25rem; + font-size: 0.75rem; + font-weight: normal; + color: white; +} +._notif-news ._news-date { + float: right; + margin-left: 1rem; + font-weight: var(--boldFontWeight); +} +._notif-news code { + display: inline-block; + vertical-align: baseline; + line-height: 0; + margin: 0 0.25rem; + padding: 0; + color: inherit; + background: none; + border: 0; +} +._notif-list { + margin: 0; + padding-left: 1rem; +} +._notif-tip { + color: var(--textColor); + background: var(--tipBackground); + border: var(--tipBorder); +} +._notif-tip ._notif-info { + color: var(--textColorLight); +} +._notif-right { + float: right; +} +._sidebar { + position: absolute; + z-index: var(--sidebarZ); + top: 0; + bottom: 0; + left: 0; + overflow-x: hidden; + overflow-y: scroll; + padding-top: var(--headerHeight); + background: var(--sidebarBackground); + background-clip: content-box; + -webkit-overflow-scrolling: touch; + -ms-overflow-style: none; +} +._sidebar:focus { + outline: none; +} +._overlay-scrollbars ._sidebar { + padding-top: 0; + top: var(--headerHeight); +} +body:not(._native-scrollbars) ._sidebar::-webkit-scrollbar { + width: 10px; +} +body:not(._native-scrollbars) ._sidebar::-webkit-scrollbar-track { + background: var(--contentBackground); + border: 0; +} +body:not(._native-scrollbars) ._sidebar::-webkit-scrollbar-thumb { + border-width: 3px; +} +body:not(._native-scrollbars) ._sidebar::-webkit-scrollbar-thumb:hover, +body:not(._native-scrollbars) ._sidebar::-webkit-scrollbar-thumb:active { + border-width: 2px; +} +._sidebar-hidden ._sidebar { + transform: translateX(-95%); + transform: translateX(calc(0.5rem - 100%)); + opacity: 0; +} +._sidebar:hover:not(.no-hover), +._sidebar.show { + transform: none; + opacity: 1; +} +._resizer { + position: absolute; + z-index: var(--headerZ); + top: var(--headerHeight); + bottom: var(--headerHeight); + left: var(--sidebarWidth); + margin-left: -2px; + width: 3px; + cursor: col-resize; +} +._sidebar-hidden ._resizer { + display: none; +} +._sidebar-hidden ._sidebar.show ~ ._resizer { + display: block; +} +._list { + margin: 0; + padding: 0; + list-style: none; + width: var(--sidebarWidth); + box-shadow: inset -1px 0 var(--sidebarBorder); +} +@media (max-width: 800px) { + ._list { + width: var(--sidebarMediumWidth); + } +} +._sidebar > ._list { + min-height: 100%; +} +._list a:focus { + outline: 0; +} +._list-title { + position: relative; + margin: 0.5rem 0 0; + padding: 0 0.75rem 0 2.125rem; + line-height: 2rem; + font-size: 0.75rem; + color: var(--textColorLight); + text-transform: uppercase; + cursor: default; +} +._list-title-link { + display: none; + float: right; + font-weight: normal; + text-transform: none; +} +._list-title:hover > ._list-title-link { + display: block; +} +._list-item { + display: block; + position: relative; + padding: 0.25rem 0.75rem; + line-height: 1.5rem; + font-size: 0.875rem; + cursor: default; + background: var(--sidebarBackground); + box-shadow: inset -1px 0 var(--sidebarBorder); +} +._list-item, +._list-item:hover { + color: inherit; + text-decoration: none; +} +._list-item.focus, +._list-item.focus:hover, +._list-item.active, +._list-item.active:hover { + color: var(--focusText); + background: var(--focusBackground); + box-shadow: inset -1px 0 var(--focusBorder); +} +._list-item.active, +._list-item.active:hover { + color: var(--selectionText); + background: var(--selectionBackground); + box-shadow: inset -1px 0 var(--selectionBorder); +} +._list-item:before { + float: left; + margin: 0.25rem 0.625rem 0 0; +} +._list-text { + display: block; + pointer-events: none; +} +._list-count, +._list-enable { + float: right; + font-size: 0.75rem; + margin-left: 0.375rem; +} +.focus > ._list-count, +.active > ._list-count, +.focus > ._list-enable, +.active > ._list-enable { + color: inherit; +} +._list-count { + color: var(--textColorLighter); + pointer-events: none; +} +._list-disabled:hover > ._list-count { + display: none; +} +._list-enable { + display: none; + color: var(--linkColor); + cursor: pointer; +} +._list-enable:hover { + text-decoration: underline; +} +._list-disabled:hover > ._list-enable, +._list-result > ._list-enable { + display: block; +} +._list-result.active > ._list-enable { + margin-right: -1rem; +} +._list-dir:not(._list-rdir), +._list-disabled { + padding-left: 2.125rem; +} +._list-disabled, +._list-disabled:hover { + color: var(--textColorLight); +} +._list-disabled:before { + opacity: 0.7; +} +._list-arrow { + position: absolute; + top: 0; + left: 0.25rem; + padding: 0.5rem 0.375rem 0.5rem 0.5rem; + width: 1rem; + height: 1rem; + cursor: pointer; + fill: var(--absolute); + opacity: 0.4; +} +._list-arrow:hover { + opacity: 0.65; +} +._list-rdir > ._list-arrow { + left: auto; + right: 0.25rem; +} +.open > ._list-arrow, +.open-title > ._list-arrow { + -webkit-transform: rotate(90deg); + transform: rotate(90deg); +} +._list-sub { + display: none; +} +.open + ._list-sub { + display: block; +} +._list-sub > ._list-item { + padding-left: 2.375rem; +} +._list-sub > ._list-dir, +._list-sub > ._list-sub > ._list-item { + padding-left: 2.75rem; +} +._list-sub > ._list-disabled { + padding-left: 3.75rem; +} +._list-sub > ._list-item:before { + content: none; +} +._list-sub > ._list-dir { + line-height: 1.375rem; +} +._list-sub ._list-arrow { + left: 1rem; + padding: 0.4375rem; +} +._list-pagelink { + color: var(--linkColor); + cursor: pointer; +} +._list-pagelink:hover { + color: var(--linkColorHover); + text-decoration: underline; +} +._list-result.active { + padding-right: 1.75rem; +} +._list-result.active > ._list-reveal { + display: block; +} +._list-result.active > ._list-count { + display: none; +} +._list-reveal { + display: none; + position: absolute; + top: 0; + bottom: 0; + right: 0; + width: 2rem; + cursor: pointer; +} +._list-reveal:before { + content: ""; + position: absolute; + bottom: 50%; + left: 0.75rem; + width: 0.75rem; + height: 1px; + background: var(--transparentSelectionText); + box-shadow: + 0 -3px var(--transparentSelectionText), + 0 3px var(--transparentSelectionText); +} +._list-note { + padding: 0.5rem 0.75rem; + line-height: 1.25rem; + font-size: 0.8125rem; + color: var(--textColorLight); +} +._list-note + ._list-note { + padding-top: 0; +} +._list-note-link { + cursor: pointer; +} +._list-hover.clone { + position: fixed; + overflow: visible; + z-index: var(--hoverZ); + left: 0; + min-width: var(--sidebarWidth); + padding: 0.25rem 0.75rem; + pointer-events: none; + -webkit-font-smoothing: subpixel-antialiased; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); +} +@media (max-width: 800px) { + ._list-hover.clone { + min-width: var(--sidebarMediumWidth); + } +} +._list-hover.clone > ._list-text { + display: inline; +} +._list-hover.clone:not(._list-result) { + padding-left: 2.75rem; +} +._list-hover.clone:not(._list-result):before { + content: none; +} +._list-hover.clone ._list-reveal, +._list-hover.clone ._list-enable { + display: none; +} +._list-picker ._list-item { + cursor: pointer; +} +._list-picker ._list-sub > ._list-item { + padding-left: 2.375rem; +} +._list-picker-head { + display: flex; + justify-content: space-between; + position: -webkit-sticky; + position: sticky; + top: 0; + z-index: 1; + margin-right: 1px; + padding: 0.5rem 0.75rem 0.25rem 0.75rem; + line-height: 1.5rem; + font-size: 0.75rem; + font-weight: var(--bolderFontWeight); + color: var(--textColorLight); + text-transform: uppercase; + background: linear-gradient( + to bottom, + var(--sidebarBackground), + var(--sidebarBackground) 75%, + var(--transparentSidebarBackground) + ); + cursor: default; +} +._list-checkbox { + position: absolute; + top: 0.5rem; + right: 0.75rem; +} +._list-link { + display: block; + padding: 0.75rem 0; + font-size: 0.8125rem; + text-align: center; +} +._list-link:after { + visibility: hidden; +} +._list-link:hover:after { + visibility: visible; +} +._settings { + display: none; + position: absolute; + top: 0; + bottom: 0; + z-index: var(--headerZ); +} +._settings._in { + display: block; +} +._settings > ._header { + justify-content: space-between; +} +._settings._dirty > ._header { + background: var(--noteGreenBackground); + border-color: var(--noteGreenBorder); +} +._settings-fieldset { + display: -ms-flexbox; + display: flex; + margin: 1.5rem 0; + line-height: 1.5rem; +} +._settings-legend { + -ms-flex: 0 1 10rem; + flex: 0 1 10rem; + margin: 0; + padding-right: 0.5rem; + line-height: inherit; + font-size: inherit; + font-weight: var(--boldFontWeight); + text-align: right; +} +._settings-inputs { + -ms-flex: 1 1 20rem; + flex: 1 1 20rem; +} +._settings-label:not(._theme-label) { + margin: 0 0 0.375rem; +} +._settings-label > small { + display: block; + color: var(--textColorLight); + margin-left: 1.75rem; +} +._settings-label._theme-label > small { + display: inline-block; + margin-left: 0.75rem; +} +._settings-label input[type="checkbox"], +._settings-label input[type="radio"] { + vertical-align: top; + margin: 0.25rem 0.375rem; +} +@media (max-width: 80rem) { + ._setting-max-width { + display: none; + } +} +._setting-native-scrollbar { + display: none; +} +@supports (-webkit-margin-end: 1px) { + ._setting-native-scrollbar { + display: block; + } +} +._settings-btn { + display: block; + width: 100%; + height: 100%; + line-height: 1.5rem; + padding: 0 0.75rem; + font-size: 0.875rem; + font-weight: var(--boldFontWeight); + color: inherit; + text-align: left; + cursor: pointer; +} +._settings-btn > svg { + width: 1.5rem; + height: 1.5rem; + margin-right: 0.125rem; +} +._dirty ._settings-btn-back { + display: none; +} +._settings-btn-save { + display: none; +} +._dirty ._settings-btn-save { + display: block; +} +._settings-tabs { + display: none; + margin-right: 0.5rem; +} +._dirty ._settings-tabs { + display: none !important; +} +._settings-tab { + position: relative; + vertical-align: top; + padding: 0 0.75rem; + line-height: var(--headerHeight); + color: var(--textColorLight); +} +._settings-tab.active { + color: var(--textColor); + font-weight: var(--boldFontWeight); + box-shadow: inset 0 -2px var(--linkColor); +} +._container { + position: relative; + z-index: var(--contentZ); + height: 100%; + margin-left: var(--sidebarWidth); + pointer-events: none; +} +@media (max-width: 800px) { + ._container { + margin-left: var(--sidebarMediumWidth); + } +} +._sidebar-hidden ._container { + margin-left: 0; +} +body:not(._native-scrollbars) ._container { + -webkit-margin-end: -1px; +} +._content { + position: relative; + height: 100%; + overflow-y: scroll; + margin-left: 0.875rem; + padding: 1.125rem 1.5rem 0; + font-size: 0.875rem; + pointer-events: auto; + -webkit-overflow-scrolling: touch; +} +._sidebar-hidden ._content:before { + content: ""; + display: block; + margin-top: var(--headerHeight); +} +._text-justify-hyphenate ._content { + text-align: justify; + hyphens: auto; +} +._overlay-scrollbars ._content { + padding-left: 0.625rem; +} +@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { + ._content { + margin-left: 0; + } +} +@supports (-ms-overflow-style: none) { + ._content { + margin-left: 0; + } +} +body:not(._native-scrollbars) ._content { + -webkit-padding-start: 0.625rem; + -webkit-padding-end: 0.75rem; +} +._content-loading:before, +._splash-title { + content: "Loading\2026"; + position: absolute; + top: 50%; + left: 0; + right: 0; + line-height: 1; + margin-top: -0.6em; + font-size: 4rem; + font-weight: 300; + letter-spacing: -0.125rem; + color: var(--loadingText); + text-align: center; + cursor: default; +} +._splash-title { + color: var(--splashText); +} +._intro { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + min-height: calc(100vh - 2.375rem); +} +._sidebar-hidden ._intro { + min-height: calc(100vh - 2.375rem - var(--headerHeight)); +} +._intro-message { + max-width: 37rem; + margin: 0.5rem 0; + padding: 1rem 1.25rem; +} +._intro-hide { + float: right; + line-height: 1.5rem; + cursor: pointer; +} +._intro-title { + margin: 0 0 1rem; + font-size: 1rem; + line-height: 1.5rem; +} +._intro-list { + margin: 1rem 0; + padding-left: 2.25rem; +} +._intro-link { + cursor: pointer; +} +._error { + position: absolute; + top: 50%; + left: 0; + right: 0; + padding: 0 2rem; + line-height: 1.5rem; + text-align: center; +} +._error-title { + margin: -5.5rem 0 1rem; + line-height: 2rem; + font-size: 1.5rem; +} +._error-text { + margin: 0 0 1rem; + color: var(--textColorLight); +} +._error-links { + font-size: 1rem; + font-weight: var(--boldFontWeight); +} +._error-link { + padding: 0 0.5rem; +} +._lined-heading, +._page > h1, +._page > header > h1, +._page > section > h1, +._php h1 { + display: flex; + align-items: center; +} +._lined-heading > *, +._page > h1 > *, +._page > header > h1 > *, +._page > section > h1 > *, +._php h1 > * { + margin: 0 0.3125rem; +} +._lined-heading:after, +._page > h1:after, +._page > header > h1:after, +._page > section > h1:after, +._php h1:after { + content: ""; + flex-grow: 1; + height: 1px; + margin-top: 0.25rem; + margin-left: 1rem; + background: var(--boxBorderLight); +} +._heading-links { + float: right; + font-weight: normal; +} +._heading-links > a + a { + margin-left: 0.25rem; +} +._toc { + float: right; + max-width: 15em; + margin: 0.25rem 0 1.5rem 1.5rem; + padding: 0.625rem 1rem; +} +._toc + h1, +._toc + ._lined-heading, +._page > ._toc + h1, +._page > header > ._toc + h1, +._page > section > ._toc + h1 { + margin-top: 0; +} +._toc-title { + margin: 0 0 0.5rem; + font-size: inherit; + font-weight: var(--boldFontWeight); +} +._toc-list { + margin: 0; + padding: 0 1em 0 0; + list-style: none; +} +._static { + padding-bottom: 2em; +} +._static > ._lined-heading:first-child, +._page._static > h1:first-child, +._page > header._static > h1:first-child, +._page > section._static > h1:first-child { + margin-top: 0; +} +._credits { + max-width: 100%; +} +._docs { + width: 100%; + margin-top: 0.25rem; + line-height: 1.5rem; +} +._docs th, +._docs td { + width: 1%; +} +._docs th:first-child, +._docs td:first-child { + width: auto; +} +._docs th:last-child, +._docs td:last-child { + width: 12rem; +} +._docs-name:before { + float: left; + margin: 0.25rem 0.5rem 0.25rem 0; +} +._docs-size { + text-align: right; +} +._docs-size > small { + color: var(--textColorLight); +} +._docs-tools { + display: -ms-flexbox; + display: flex; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + -ms-flex-pack: justify; + justify-content: space-between; + -ms-flex-align: center; + align-items: center; + line-height: 1.5rem; + margin-top: -0.5rem; +} +._docs-tools input[type="checkbox"] { + vertical-align: top; + margin: 0.25rem; +} +._docs-links { + -ms-flex: 0 0 auto; + flex: 0 0 auto; + margin: 0.5rem 0; + padding: 0.25rem 0; +} +._docs-links ._btn-link { + vertical-align: top; + padding: 0 0.75rem; +} +._docs-links ._btn-link:not(._show) { + display: none; +} +._docs-links ._btn-link._show ~ ._btn-link._show { + border-left: 1px solid var(--boxBorder); +} +._content ._news-row { + position: relative; + padding-left: 10em; + font-size: 0.8125rem; + color: var(--textColorLight); +} +._content ._news-row + ._news-row { + margin-top: 1em; +} +._content ._news-title { + display: block; + font-size: 0.875rem; + color: var(--textColor); +} +._content ._news-date { + position: absolute; + top: 0; + left: 0; + font-size: 0.875rem; +} +._shortcuts-title { + width: 16rem; + max-width: 40%; + margin: 2rem 0 1rem; + font-size: 1rem; + text-align: right; +} +._shortcuts-dl { + margin: 1rem 0; +} +._shortcuts-dt { + float: left; + clear: left; + margin: 0 0 0.75rem; + width: 16rem; + max-width: 40%; + font-weight: normal; + text-align: right; +} +._shortcuts-dd { + display: block; + margin: 0 0 0.75rem; + padding: 1px 0 1px 0.75rem; + overflow: hidden; +} +._shortcut-code { + display: inline-block; + vertical-align: top; + padding: 0 0.5em; +} +._aliases { + display: flex; + justify-content: space-between; +} +._aliases > table { + margin-top: 0; + width: calc(50% - 0.5rem); +} +._bold { + font-weight: var(--boldFontWeight); +} +._highlight, +._highlight > td { + background: var(--highlightBackground) !important; +} +._table { + width: 100%; +} +._mobile ._table { + overflow-x: auto; +} +._pre-clip { + display: none; + position: absolute; + top: 0; + right: 0; + opacity: 0.5; + padding: 0.375rem; + cursor: pointer; +} +pre:hover > ._pre-clip { + display: block; + top: 0.1875rem; + padding: 0; +} +._pre-clip:hover { + opacity: 1; +} +._pre-clip > svg { + fill: var(--absolute); +} +._pre-clip._pre-clip-success > svg, +._pre-clip._pre-clip-error > svg { + display: none; +} +._pre-clip._pre-clip-success:before { + content: "Copied"; +} +._pre-clip._pre-clip-error:before { + content: "Error"; +} +._btn { + display: inline-block; + vertical-align: top; + line-height: normal; + white-space: nowrap; + padding: 0.375rem 0.675rem; + background-color: var(--boxBackground); + border: 1px solid var(--boxBorder); + border-radius: 3px; + cursor: pointer; +} +._btn:active { + box-shadow: + inset 0 1px 1px rgba(0, 0, 0, 0.05), + inset 0 1px 4px var(--boxBorder); +} +._file-btn { + position: relative; + overflow: hidden; +} +._file-btn > input { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + visibility: hidden; +} +._btn-link { + line-height: inherit; + color: var(--linkColor); + text-decoration: var(--linkTextDecoration); +} +._btn-link:hover { + color: var(--linkColorHover); + text-decoration: underline; +} +._reset-btn, +._reset-btn:hover { + color: var(--textColorRed); +} +._github-btn { + display: inline-block; + vertical-align: text-top; + margin-left: 0.25rem; + background: inherit; +} +._page { + position: relative; + min-height: calc(100% - 1.25rem); +} +._page._page-error { + position: static; +} +._page > h1:first-child, +._page > header:first-of-type > h1, +._page > section:first-of-type > h1 { + margin-top: 0; +} +._page a:not([href]) { + color: inherit; + text-decoration: none; +} +._page iframe { + display: block; + max-width: 100%; + margin-bottom: 1em; + padding: 1px; + border: 1px dotted var(--boxBorder); + border-radius: 3px; +} +._links { + position: absolute; + top: 0; + right: 0; + margin: 0; + line-height: 2em; + text-align: right; +} +._links + h1 { + margin-top: 0; +} +@media (max-width: 1023px) { + ._links { + display: none; + } +} +._links-link { + display: inline-block; + vertical-align: top; + padding: 0 0.5rem; + background: var(--contentBackground); +} +._links-link + ._links-link { + margin-left: 0.75rem; +} +._links-link:first-child { + padding-left: 1rem; +} +._links-link:last-child { + padding-right: 0; +} +._attribution { + clear: both; + margin: 2rem 0 1.5rem; + font-size: 0.75rem; + color: var(--textColorLight); + text-align: center; + -webkit-font-smoothing: subpixel-antialiased; +} +._attribution + ._attribution { + margin-top: 1.5rem; +} +._attribution + ._attribution > ._attribution-link { + display: none; +} +._attribution-p { + display: inline-block; + margin: 0; + padding: 0.25rem 0.75rem; + background: var(--labelBackground); + border-radius: 3px; +} +._entry-list { + padding-left: 1em; + list-style: none; +} +._fail { + display: block; + position: relative; + top: 1.5rem; + width: 24rem; + max-width: 90%; + margin: 0 auto; + padding: 1rem 1.5rem; + background: #eaefef; + border-radius: 5px; +} +._fail:after { + content: ""; + position: relative; + top: 3rem; + float: left; + width: 1px; + height: 1px; +} +._fail-title { + margin: 0 0 1rem; + font-size: 1rem; + font-weight: bold; +} +._fail-text, +._fail-list { + margin: 0 0 1rem; + font-size: 0.875rem; +} +._fail-text:last-child { + margin: 0; +} +._path { + position: absolute; + z-index: var(--headerZ); + bottom: 0; + left: var(--sidebarWidth); + right: 0; + height: 2rem; + line-height: 2rem; + padding: 0 0.375rem; + font-size: 0.875rem; + background: var(--pathBackground); + box-shadow: inset 0 1px var(--pathBorder); +} +@media (max-width: 800px) { + ._path { + left: var(--sidebarMediumWidth); + } +} +._sidebar-hidden ._path { + left: 0; +} +._path ~ ._container { + padding-bottom: 2rem; +} +._path a:focus { + outline: 0; +} +._path-item { + position: relative; + display: inline-block; + vertical-align: top; + padding: 0 0.375rem; + color: var(--textColor); + text-decoration: none; +} +._path-item:first-child:before { + content: ""; + float: left; + width: 1rem; + height: 1rem; + margin: 0.5rem 0.375rem 0 0; +} +._path-arrow { + display: inline-block; + vertical-align: top; + width: 0.75rem; + height: 0.75rem; + margin: 0.625rem 0.25rem; + fill: #888; +} +._notice { + position: absolute; + z-index: var(--noticeZ); + bottom: 0; + left: var(--sidebarWidth); + right: 0; + height: 2.5rem; + padding: 0 1.25rem; + background: var(--noticeBackground); + box-shadow: inset 0 1px var(--noticeBorder); +} +@media (max-width: 800px) { + ._notice { + left: var(--sidebarMediumWidth); + } +} +._sidebar-hidden ._notice { + left: 0; +} +._notice ~ ._container { + padding-bottom: 2.5rem; +} +._notice-text { + display: table-cell; + vertical-align: middle; + margin: 0; + height: 2.5rem; + line-height: 1rem; + font-size: 0.875rem; +} +._notice-link { + cursor: pointer; +} +html { + --prismValue: #905; + --prismText: #5e8e01; + --prismOperator: #a67f59; + --prismKeyword: #0070a3; + --prismFunction: #dd4a68; + --prismVariable: #e90; +} +html._theme-dark { + --prismValue: #eb8160; + --prismText: #ddcf88; + --prismOperator: #b1c676; + --prismKeyword: #91b3ed; + --prismFunction: #c79e6b; + --prismVariable: #e9c062; +} +.token.comment, +.token.prolog, +.token.doctype, +.token.cdata, +.token.punctuation { + color: var(--textColorLight); +} +.namespace { + opacity: 0.7; +} +.token.property, +.token.tag, +.token.boolean, +.token.number, +.token.constant, +.token.symbol, +.token.deleted { + color: var(--prismValue); +} +.token.selector, +.token.attr-name, +.token.string, +.token.char, +.token.builtin, +.token.inserted { + color: var(--prismText); +} +.token.operator, +.token.entity, +.token.url, +.language-css .token.string, +.style .token.string { + color: var(--prismOperator); +} +.token.atrule, +.token.attr-value, +.token.keyword { + color: var(--prismKeyword); +} +.token.function { + color: var(--prismFunction); +} +.token.regex, +.token.important, +.token.variable { + color: var(--prismVariable); +} +.token.important, +.token.bold { + font-weight: var(--boldFontWeight); +} +.token.italic { + font-style: italic; +} +._mobile { + font-size: 100%; + background: var(--contentBackground); +} +._mobile ._hide-on-mobile { + display: none; +} +._mobile body { + -ms-overflow-style: -ms-autohiding-scrollbar; +} +._mobile:not(._booting) ._app, +._mobile:not(._booting) ._content { + overflow: visible; +} +._mobile ._container { + margin: 0; + padding-top: var(--headerHeight); +} +._mobile ._content { + position: static; + height: auto; + margin: 0; + padding: 0.75rem 1rem 1px; +} +._mobile ._content:before { + content: none; +} +._mobile ._content-loading:before, +._mobile ._splash-title { + font-size: 3rem; +} +._mobile ._header { + position: fixed; +} +._mobile ._header, +._mobile ._list { + width: 100%; + border-right: 0; + box-shadow: none; +} +._mobile ._settings { + position: relative; +} +._mobile ._settings-tabs { + display: block; +} +._mobile ._header > ._settings-btn-back { + width: auto; +} +._mobile ._header-btn[hidden] { + display: block; +} +._mobile ._search { + padding-right: 0.125rem; + padding-left: 0.125rem; +} +._mobile ._search > svg { + left: 0.5rem; +} +._mobile ._search-tag { + left: 0.5rem; +} +._mobile ._search-clear > svg { + left: 0.25rem; +} +._mobile ._sidebar { + position: relative; + min-height: 100%; + overflow: visible; +} +._mobile ._resizer { + display: none; +} +._mobile ._list-item { + white-space: normal; + word-wrap: break-word; + overflow-wrap: break-word; + box-shadow: none; +} +._mobile ._list-result { + padding-left: 2.375rem; +} +._mobile ._list-result:before { + position: absolute; + top: 0.25rem; + left: 0.75rem; +} +._mobile ._notice { + position: fixed; + left: 0; + padding: 0 0.5rem; +} +._mobile ._notice-text { + font-size: 0.75em; +} +._mobile ._notif { + position: fixed; +} +._mobile ._toc { + float: none; + max-width: none; + margin-left: 0; +} +._mobile ._aliases { + display: block; +} +._mobile ._aliases > table { + width: 100%; +} +@-ms-viewport { + width: device-width; +} +@media (orientation: portrait) and (min-device-width: 720px) and (max-device-width: 768px), + (orientation: landscape) and (device-width: 1280px) and (max-device-height: 768px) { + @-ms-viewport { + width: 50%; + } +} +._forward-btn { + margin-right: -0.5rem; +} +._forward-btn > svg { + margin-left: -0.375rem; +} +._mobile-intro > ._intro-list { + padding-left: 1.5rem; +} +._mobile-intro ._intro-hide { + position: static; + float: none; + display: block; + margin-top: 0.75rem; + text-align: center; +} +._simple, +._angular, +._apache, +._async, +._bootstrap, +._cakephp, +._codeception, +._coffeescript, +._cordova, +._crystal, +._cypress, +._dart, +._dojo, +._elixir, +._ember, +._erlang, +._express, +._fluture, +._github, +._gnuplot, +._go, +._graphite, +._hapi, +._jekyll, +._joi, +._jq, +._julia, +._kubectl, +._kubernetes, +._liquid, +._love, +._lua, +._mariadb, +._meteor, +._npm, +._nushell, +._octave, +._openjdk, +._perl, +._phalcon, +._phaser, +._phpunit, +._pug, +._pygame, +._qt, +._ramda, +._react_native, +._reactivex, +._rethinkdb, +._rubydoc, +._rust, +._rxjs, +._sanctuary, +._sanctuary_def, +._sanctuary_type_classes, +._scala, +._sinon, +._sphinx_simple, +._sqlite, +._tcl_tk, +._tensorflow, +._terraform, +._typescript, +._vue, +._webpack, +._wordpress, +._yard, +._yii { + padding-left: 1rem; +} +._simple h1, +._angular h1, +._apache h1, +._async h1, +._bootstrap h1, +._cakephp h1, +._codeception h1, +._coffeescript h1, +._cordova h1, +._crystal h1, +._cypress h1, +._dart h1, +._dojo h1, +._elixir h1, +._ember h1, +._erlang h1, +._express h1, +._fluture h1, +._github h1, +._gnuplot h1, +._go h1, +._graphite h1, +._hapi h1, +._jekyll h1, +._joi h1, +._jq h1, +._julia h1, +._kubectl h1, +._kubernetes h1, +._liquid h1, +._love h1, +._lua h1, +._mariadb h1, +._meteor h1, +._npm h1, +._nushell h1, +._octave h1, +._openjdk h1, +._perl h1, +._phalcon h1, +._phaser h1, +._phpunit h1, +._pug h1, +._pygame h1, +._qt h1, +._ramda h1, +._react_native h1, +._reactivex h1, +._rethinkdb h1, +._rubydoc h1, +._rust h1, +._rxjs h1, +._sanctuary h1, +._sanctuary_def h1, +._sanctuary_type_classes h1, +._scala h1, +._sinon h1, +._sphinx_simple h1, +._sqlite h1, +._tcl_tk h1, +._tensorflow h1, +._terraform h1, +._typescript h1, +._vue h1, +._webpack h1, +._wordpress h1, +._yard h1, +._yii h1, +._simple h2, +._angular h2, +._apache h2, +._async h2, +._bootstrap h2, +._cakephp h2, +._codeception h2, +._coffeescript h2, +._cordova h2, +._crystal h2, +._cypress h2, +._dart h2, +._dojo h2, +._elixir h2, +._ember h2, +._erlang h2, +._express h2, +._fluture h2, +._github h2, +._gnuplot h2, +._go h2, +._graphite h2, +._hapi h2, +._jekyll h2, +._joi h2, +._jq h2, +._julia h2, +._kubectl h2, +._kubernetes h2, +._liquid h2, +._love h2, +._lua h2, +._mariadb h2, +._meteor h2, +._npm h2, +._nushell h2, +._octave h2, +._openjdk h2, +._perl h2, +._phalcon h2, +._phaser h2, +._phpunit h2, +._pug h2, +._pygame h2, +._qt h2, +._ramda h2, +._react_native h2, +._reactivex h2, +._rethinkdb h2, +._rubydoc h2, +._rust h2, +._rxjs h2, +._sanctuary h2, +._sanctuary_def h2, +._sanctuary_type_classes h2, +._scala h2, +._sinon h2, +._sphinx_simple h2, +._sqlite h2, +._tcl_tk h2, +._tensorflow h2, +._terraform h2, +._typescript h2, +._vue h2, +._webpack h2, +._wordpress h2, +._yard h2, +._yii h2, +._simple h3, +._angular h3, +._apache h3, +._async h3, +._bootstrap h3, +._cakephp h3, +._codeception h3, +._coffeescript h3, +._cordova h3, +._crystal h3, +._cypress h3, +._dart h3, +._dojo h3, +._elixir h3, +._ember h3, +._erlang h3, +._express h3, +._fluture h3, +._github h3, +._gnuplot h3, +._go h3, +._graphite h3, +._hapi h3, +._jekyll h3, +._joi h3, +._jq h3, +._julia h3, +._kubectl h3, +._kubernetes h3, +._liquid h3, +._love h3, +._lua h3, +._mariadb h3, +._meteor h3, +._npm h3, +._nushell h3, +._octave h3, +._openjdk h3, +._perl h3, +._phalcon h3, +._phaser h3, +._phpunit h3, +._pug h3, +._pygame h3, +._qt h3, +._ramda h3, +._react_native h3, +._reactivex h3, +._rethinkdb h3, +._rubydoc h3, +._rust h3, +._rxjs h3, +._sanctuary h3, +._sanctuary_def h3, +._sanctuary_type_classes h3, +._scala h3, +._sinon h3, +._sphinx_simple h3, +._sqlite h3, +._tcl_tk h3, +._tensorflow h3, +._terraform h3, +._typescript h3, +._vue h3, +._webpack h3, +._wordpress h3, +._yard h3, +._yii h3 { + margin-left: -1rem; +} +._simple h4, +._angular h4, +._apache h4, +._async h4, +._bootstrap h4, +._cakephp h4, +._codeception h4, +._coffeescript h4, +._cordova h4, +._crystal h4, +._cypress h4, +._dart h4, +._dojo h4, +._elixir h4, +._ember h4, +._erlang h4, +._express h4, +._fluture h4, +._github h4, +._gnuplot h4, +._go h4, +._graphite h4, +._hapi h4, +._jekyll h4, +._joi h4, +._jq h4, +._julia h4, +._kubectl h4, +._kubernetes h4, +._liquid h4, +._love h4, +._lua h4, +._mariadb h4, +._meteor h4, +._npm h4, +._nushell h4, +._octave h4, +._openjdk h4, +._perl h4, +._phalcon h4, +._phaser h4, +._phpunit h4, +._pug h4, +._pygame h4, +._qt h4, +._ramda h4, +._react_native h4, +._reactivex h4, +._rethinkdb h4, +._rubydoc h4, +._rust h4, +._rxjs h4, +._sanctuary h4, +._sanctuary_def h4, +._sanctuary_type_classes h4, +._scala h4, +._sinon h4, +._sphinx_simple h4, +._sqlite h4, +._tcl_tk h4, +._tensorflow h4, +._terraform h4, +._typescript h4, +._vue h4, +._webpack h4, +._wordpress h4, +._yard h4, +._yii h4 { + font-size: inherit; +} +._mobile ._simple, +._mobile ._angular, +._mobile ._apache, +._mobile ._async, +._mobile ._bootstrap, +._mobile ._cakephp, +._mobile ._codeception, +._mobile ._coffeescript, +._mobile ._cordova, +._mobile ._crystal, +._mobile ._cypress, +._mobile ._dart, +._mobile ._dojo, +._mobile ._elixir, +._mobile ._ember, +._mobile ._erlang, +._mobile ._express, +._mobile ._fluture, +._mobile ._github, +._mobile ._gnuplot, +._mobile ._go, +._mobile ._graphite, +._mobile ._hapi, +._mobile ._jekyll, +._mobile ._joi, +._mobile ._jq, +._mobile ._julia, +._mobile ._kubectl, +._mobile ._kubernetes, +._mobile ._liquid, +._mobile ._love, +._mobile ._lua, +._mobile ._mariadb, +._mobile ._meteor, +._mobile ._npm, +._mobile ._nushell, +._mobile ._octave, +._mobile ._openjdk, +._mobile ._perl, +._mobile ._phalcon, +._mobile ._phaser, +._mobile ._phpunit, +._mobile ._pug, +._mobile ._pygame, +._mobile ._qt, +._mobile ._ramda, +._mobile ._react_native, +._mobile ._reactivex, +._mobile ._rethinkdb, +._mobile ._rubydoc, +._mobile ._rust, +._mobile ._rxjs, +._mobile ._sanctuary, +._mobile ._sanctuary_def, +._mobile ._sanctuary_type_classes, +._mobile ._scala, +._mobile ._sinon, +._mobile ._sphinx_simple, +._mobile ._sqlite, +._mobile ._tcl_tk, +._mobile ._tensorflow, +._mobile ._terraform, +._mobile ._typescript, +._mobile ._vue, +._mobile ._webpack, +._mobile ._wordpress, +._mobile ._yard, +._mobile ._yii { + padding-left: 0; +} +._mobile ._simple h1, +._mobile ._angular h1, +._mobile ._apache h1, +._mobile ._async h1, +._mobile ._bootstrap h1, +._mobile ._cakephp h1, +._mobile ._codeception h1, +._mobile ._coffeescript h1, +._mobile ._cordova h1, +._mobile ._crystal h1, +._mobile ._cypress h1, +._mobile ._dart h1, +._mobile ._dojo h1, +._mobile ._elixir h1, +._mobile ._ember h1, +._mobile ._erlang h1, +._mobile ._express h1, +._mobile ._fluture h1, +._mobile ._github h1, +._mobile ._gnuplot h1, +._mobile ._go h1, +._mobile ._graphite h1, +._mobile ._hapi h1, +._mobile ._jekyll h1, +._mobile ._joi h1, +._mobile ._jq h1, +._mobile ._julia h1, +._mobile ._kubectl h1, +._mobile ._kubernetes h1, +._mobile ._liquid h1, +._mobile ._love h1, +._mobile ._lua h1, +._mobile ._mariadb h1, +._mobile ._meteor h1, +._mobile ._npm h1, +._mobile ._nushell h1, +._mobile ._octave h1, +._mobile ._openjdk h1, +._mobile ._perl h1, +._mobile ._phalcon h1, +._mobile ._phaser h1, +._mobile ._phpunit h1, +._mobile ._pug h1, +._mobile ._pygame h1, +._mobile ._qt h1, +._mobile ._ramda h1, +._mobile ._react_native h1, +._mobile ._reactivex h1, +._mobile ._rethinkdb h1, +._mobile ._rubydoc h1, +._mobile ._rust h1, +._mobile ._rxjs h1, +._mobile ._sanctuary h1, +._mobile ._sanctuary_def h1, +._mobile ._sanctuary_type_classes h1, +._mobile ._scala h1, +._mobile ._sinon h1, +._mobile ._sphinx_simple h1, +._mobile ._sqlite h1, +._mobile ._tcl_tk h1, +._mobile ._tensorflow h1, +._mobile ._terraform h1, +._mobile ._typescript h1, +._mobile ._vue h1, +._mobile ._webpack h1, +._mobile ._wordpress h1, +._mobile ._yard h1, +._mobile ._yii h1, +._mobile ._simple h2, +._mobile ._angular h2, +._mobile ._apache h2, +._mobile ._async h2, +._mobile ._bootstrap h2, +._mobile ._cakephp h2, +._mobile ._codeception h2, +._mobile ._coffeescript h2, +._mobile ._cordova h2, +._mobile ._crystal h2, +._mobile ._cypress h2, +._mobile ._dart h2, +._mobile ._dojo h2, +._mobile ._elixir h2, +._mobile ._ember h2, +._mobile ._erlang h2, +._mobile ._express h2, +._mobile ._fluture h2, +._mobile ._github h2, +._mobile ._gnuplot h2, +._mobile ._go h2, +._mobile ._graphite h2, +._mobile ._hapi h2, +._mobile ._jekyll h2, +._mobile ._joi h2, +._mobile ._jq h2, +._mobile ._julia h2, +._mobile ._kubectl h2, +._mobile ._kubernetes h2, +._mobile ._liquid h2, +._mobile ._love h2, +._mobile ._lua h2, +._mobile ._mariadb h2, +._mobile ._meteor h2, +._mobile ._npm h2, +._mobile ._nushell h2, +._mobile ._octave h2, +._mobile ._openjdk h2, +._mobile ._perl h2, +._mobile ._phalcon h2, +._mobile ._phaser h2, +._mobile ._phpunit h2, +._mobile ._pug h2, +._mobile ._pygame h2, +._mobile ._qt h2, +._mobile ._ramda h2, +._mobile ._react_native h2, +._mobile ._reactivex h2, +._mobile ._rethinkdb h2, +._mobile ._rubydoc h2, +._mobile ._rust h2, +._mobile ._rxjs h2, +._mobile ._sanctuary h2, +._mobile ._sanctuary_def h2, +._mobile ._sanctuary_type_classes h2, +._mobile ._scala h2, +._mobile ._sinon h2, +._mobile ._sphinx_simple h2, +._mobile ._sqlite h2, +._mobile ._tcl_tk h2, +._mobile ._tensorflow h2, +._mobile ._terraform h2, +._mobile ._typescript h2, +._mobile ._vue h2, +._mobile ._webpack h2, +._mobile ._wordpress h2, +._mobile ._yard h2, +._mobile ._yii h2, +._mobile ._simple h3, +._mobile ._angular h3, +._mobile ._apache h3, +._mobile ._async h3, +._mobile ._bootstrap h3, +._mobile ._cakephp h3, +._mobile ._codeception h3, +._mobile ._coffeescript h3, +._mobile ._cordova h3, +._mobile ._crystal h3, +._mobile ._cypress h3, +._mobile ._dart h3, +._mobile ._dojo h3, +._mobile ._elixir h3, +._mobile ._ember h3, +._mobile ._erlang h3, +._mobile ._express h3, +._mobile ._fluture h3, +._mobile ._github h3, +._mobile ._gnuplot h3, +._mobile ._go h3, +._mobile ._graphite h3, +._mobile ._hapi h3, +._mobile ._jekyll h3, +._mobile ._joi h3, +._mobile ._jq h3, +._mobile ._julia h3, +._mobile ._kubectl h3, +._mobile ._kubernetes h3, +._mobile ._liquid h3, +._mobile ._love h3, +._mobile ._lua h3, +._mobile ._mariadb h3, +._mobile ._meteor h3, +._mobile ._npm h3, +._mobile ._nushell h3, +._mobile ._octave h3, +._mobile ._openjdk h3, +._mobile ._perl h3, +._mobile ._phalcon h3, +._mobile ._phaser h3, +._mobile ._phpunit h3, +._mobile ._pug h3, +._mobile ._pygame h3, +._mobile ._qt h3, +._mobile ._ramda h3, +._mobile ._react_native h3, +._mobile ._reactivex h3, +._mobile ._rethinkdb h3, +._mobile ._rubydoc h3, +._mobile ._rust h3, +._mobile ._rxjs h3, +._mobile ._sanctuary h3, +._mobile ._sanctuary_def h3, +._mobile ._sanctuary_type_classes h3, +._mobile ._scala h3, +._mobile ._sinon h3, +._mobile ._sphinx_simple h3, +._mobile ._sqlite h3, +._mobile ._tcl_tk h3, +._mobile ._tensorflow h3, +._mobile ._terraform h3, +._mobile ._typescript h3, +._mobile ._vue h3, +._mobile ._webpack h3, +._mobile ._wordpress h3, +._mobile ._yard h3, +._mobile ._yii h3 { + margin-left: 0; +} +._simple blockquote > h4, +._angular blockquote > h4, +._apache blockquote > h4, +._async blockquote > h4, +._bootstrap blockquote > h4, +._cakephp blockquote > h4, +._codeception blockquote > h4, +._coffeescript blockquote > h4, +._cordova blockquote > h4, +._crystal blockquote > h4, +._cypress blockquote > h4, +._dart blockquote > h4, +._dojo blockquote > h4, +._elixir blockquote > h4, +._ember blockquote > h4, +._erlang blockquote > h4, +._express blockquote > h4, +._fluture blockquote > h4, +._github blockquote > h4, +._gnuplot blockquote > h4, +._go blockquote > h4, +._graphite blockquote > h4, +._hapi blockquote > h4, +._jekyll blockquote > h4, +._joi blockquote > h4, +._jq blockquote > h4, +._julia blockquote > h4, +._kubectl blockquote > h4, +._kubernetes blockquote > h4, +._liquid blockquote > h4, +._love blockquote > h4, +._lua blockquote > h4, +._mariadb blockquote > h4, +._meteor blockquote > h4, +._npm blockquote > h4, +._nushell blockquote > h4, +._octave blockquote > h4, +._openjdk blockquote > h4, +._perl blockquote > h4, +._phalcon blockquote > h4, +._phaser blockquote > h4, +._phpunit blockquote > h4, +._pug blockquote > h4, +._pygame blockquote > h4, +._qt blockquote > h4, +._ramda blockquote > h4, +._react_native blockquote > h4, +._reactivex blockquote > h4, +._rethinkdb blockquote > h4, +._rubydoc blockquote > h4, +._rust blockquote > h4, +._rxjs blockquote > h4, +._sanctuary blockquote > h4, +._sanctuary_def blockquote > h4, +._sanctuary_type_classes blockquote > h4, +._scala blockquote > h4, +._sinon blockquote > h4, +._sphinx_simple blockquote > h4, +._sqlite blockquote > h4, +._tcl_tk blockquote > h4, +._tensorflow blockquote > h4, +._terraform blockquote > h4, +._typescript blockquote > h4, +._vue blockquote > h4, +._webpack blockquote > h4, +._wordpress blockquote > h4, +._yard blockquote > h4, +._yii blockquote > h4, +._simple blockquote > h5, +._angular blockquote > h5, +._apache blockquote > h5, +._async blockquote > h5, +._bootstrap blockquote > h5, +._cakephp blockquote > h5, +._codeception blockquote > h5, +._coffeescript blockquote > h5, +._cordova blockquote > h5, +._crystal blockquote > h5, +._cypress blockquote > h5, +._dart blockquote > h5, +._dojo blockquote > h5, +._elixir blockquote > h5, +._ember blockquote > h5, +._erlang blockquote > h5, +._express blockquote > h5, +._fluture blockquote > h5, +._github blockquote > h5, +._gnuplot blockquote > h5, +._go blockquote > h5, +._graphite blockquote > h5, +._hapi blockquote > h5, +._jekyll blockquote > h5, +._joi blockquote > h5, +._jq blockquote > h5, +._julia blockquote > h5, +._kubectl blockquote > h5, +._kubernetes blockquote > h5, +._liquid blockquote > h5, +._love blockquote > h5, +._lua blockquote > h5, +._mariadb blockquote > h5, +._meteor blockquote > h5, +._npm blockquote > h5, +._nushell blockquote > h5, +._octave blockquote > h5, +._openjdk blockquote > h5, +._perl blockquote > h5, +._phalcon blockquote > h5, +._phaser blockquote > h5, +._phpunit blockquote > h5, +._pug blockquote > h5, +._pygame blockquote > h5, +._qt blockquote > h5, +._ramda blockquote > h5, +._react_native blockquote > h5, +._reactivex blockquote > h5, +._rethinkdb blockquote > h5, +._rubydoc blockquote > h5, +._rust blockquote > h5, +._rxjs blockquote > h5, +._sanctuary blockquote > h5, +._sanctuary_def blockquote > h5, +._sanctuary_type_classes blockquote > h5, +._scala blockquote > h5, +._sinon blockquote > h5, +._sphinx_simple blockquote > h5, +._sqlite blockquote > h5, +._tcl_tk blockquote > h5, +._tensorflow blockquote > h5, +._terraform blockquote > h5, +._typescript blockquote > h5, +._vue blockquote > h5, +._webpack blockquote > h5, +._wordpress blockquote > h5, +._yard blockquote > h5, +._yii blockquote > h5 { + margin-top: 0.25rem; +} +._angular .breadcrumbs { + padding-left: 2em; +} +._angular img { + margin: 1em 0; +} +._angular .location-badge { + font-style: italic; + text-align: right; +} +._angular td h3 { + margin: 0 !important; +} +._angularjs .nav-index-section { + margin: 1.5em 0 1em -2em; + list-style: none; + font-weight: var(--boldFontWeight); + text-transform: capitalize; +} +._angularjs h3, +._angularjs h4 { + font-size: 1rem; +} +._angularjs .view-source, +._angularjs .improve-docs { + order: 1; + display: block; + vertical-align: top; + padding-left: 1em; + font-size: 0.875rem; +} +._angularjs .defs { + padding-left: 1rem; + list-style: none; +} +._angularjs .defs > li > h3:first-child { + margin: 0 0 1em -1rem; +} +._angularjs .defs > li + li { + margin-top: 2em; +} +._angularjs .defs h4 { + margin: 1em 0 0.5em; + font-size: 1em; +} +._angularjs .defs ul { + list-style-type: disc; +} +._async h3 > .type-signature { + float: right; + color: var(--textColorLight); +} +._async h3 > .signature-attributes { + font-size: 0.75rem; + font-weight: normal; + font-style: italic; + color: var(--textColorLighter); +} +._bash th[align="left"] { + border-left: 1px solid var(--boxBorder); +} +._bootstrap h2 > small { + color: var(--textColorLight); + float: right; +} +._bootstrap .h5 { + font-size: 1.25rem; +} +._bootstrap .bs-callout > h4, +._bootstrap .bs-callout > h5 { + margin-top: 0.25rem; +} +._bootstrap p.bs-example { + padding: 0.375rem 0.625rem; + line-height: 1.5; +} +._bootstrap a.thumbnail { + display: block; + padding: 0.25em; +} +._bootstrap a.thumbnail:after { + content: none; +} +._bootstrap a.thumbnail + h4 { + margin: 0.75em 0 0.5em; +} +._bootstrap a.thumbnail > img { + display: block; +} +._bootstrap .col { + margin-bottom: 1.5em; +} +._bootstrap .d-block { + display: block; +} +@media (min-width: 800px) { + ._bootstrap .row { + display: flex; + flex-wrap: wrap; + } + ._bootstrap .col { + flex: 0 1 auto; + padding: 0 1em; + width: 33.33%; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + ._bootstrap .col-md-6 { + width: 50%; + } +} +._cppref .t-li1 { + margin: 0 0 1em; +} +._cppref .t-mark, +._cppref .t-mark-rev { + white-space: nowrap; +} +._cppref .t-dcl-begin pre { + margin: 0; + padding: 0; + line-height: inherit; + background: none; + border: 0; +} +._cppref .t-lines > span { + display: block; +} +._cppref .t-spar { + font-style: italic; + color: var(--textColorLight); +} +._cppref .t-sdsc-nopad dl, +._cppref .t-sdsc-nopad dd { + margin: 0; +} +._cppref td > h3, +._cppref td > h5 { + margin: 0 0 0.5em; + line-height: inherit; +} +._cppref td > h3:only-child, +._cppref td > h5:only-child { + margin: 0; +} +._cppref td > ul, +._cppref td > dl { + margin: 0.5em 0; +} +._cppref td > ul:only-child, +._cppref td > dl:only-child { + margin: 0; +} +._cppref td > .t-dsc-member-div > div { + float: left; +} +._cppref td > .t-dsc-member-div > div + div { + margin-left: 0.5em; +} +._cppref td > table { + margin: 0; +} +._cppref .t-dcl-rev-aux > td:empty { + padding: 0; +} +._cppref .t-inheritance-diagram { + display: table; + margin: 1rem 0; + padding: 0.375rem; + font-size: 0.75rem; + border: 1px solid var(--boxBorder); + border-radius: 2px; +} +._cppref ul > ul { + margin: 0 0 0.5em; +} +._cakephp h3 > .source { + float: right; +} +._cakephp h3 > a, +._cakephp span.label, +._cakephp span.php-keyword1 { + font-weight: normal; +} +._cakephp h4 { + margin: 1.5em 0; +} +._cakephp dl { + margin: 1em 0; +} +._clojure .type { + float: right; + font-size: 0.9em; + color: var(--textColorLight); +} +._coffeescript > .code { + margin: 1.5em 0; + overflow: hidden; +} +._coffeescript > .code > pre { + float: left; + width: 49%; + margin: 0; +} +._coffeescript > .code > pre:last-child { + float: right; +} +._cordova .compat .n { + background: pink; +} +._cordova .compat .y { + background: lightgreen; +} +._cordova .compat .p { + background: khaki; +} +._crystal .entry-detail { + margin-top: 1em; +} +._crystal .view-source { + float: right; +} +._crystal .superclass-hierarchy { + list-style: none; + padding: 0; + overflow: hidden; +} +._crystal li.superclass { + float: left; + margin: 0 0.5em 0 0; + padding: 0; +} +._crystal li.superclass + li.superclass:before { + content: "<"; + margin-right: 0.5em; +} +._cypress .note h1 { + margin-left: inherit; +} +._d .d_decl > small { + color: var(--textColorLight); +} +._d .d_decl > strong { + font-weight: var(--bolderFontWeight); +} +._d span.red { + color: var(--textColorRed); +} +._d3 > h4 { + font-size: 1rem; +} +._d3 > h6 > .source { + float: right; + font-weight: normal; +} +._dart dl:not(.dl-horizontal) dt .features, +._dart .multi-line-signature .features { + float: right; + color: var(--textColorLight); +} +._dojo .jsdoc-inheritance { + color: var(--textColorLight); +} +._elixir .type-detail { + margin-bottom: 2em; +} +._elixir .type-detail pre { + margin-left: -1rem; +} +._mobile ._elixir .type-detail pre { + margin-left: 0; +} +._elixir a.source { + float: right; + font-size: 0.9em; +} +._elisp dl[compact] > dt { + background: none; + border-color: none; + line-height: normal; + margin: auto; + border: none; +} +._ember h3 > .access { + float: right; + color: var(--textColorLight); + font-weight: normal; +} +._ember h3 > .args, +._ember h3 > .return-type { + font-weight: normal; +} +._ember p.github-link { + color: var(--textColorLight); +} +._erlang h3 > code { + display: block; +} +._erlang .note .label, +._erlang .warning .label { + font-weight: var(--boldFontWeight); +} +._erlang .since { + color: var(--textColorLight); + font-weight: normal; + font-size: small; +} +._fastapi .tabbed-block { + border: 1px dashed black; + padding: 0.5rem 1rem 0; + margin-bottom: 1rem; +} +._fastapi .tabbed-block label { + font-weight: var(--bolderFontWeight); +} +._fastapi .admonition-title { + font-weight: var(--bolderFontWeight); +} +._fluture pre > code { + font-size: inherit; +} +._git { + padding-left: 1rem; +} +._git > h1, +._git > h2, +._git > .reference-menu, +._git > .callout, +._git > h1 + .sectionbody { + margin-left: -1rem; +} +._git h3 { + font-size: 1rem; +} +._git em { + font-style: normal; +} +._gnuplot .CENTER { + text-align: center; +} +._go #short-nav, +._go table.dir { + margin-left: -1rem; +} +._go a.source, +._go span[title^="Added in Go"] { + float: right; + font-size: 0.9em; +} +._groovy { + padding-left: 1rem; +} +._groovy h1, +._groovy h2 { + margin-left: -1rem; +} +._gtk { + padding-left: 1rem; +} +._gtk h1, +._gtk h2, +._gtk h3 { + margin-left: -1rem; +} +._gtk div.toc { + margin-top: 1.5em; +} +._gtk .toc dl { + margin-top: 0; + margin-bottom: 0; +} +._gtk .gallery-float { + float: left; +} +._hapi pre > code { + font-size: inherit; +} +._haproxy { + padding-left: 1rem; +} +._haproxy h1, +._haproxy h2, +._haproxy h3 { + margin-left: -1rem; +} +._mobile ._haproxy { + padding-left: 0; +} +._mobile ._haproxy h1, +._mobile ._haproxy h2, +._mobile ._haproxy h3 { + margin-left: 0; +} +._haproxy .pagination-centered { + text-align: center; +} +._haproxy .pull-right { + float: right !important; +} +._haproxy pre.text { + background: var(--contentBackground); + border-width: 0px; +} +._haproxy td.alert-success { + background: var(--noteGreenBackground); +} +._haproxy td.alert-error { + background: var(--noteRedBackground); +} +._haskell-api h4 { + font-size: 1em; +} +._haskell-api .module + .package, +._haskell-api p.src > .link { + float: right; +} +._haskell-api .src { + white-space: normal; +} +._haskell-api p.src { + font-size: 0.8125rem; +} +._haskell-api dt.src { + white-space: normal; +} +._haskell-api > .subs { + margin-left: 2em; +} +._haskell-api .subs p.src { + margin-top: 1em; +} +._haskell-api table { + margin: 1em 0; +} +._haskell-api td > pre { + margin: 0; +} +._joi pre > code { + font-size: inherit; +} +._jq .manual-example table { + border: none; +} +._jq .manual-example table td { + border: none; +} +._jq .manual-example table td.jqprogram { + font-weight: bold; +} +._jq .manual-example table th { + color: var(--textColor); + background: var(--contentBackground); + text-align: right; + border: none; +} +._jq .manual-example table tr:not(:first-child) th:not(:empty), +._jq .manual-example table tr:not(:first-child) th:not(:empty) + td { + border-top: 1px solid var(--boxBorder); +} +._jquery h2.entry-title { + margin: 0 0 1.5rem; + font-size: 1rem; + font-weight: normal; +} +._jquery .entry-summary { + margin: -1rem 0 1.5rem; + padding-right: 1.5rem; +} +._jquery .post:not(:only-of-type), +._jquery .page:not(:only-of-type) { + width: 50%; + float: left; +} +._jquery .post:not(:only-of-type):nth-of-type(2n + 1), +._jquery .page:not(:only-of-type):nth-of-type(2n + 1) { + clear: both; +} +._jquery .toc > h4 { + font-size: inherit; +} +._jquery .toc-list { + margin-top: 0; + font-weight: var(--boldFontWeight); +} +._jquery .toc-list > li + li { + margin-top: 1em; +} +._jquery .toc-list > li > ul { + font-weight: normal; +} +._jquery .toc-list > li > ul > li + li { + margin-top: 0; +} +._jquery .name > .version-details, +._jquery .section-title > .version-details, +._jquery .returns, +._jquery .option-type { + float: right; + font-weight: var(--boldFontWeight); + margin-left: 1em; +} +._jquery .signatures { + padding: 0; + list-style: none; +} +._jquery .signature + .signature { + margin-top: 1em; +} +._jquery .signature > .name { + margin-top: 1em; +} +._jquery .signature > ul { + padding-left: 1em; + list-style: none; +} +._jquery .signature > ul > li + li { + margin-top: 1em; +} +._jquery .signature > ul > li > ul { + list-style-type: disc; +} +._jquery .entry-example > h4 { + margin: 2em 0 1.5em; + line-height: inherit; + font-size: inherit; + font-weight: normal; +} +._jquery #quick-nav { + margin-bottom: 2em; + max-width: 38em; + overflow: hidden; +} +._jquery #quick-nav > h2 { + margin: 0.25rem 0 1rem; + font-size: 1rem; +} +._jquery #quick-nav > h2 > a { + float: right; +} +._jquery .quick-nav-section { + width: 33%; + float: left; +} +._jquery .quick-nav-section > h3 { + margin: 0 0 0.5em; + font-size: inherit; +} +._jquery .api-item { + padding-left: 1rem; +} +._jquery .api-item > h3 { + margin-left: -1rem; +} +._jquery .name > a, +._jquery .version-details > a { + color: inherit; +} +._julia .docstring-category { + float: right; +} +._kotlin td > pre { + margin: 0.5em 0; +} +._laravel h4 { + font-size: 1em; +} +._love .smwtable { + width: 100%; +} +._love .smwtable td:nth-last-child(2), +._love .smwtable td:last-child { + width: 2.5em; +} +._love .cell-orange { + background: var(--noteOrangeBackground); +} +._love .cell-green { + background: var(--noteGreenBackground); +} +._love .cell-red { + background: var(--noteRedBackground); +} +._lua .apii { + float: right; +} +._mdn { + container-type: inline-size; +} +._mdn .index { + -webkit-columns: 16em; + -moz-columns: 16em; + columns: 16em; +} +._mdn .index > span { + display: block; + font-size: 1rem; + font-weight: var(--boldFontWeight); +} +._mdn .index ul, +._mdn .index ol { + margin: 0 0 1em; + padding: 0; + line-height: 1.5; + list-style: none; +} +._mdn .index li { + padding-left: 1em; +} +._mdn > h4 { + font-size: 1em; +} +._mdn > .note em { + font-style: normal; + font-weight: var(--boldFontWeight); +} +._mdn > .note > ul { + margin: 1em 0; +} +._mdn > .note > p:last-child, +._mdn > .note > ul:last-child { + margin-bottom: 0; +} +._mdn .inlineIndicator { + white-space: nowrap; +} +._mdn .syntaxbox a, +._mdn .twopartsyntaxbox a, +._mdn .inlineIndicator > a { + color: inherit; +} +._mdn .htmlelt, +._mdn .cssprop { + display: table; +} +._mdn .htmlelt > li, +._mdn .cssprop > li { + display: table-row; + margin: 0; +} +._mdn .htmlelt > li > dfn, +._mdn .cssprop > li > dfn { + display: table-cell; + padding: 0.125rem 1.5rem 0.125rem 0; + white-space: pre; + border: 0; + cursor: inherit; +} +._mdn .htmlelt > li > dfn:after, +._mdn .cssprop > li > dfn:after { + content: ":"; +} +._mdn .htmlelt th, +._mdn .htmlelt td, +._mdn .cssprop th, +._mdn .cssprop td { + background: none; + border: 0; +} +._mdn dt > strong > code, +._mdn dl > dt > code { + font-family: inherit; + font-weight: var(--boldFontWeight); + font-size: inherit; +} +._mdn .eventinfo > dd + dt { + margin-top: 0; +} +._mdn .cleared { + clear: both; +} +._mdn code > strong { + font-weight: normal; +} +._mdn .bc-github-link { + float: right; + font-size: 0.75rem; +} +._mdn .bc-supports-yes, +._mdn .bc-supports-yes + dd, +._mdn .bc-supports-yes + dd + dd { + background: var(--noteGreenBackground); +} +._mdn .bc-supports-unknown, +._mdn .bc-supports-unknown + dd, +._mdn .bc-supports-unknown + dd + dd { + background: var(--noteBackground); +} +._mdn .bc-supports-partial, +._mdn .bc-supports-partial + dd, +._mdn .bc-supports-partial + dd + dd { + background: var(--noteOrangeBackground); +} +._mdn .bc-supports-no, +._mdn .bc-supports-no + dd, +._mdn .bc-supports-no + dd + dd { + background: var(--noteRedBackground); +} +._mdn .bc-table { + min-width: 100%; +} +._mdn .bc-table dl { + margin: 0.25rem 0 0; + padding: 0.25rem 0 0; + font-size: 0.75rem; + border-top: 1px solid var(--boxBorder); +} +._mdn .bc-table dd { + margin: 0; +} +._mdn .interactive { + width: 100%; + height: 680px; +} +._mdn .interactive.is-js-height { + height: 520px; +} +._mdn .interactive.is-shorter-height { + height: 440px; +} +._mdn .interactive.is-taller-height { + height: 730px; +} +._mdn .interactive.is-tabbed-shorter-height { + height: 490px; +} +._mdn .interactive.is-tabbed-standard-height { + height: 550px; +} +._mdn .interactive.is-tabbed-taller-height { + height: 780px; +} +@container (min-width: 594px) { + ._mdn .interactive { + height: 380px; + } + ._mdn .interactive.is-js-height { + height: 450px; + } + ._mdn .interactive.is-shorter-height { + height: 370px; + } + ._mdn .interactive.is-taller-height { + height: 660px; + } + ._mdn .interactive.is-tabbed-shorter-height { + height: 360px; + } + ._mdn .interactive.is-tabbed-standard-height { + height: 430px; + } + ._mdn .interactive.is-tabbed-taller-height { + height: 640px; + } +} +._meteor dl.args { + margin-left: 1rem; +} +._meteor .api-heading { + overflow: hidden; +} +._meteor .api-heading > code { + font-weight: var(--boldFontWeight); +} +._meteor .locus, +._meteor .src-code { + float: right; +} +._meteor .locus, +._meteor .type, +._meteor .src-code { + margin-left: 0.5em; +} +._meteor h2 .subtext-api { + margin-top: 0.25rem; +} +._meteor .locus, +._meteor .subtext-api, +._meteor .subtext-api > code { + font-size: 0.75rem; +} +._meteor .locus, +._meteor .type { + color: var(--textColorLight); +} +._mkdocs strong { + font-weight: var(--bolderFontWeight); +} +._modernizr h4 { + font-size: 1em; +} +._moment > h3 > span { + float: right; +} +._moment h4 { + font-size: 1em; +} +._nginx .directive { + margin: 2.5em 0 1em; +} +._nginx td > pre { + margin: 0; +} +._node .api_stability { + clear: both; +} +._node > h2 + h2, +._node > h3 + h3 { + margin-top: 0; +} +._node p > code, +._node li > code, +._node .type { + white-space: normal; +} +._node .api_metadata { + float: right; + margin: 0 0 1em 1em; +} +._node .srclink { + float: right; +} +._node details > table { + margin: 0; +} +._npm .pageColumns { + padding-left: 0; + list-style: none; +} +._npm .faint.heading { + font-size: 0.9em; + color: var(--textColorLight); +} +._npm .youtube-video iframe { + width: 420px; + height: 315px; +} +._nushell pre > code { + font-size: inherit; +} +._openjdk ul.inheritance { + list-style: none; +} +._openjdk > ul.inheritance ul.inheritance { + margin: 0; +} +._perl dt + dt { + margin-top: 1em; +} +._phalcon h3 > small { + float: right; + color: var(--textColorLight); +} +._phaser .type-signature, +._phaser dt.tag-source { + color: #666; + font-weight: normal; +} +._php h1 { + margin-top: 0; +} +._php .manualnavbar { + margin-top: 1rem; +} +._php .verinfo { + float: right; + font-weight: var(--boldFontWeight); +} +._php .classsynopsisinfo_comment { + color: var(--textColorLight); +} +._php .classsynopsisinfo_comment, +._php .classsynopsis > .constructorsynopsis, +._php .classsynopsis > .methodsynopsis, +._php .classsynopsis > .fieldsynopsis { + margin-left: 1em; +} +._php blockquote.note > p { + margin-bottom: 0; +} +._phpunit .warning > h3, +._phpunit .alert > h3 { + margin: 0 0 0.5em; + font-size: 1em; +} +._postgres { + padding-left: 1rem; +} +._postgres h1, +._postgres h1 ~ p, +._postgres h1 ~ pre, +._postgres h1 ~ ul, +._postgres h1 ~ blockquote, +._postgres h2, +._postgres .navfooter { + margin-left: -1rem; +} +._postgres blockquote > h3 { + font-size: 0.875rem; + margin: 0 0 0.25rem; +} +._postgres p.c2 { + font-weight: var(--boldFontWeight); +} +._postgres .navfooter > table { + width: 100%; +} +._postgres td[align="center"] { + text-align: center; +} +._postgres td[align="right"] { + text-align: right; +} +._pug .alert h6 { + margin-top: 0.25rem; +} +._pygame .line-block > .line:first-child { + margin-bottom: 1em; +} +._pygame .line-block > .line:only-child { + margin-bottom: 0em; +} +._pygame span.signature { + font-family: monospace; +} +._python h2 > a, +._python h3 > a, +._python dt[id] > a.external, +._python dt[id] > a.internal { + float: none !important; +} +._qt h3.fn > code { + float: right; + color: var(--textColorLight); +} +._ramda h3 > small { + float: right; +} +._ramda ul { + margin-top: 1em; +} +._rdoc > .description, +._rdoc > .documentation-section { + padding-left: 1rem; +} +._rdoc > .description > h2, +._rdoc header > h3, +._rdoc .method-heading { + margin-left: -1rem; +} +._rdoc .description > h1 { + font-size: 1rem; +} +._rdoc .method-description > h2, +._rdoc h3, +._rdoc h4, +._rdoc h5, +._rdoc h6 { + font-size: 1em; +} +._rdoc .method-heading { + font-weight: var(--boldFontWeight); +} +._rdoc .method-heading + .method-heading { + margin-top: -0.5em; +} +._rdoc > .meta > dd { + margin: 0; +} +._rdoc > .meta > dd + dt { + margin-top: 0.5em; +} +._rdoc a.method-click-advice { + float: right; + font-size: 0.75rem; + color: var(--linkColor); + cursor: pointer; +} +._rdoc a.method-click-advice:hover { + text-decoration: underline; +} +@media print { + ._rdoc a.method-click-advice { + display: none; + } +} +._rdoc .method-source-code { + display: none; +} +._react_native .deprecatedTitle { + font-weight: var(--boldFontWeight); +} +._react_native span.platform { + float: right; +} +._react_native span.propType, +._react_native span.platform { + font-weight: normal; +} +._react_native .label { + display: inline-block; + font-size: 0.85rem; +} +._react_native .label::before { + content: "["; +} +._react_native .label::after { + content: "]"; +} +._reactivex img { + max-width: 50%; +} +._reactivex figure { + margin: 0; +} +._reactivex dfn { + cursor: text; + font-style: italic; + text-decoration: none; + border-bottom: none; +} +._reactivex #tree dt, +._reactivex #tree dd { + font-weight: normal; +} +._reactivex #tree dt { + float: left; + clear: left; + margin-top: 0; +} +._reactivex #tree dt:before { + content: "\2026"; +} +._reactivex #tree dd:not(.sub) { + float: left; + margin: 0 0 0 5px; + padding: 0; +} +._reactivex #tree dl#outer > dt { + font-weight: bold; + margin-top: 5px; +} +._reactivex #tree dl#outer > dt + dd { + margin-top: 5px; +} +._redis { + padding-left: 1rem; +} +._redis > .commands { + padding-left: 0; + list-style: none; +} +._redis > .commands > li { + margin-bottom: 1em; +} +._redis .command, +._redis .summary { + display: block; +} +._redis .args { + font-size: 0.75rem; + color: var(--textColorLight); +} +._redis > h1, +._redis > h2, +._redis > .metadata, +._redis > h1 ~ p, +._redis > h1 + pre { + margin-left: -1rem; +} +._redis > h2 ~ p { + margin-left: 0; +} +._redis > .metadata > p { + margin: 0; +} +._redis > .example { + white-space: normal; +} +._redis > .example > .prompt { + float: left; + margin-right: 0.5em; + color: var(--textColorLight); +} +._redis > .example > code { + display: block; + clear: left; + margin-bottom: 0.5em; +} +._redis > .example > code:last-child { + margin-bottom: 0; +} +._rethinkdb .api_command_illustration { + float: right; + margin: 0 0 1em 1em; +} +._rfc-pre { + font-size: 0.8125rem; + min-width: 38rem; +} +._rfc-pre > h3, +._rfc-pre > h4 { + font-size: 0.875rem; +} +._rfc-pre > h1, +._rfc-pre > h2, +._rfc-pre > h3, +._rfc-pre > h4, +._rfc-pre > h5 { + margin: 0; + font-family: var(--baseFont); +} +._rubydoc h4 + ul { + margin-top: 1em; +} +._rust .docblock { + margin-left: 1em; +} +._rust div.information > pre, +._rust div.important-traits > pre { + margin: 0.5rem 0; +} +._rust div.stability { + margin-bottom: 1em; +} +._rust .out-of-band { + float: right; +} +._rust .since, +._rust .srclink { + float: right; + margin-left: 0.5rem; +} +._rxjs .breadcrumbs { + padding-left: 2em; +} +._rxjs img { + margin: 1em 0; +} +._rxjs .location-badge { + font-style: italic; + text-align: right; +} +._rxjs td h3 { + margin: 0 !important; +} +._sanctuary pre > code { + font-size: inherit; +} +._sanctuary_def pre > code { + font-size: inherit; +} +._sanctuary_type_classes pre > code { + font-size: inherit; +} +._scala .attributes dl, +._scala .attributes pre { + margin: 0; +} +._scala .related-types { + margin: 0; + white-space: normal; +} +._scala .links { + margin-left: -1rem; + text-align: center; + padding: 0.5em; +} +._scala .links a { + padding: 0.4em; +} +@media print { + ._scala .links { + display: none; + } +} +._scala .source-link { + float: right; + font-size: 0.75rem; + color: var(--linkColor); + cursor: pointer; +} +._scala .source-link:hover { + text-decoration: underline; +} +@media print { + ._scala .source-link { + display: none; + } +} +._python h4, +._sphinx h4 { + font-size: 1em; +} +._python dt + dt, +._sphinx dt + dt { + margin-top: -0.5em; +} +._python .versionmodified, +._sphinx .versionmodified, +._python span.title, +._sphinx span.title, +._python .topic-title, +._sphinx .topic-title { + display: block; + font-weight: var(--boldFontWeight); +} +._python ul.simple, +._sphinx ul.simple { + margin: 1em 0; +} +._python h2 > a, +._sphinx h2 > a, +._python h3 > a, +._sphinx h3 > a, +._python dt[id] > a.external, +._sphinx dt[id] > a.external, +._python dt[id] > a.internal, +._sphinx dt[id] > a.internal { + float: right; +} +._python .admonition-title, +._sphinx .admonition-title { + float: left; + margin: 0 0.5em 0 0; + font-weight: var(--boldFontWeight); +} +._python .admonition-title:after, +._sphinx .admonition-title:after { + content: ":"; +} +._python .admonition > dl, +._sphinx .admonition > dl, +._python .admonition > ul, +._sphinx .admonition > ul { + clear: left; + margin: 0; +} +._python .admonition-title + dl, +._sphinx .admonition-title + dl { + padding-top: 0.5em; +} +._python td > div, +._sphinx td > div { + margin: 0 !important; +} +._python .classifier:before, +._sphinx .classifier:before { + content: ": "; +} +._python .property::after, +._sphinx .property::after { + content: " "; +} +._python span.descclassname, +._sphinx span.descclassname, +._python span.descname, +._sphinx span.descname { + font-family: var(--monoFont); +} +nav[aria-label="Page navigation"] { + display: flex !important; + justify-content: space-between !important; +} +._sphinx_simple .admonition-title { + margin: 0 0 0.25rem; + font-weight: var(--boldFontWeight); +} +svg text.fill { + fill: var(--textColor); +} +svg .fill { + fill: var(--textColorLighter); +} +svg .stroke { + fill: none; + stroke-width: 2.16; + stroke: var(--textColorLighter); +} +._support_tables > .stats tr.show-all ~ tr { + display: none; +} +._support_tables > .stats.show-all tr.show-all { + display: none; +} +._support_tables > .stats.show-all tr.show-all ~ tr { + display: table-row; +} +._support_tables > .stats td, +._support_tables > .stats th { + position: relative; + text-align: center; + min-width: 5rem; +} +._support_tables > .stats sup { + position: absolute; + top: 0; + right: 2px; + font-size: 0.625rem; +} +._support_tables > .stats tr.current { + font-weight: var(--boldFontWeight); + font-size: 1rem; +} +._support_tables > .stats td { + padding: 0.125rem 0.25rem; + cursor: default; +} +._support_tables > .stats td.y { + color: white; + background: #39b54a; +} +._support_tables > .stats td.n, +._support_tables > .stats td.p { + color: white; + background: #c44230; +} +._support_tables > .stats td.a { + color: white; + background: #a8bd04; +} +._support_tables > .stats td.u { + color: white; + background: #838383; +} +._support_tables > .stats th.show-all { + background: none; + border-bottom: 0; +} +._support_tables > .stats a.show-all { + display: block; +} +._tailwindcss .colors { + display: flex; + flex-direction: column; + gap: 1.2rem; + margin-bottom: 1rem; +} +._tailwindcss .color > div:first-child { + font-weight: bold; +} +._tailwindcss .color-swatch-group { + display: flex; + gap: 1rem; + flex-wrap: wrap; +} +._tailwindcss .color-swatch-container { + display: inline-block; +} +._tailwindcss .color-swatch { + width: 120px; + height: 40px; + border-radius: 4px; +} +._tailwindcss .color-tone-information { + display: flex; + justify-content: space-between; +} +._tailwindcss .long-quick-reference { + max-height: 40vh; + width: fit-content; + overflow-y: auto; + padding: 0.3rem; + border-top: 1px solid var(--textColor); + border-bottom: 1px solid var(--textColor); +} +._tcl_tk dl { + margin: 0.5em 0; +} +._tensorflow h3 + h3 { + margin-top: 0.25rem; +} +._tensorflow > .toc ul ul { + margin: 0.25rem 0; +} +._tensorflow table { + float: inherit; +} +._underscore { + padding-left: 1rem; +} +._underscore > h1, +._underscore > h2, +._underscore .header { + margin-left: -1rem; +} +._underscore .header { + display: inline-block; + vertical-align: top; + margin-bottom: 1em; +} +._underscore > p[id] { + margin-top: 2rem; +} +._underscore > pre { + margin-top: 1em; +} +._underscore .header + code { + margin-left: 1em; +} +._underscore .alias { + margin-left: 1em; + font-style: italic; +} +._wordpress .breadcrumbs { + display: none; +} +._yard .tag_title { + font-weight: var(--boldFontWeight); +} +._yii .detail-header-tag, +._yii .detailHeaderTag { + float: right; + color: var(--textColorLight); +} diff --git a/src/sidebar/DevdocBrowseView.js b/src/sidebar/DevdocBrowseView.js new file mode 100644 index 0000000..c3a21b7 --- /dev/null +++ b/src/sidebar/DevdocBrowseView.js @@ -0,0 +1,248 @@ +import Gdk from "gi://Gdk"; +import Gtk from "gi://Gtk"; +import Gio from "gi://Gio"; +import GLib from "gi://GLib"; +import GObject from "gi://GObject"; +import Webkit from "gi://WebKit"; + +import DocumentationPage from "./DocumentationPage.js"; +import { decode } from "../util.js"; + +import Template from "./BrowseView.blp" with { type: "uri" }; + +// Biblioteca is GTK4 only; these are GTK 3 libraries +// we only support gi-docgen and gtk3 uses gtk-doc + +const ITEM_HEIGHT = 38; + +class BrowseView extends Gtk.ScrolledWindow { + constructor(...params) { + super(params); + + this.root_model = Gio.ListStore.new(DocumentationPage); + this.#createBrowseSelectionModel(); + this.#loadDocs().catch(console.error); + + this._scrolled_to = false; + this._adj = this._browse_list_view.get_vadjustment(); + this._adj.connect("value-changed", () => { + this.#adjustScrolling(); + }); + + const gesture_click = new Gtk.GestureClick({ button: 0 }); + this._browse_list_view.add_controller(gesture_click); + gesture_click.connect("pressed", this.#onGestureClick); + + this._browse_list_view.connect("activate", (list_view, pos) => { + const row = this._tree_model.get_row(pos); + row.expanded = !row.expanded; + }); + } + + get webview() { + if (this._webview === undefined) this._webview = null; + return this._webview; + } + + set webview(value) { + if (this._webview === value) return; + this._webview = value; + this.notify("webview"); + } + + selectItem(path) { + const index = this.#getItemIndex(path); + // If possible, overshoot scrolling by one row to ensure selected row is visible + index + 1 === this.selection_model.n_items + ? this._browse_list_view.scroll_to(index, Gtk.ListScrollFlags.NONE, null) + : this._browse_list_view.scroll_to( + index + 1, + Gtk.ListScrollFlags.NONE, + null, + ); + this.selection_model.selected = index; + this._scrolled_to = true; + } + + unselectSelection() { + this.selection_model.unselect_item(this.selection_model.selected); + } + + collapseAllRows() { + for (let i = 0; i < this._tree_model.n_items; i++) { + const row = this._tree_model.get_row(i); + row.expanded = false; + } + } + + #onGestureClick = (gesture, n_press, x, y) => { + switch (gesture.get_current_button()) { + case Gdk.BUTTON_MIDDLE: { + const index = Math.floor((this._adj.value + y) / ITEM_HEIGHT); + const uri = this._tree_model.get_row(index).item.uri; + this.activate_action("app.new-tab", new GLib.Variant("s", uri)); + break; + } + } + }; + + #adjustScrolling() { + if (this._scrolled_to) { + const index = this.selection_model.selected; + const bottom_edge = (index + 1) * ITEM_HEIGHT - this._adj.value; + const top_edge = bottom_edge - ITEM_HEIGHT; + // If row is not visible after scroll_to, adjust + if (bottom_edge === 0) { + this._adj.value -= ITEM_HEIGHT; + } else if (top_edge === this._adj.page_size) { + this._adj.value += ITEM_HEIGHT; + } + this._scrolled_to = false; + } + } + + #getItemIndex(path) { + let relative_index = 0; // Relative index of the item under its parent + let absolute_index = 0; // Index of the item in the entire model + let skip = 0; // Number of items to skip due to expanded rows + + for (let i = 0; i < path.length; i++) { + while (relative_index < path[i]) { + const row = this._tree_model.get_row(absolute_index); + if (row.expanded) { + skip += row.children.get_n_items(); + } + if (!skip) relative_index++; // Go to next sibling + else skip--; + absolute_index++; + } + // Check to ensure the last item is not expanded + if (i < path.length - 1) { + this._tree_model.get_row(absolute_index).expanded = true; + absolute_index++; + relative_index = 1; + } + } + return absolute_index; + } + + #createBrowseSelectionModel() { + this._tree_model = Gtk.TreeListModel.new( + this.root_model, + false, + false, + (item) => item.children, + ); + this.selection_model = Gtk.SingleSelection.new(this._tree_model); + this.selection_model.can_unselect = true; + this.selection_model.connect("selection-changed", () => { + if (!this.selection_model.selected_item) return; + if (this.selection_model.selected_item.item.html) { + this.webview.load_html( + this.selection_model.selected_item.item.html, + null, + ); + return; + } + // If selection changed to sync the sidebar, dont load_uri again + const uri = this.selection_model.selected_item.item.uri; + if (this.webview.uri === uri) { + return; + } + this.webview.load_uri(uri); + }); + this._browse_list_view.model = this.selection_model; + } + + async #loadDocs() { + await this.#readIndex( + Gio.File.new_for_path("src/sidebar/db.json"), + Gio.File.new_for_path("src/sidebar/index.json"), + "JavaScript", + ); + this.emit("browse-view-loaded"); + } + + async #readIndex(dbjson, indexjson, docset_name) { + let [data] = await indexjson.load_contents_async(null); + const index = JSON.parse(decode(data)); + + [data] = await dbjson.load_contents_async(null); + const db = JSON.parse(decode(data)); + + const doc = new DocumentationPage({ + name: docset_name, + search_name: docset_name, + uri: `index.html`, + html: db["index"], + children: this.#newListStore(), + }); + this.root_model.insert_sorted(doc, this.#sortFunc); + const types = {}; + for (const type of index.types) { + const type_doc = new DocumentationPage({ + name: type.name, + search_name: type.name, + // html: db[type.slug], + children: this.#newListStore(), + }); + types[type.name] = type_doc; + doc.children.insert_sorted(type_doc, this.#sortFunc); + } + for (const item of index.entries) { + const item_doc = new DocumentationPage({ + name: item.name, + search_name: item.name, + uri: item.path, + html: db[item.path], + }); + types[item.type].children.insert_sorted(item_doc, this.#sortFunc); + } + } + + #sortFunc(doc1, doc2) { + return doc1.name.localeCompare(doc2.name); + } + + #newListStore() { + return Gio.ListStore.new(DocumentationPage); + } +} +export default GObject.registerClass( + { + GTypeName: "BrowseView", + Template, + Properties: { + webview: GObject.ParamSpec.object( + "webview", + "webview", + "Current active webview", + GObject.ParamFlags.READWRITE, + Webkit.WebView, + ), + }, + Signals: { + "browse-view-loaded": {}, + }, + InternalChildren: ["browse_list_view"], + }, + BrowseView, +); + +Gio._promisify( + Gio.File.prototype, + "load_contents_async", + "load_contents_finish", +); + +Gio._promisify( + Gio.FileEnumerator.prototype, + "next_files_async", + "next_files_finish", +); + +Gio._promisify( + Gio.File.prototype, + "enumerate_children_async", + "enumerate_children_finish", +); diff --git a/src/sidebar/DocumentationPage.js b/src/sidebar/DocumentationPage.js index f543543..c515a67 100644 --- a/src/sidebar/DocumentationPage.js +++ b/src/sidebar/DocumentationPage.js @@ -44,6 +44,13 @@ export default GObject.registerClass( GObject.ParamFlags.READWRITE, "", ), + html: GObject.ParamSpec.string( + "html", + "html", + "HTML documentation", + GObject.ParamFlags.READWRITE, + "", + ), children: GObject.ParamSpec.object( "children", "children", diff --git a/src/sidebar/Sidebar.js b/src/sidebar/Sidebar.js index 61ed02d..a3ecf80 100644 --- a/src/sidebar/Sidebar.js +++ b/src/sidebar/Sidebar.js @@ -4,7 +4,7 @@ import GObject from "gi://GObject"; import ThemeSelector from "../../troll/src/widgets/ThemeSelector.js"; -import BrowseView from "./BrowseView.js"; +import BrowseView from "./DevdocBrowseView.js"; import SearchView from "./SearchView.js"; import DocumentationPage from "./DocumentationPage.js"; diff --git a/src/sidebar/db.json b/src/sidebar/db.json new file mode 100644 index 0000000..bae8e83 --- /dev/null +++ b/src/sidebar/db.json @@ -0,0 +1,930 @@ +{ + "index": "

JavaScript reference

\n

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title \"JavaScript reference\").

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

\n
\n

Built-ins

\n

JavaScript standard built-in objects, along with their methods and properties.

Value properties

\n

Function properties

\n

Fundamental objects

\n

Error objects

\n

Numbers and dates

\n

Text processing

\n

Indexed collections

\n

Keyed collections

\n

Structured data

\n

Managing memory

\n

Control abstraction objects

\n

Reflection

\n

Internationalization

\n

Statements

\n

JavaScript statements and declarations

Control flow

\n

Declaring variables

\n

Functions and classes

\n

Iterations

\n

Others

\n

Expressions and operators

\n

JavaScript expressions and operators.

Primary expressions

\n

Left-hand-side expressions

\n

Increment and decrement

\n

Unary operators

\n

Arithmetic operators

\n

Relational operators

\n

Equality operators

\n

Bitwise shift operators

\n

Binary bitwise operators

\n

Binary logical operators

\n

Conditional (ternary) operator

\n

Assignment operators

\n

Yield operators

\n

Spread syntax

\n

Comma operator

\n

Functions

\n
\n

JavaScript functions.

\n

Classes

\n
\n

JavaScript classes.

\n

Additional reference pages

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference\n

\n
\n", + "global_objects/globalthis": "

globalThis

The globalThis global property contains the global this value, which is usually akin to the global object.

\n

Try it

\n

Value

\n
\n

The global this object.

\n
Property attributes of globalThis\n
Writable yes
Enumerable no
Configurable yes

Note: The globalThis property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object.

\n

Description

\n
\n

Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non–strict mode, but this will be undefined in modules and inside functions running in strict mode. You can also use Function('return this')(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way.

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value is globalThis.

Note: globalThis is generally the same concept as the global object (i.e. adding properties to globalThis makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for globalThis that's unrelated to the global object.

\n

HTML and the WindowProxy

\n

In many engines globalThis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a Proxy around the actual global object (which you can't directly access). This distinction is rarely relevant in common usage, but important to be aware of.

Naming

\n
\n

Several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. See the language proposal's \"naming\" document for more details.

globalThis is, quite literally, the global this value. It's the same value as the this value in a non-strict function called without an object. It's also the value of this in the global scope of a script.

\n

Examples

\n

Search for the global across environments

\n
\n

Usually, the global object does not need to be explicitly specified — its properties are automatically accessible as global variables.

\n

js

\n
console.log(window.Math === Math); // true\n
\n

However, one case where one needs to explicitly access the global object is when writing to it, usually for the purpose of polyfills.

Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). However, this causes CSP violations in some settings, so authors would use a piecewise definition like this (slightly adapted from the original core-js source):

\n

js

\n
function check(it) {\n  // Math is known to exist as a global in every environment.\n  return it && it.Math === Math && it;\n}\n\nconst globalObject =\n  check(typeof window === \"object\" && window) ||\n  check(typeof self === \"object\" && self) ||\n  check(typeof global === \"object\" && global) ||\n  // This returns undefined when running in strict mode\n  (function () {\n    return this;\n  })() ||\n  Function(\"return this\")();\n
\n

After obtaining the global object, we can define new globals on it. For example, adding an implementation for Intl:

\n

js

\n
if (typeof globalObject.Intl === \"undefined\") {\n  // No Intl in this environment; define our own on the global scope\n  Object.defineProperty(globalObject, \"Intl\", {\n    value: {\n      // Our Intl implementation\n    },\n    enumerable: false,\n    configurable: true,\n    writable: true,\n  });\n}\n
\n

With globalThis available, the additional search for the global across environments is not necessary anymore:

\n

js

\n
if (typeof globalThis.Intl === \"undefined\") {\n  Object.defineProperty(globalThis, \"Intl\", {\n    value: {\n      // Our Intl implementation\n    },\n    enumerable: false,\n    configurable: true,\n    writable: true,\n  });\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-globalthis
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
globalThis717965No5812.17171655012.210.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\n

\n
\n", + "global_objects/error": "

Error

Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.

\n

Description

\n
\n

Runtime errors result in new Error objects being created and thrown.

Error is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

\n

Error types

\n
\n

Besides the generic Error constructor, there are other core error constructors in JavaScript. For client-side exceptions, see Exception handling statements.

EvalError

Creates an instance representing an error that occurs regarding the global function eval().

RangeError

Creates an instance representing an error that occurs when a numeric variable or parameter is outside its valid range.

ReferenceError

Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError

Creates an instance representing a syntax error.

TypeError

Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError

Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

AggregateError

Creates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example by Promise.any().

\nInternalError Non-standard \n

Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. \"too much recursion\".

\n

Constructor

\n
Error()

Creates a new Error object.

Static methods

\n
\nError.captureStackTrace() Non-standard \n

A non-standard V8 function that creates the stack property on an Error instance.

\nError.stackTraceLimit Non-standard \n

A non-standard V8 numerical property that limits how many stack frames to include in an error stacktrace.

\nError.prepareStackTrace() Non-standard Optional\n

A non-standard V8 function that, if provided by usercode, is called by the V8 JavaScript engine for thrown exceptions, allowing the user to provide custom formatting for stacktraces.

Instance properties

\n
\n

These properties are defined on Error.prototype and shared by all Error instances.

Error.prototype.constructor

The constructor function that created the instance object. For Error instances, the initial value is the Error constructor.

Error.prototype.name

Represents the name for the type of error. For Error.prototype.name, the initial value is \"Error\". Subclasses like TypeError and SyntaxError provide their own name properties.

\nError.prototype.stack Non-standard \n

A non-standard property for a stack trace.

These properties are own properties of each Error instance.

cause

Error cause indicating the reason why the current error is thrown — usually another caught error. For user-created Error objects, this is the value provided as the cause property of the constructor's second argument.

\ncolumnNumber Non-standard \n

A non-standard Mozilla property for the column number in the line that raised this error.

\nfileName Non-standard \n

A non-standard Mozilla property for the path to the file that raised this error.

\nlineNumber Non-standard \n

A non-standard Mozilla property for the line number in the file that raised this error.

message

Error message. For user-created Error objects, this is the string provided as the constructor's first argument.

\n

Instance methods

\n
Error.prototype.toString()

Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

Examples

\n

Throwing a generic error

\n
\n

Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct:

\n

js

\n
try {\n  throw new Error(\"Whoops!\");\n} catch (e) {\n  console.error(`${e.name}: ${e.message}`);\n}\n
\n
\n

Handling a specific error type

\n
\n

You can choose to handle only specific error types by testing the error type with the instanceof keyword:

\n

js

\n
try {\n  foo.bar();\n} catch (e) {\n  if (e instanceof EvalError) {\n    console.error(`${e.name}: ${e.message}`);\n  } else if (e instanceof RangeError) {\n    console.error(`${e.name}: ${e.message}`);\n  }\n  // etc.\n  else {\n    // If none of our cases matched leave the Error unhandled\n    throw e;\n  }\n}\n
\n
\n

Differentiate between similar errors

\n
\n

Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e. with the same type and message).

If you don't have control over the original errors that are thrown, one option is to catch them and throw new Error objects that have more specific messages. The original error should be passed to the new Error in the constructor's options parameter as its cause property. This ensures that the original error and stack trace are available to higher-level try/catch blocks.

The example below shows this for two methods that would otherwise fail with similar errors (doFailSomeWay() and doFailAnotherWay()):

\n

js

\n
function doWork() {\n  try {\n    doFailSomeWay();\n  } catch (err) {\n    throw new Error(\"Failed in some way\", { cause: err });\n  }\n  try {\n    doFailAnotherWay();\n  } catch (err) {\n    throw new Error(\"Failed in another way\", { cause: err });\n  }\n}\n\ntry {\n  doWork();\n} catch (err) {\n  switch (err.message) {\n    case \"Failed in some way\":\n      handleFailSomeWay(err.cause);\n      break;\n    case \"Failed in another way\":\n      handleFailAnotherWay(err.cause);\n      break;\n  }\n}\n
\n

Note: If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See the error cause page for an example.

Custom error types can also use the cause property, provided the subclasses' constructor passes the options parameter when calling super(). The Error() base class constructor will read options.cause and define the cause property on the new error instance.

\n

js

\n
class MyError extends Error {\n  constructor(message, options) {\n    // Need to pass `options` as the second parameter to install the \"cause\" property.\n    super(message, options);\n  }\n}\n\nconsole.log(new MyError(\"test\", { cause: new Error(\"cause\") }).cause);\n// Error: cause\n
\n
\n

Custom error types

\n
\n

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code.

See \"What's a good way to extend Error in JavaScript?\" on StackOverflow for an in-depth discussion.

Warning: Builtin subclassing cannot be reliably transpiled to pre-ES6 code, because there's no way to construct the base class with a particular new.target without Reflect.construct(). You need additional configuration or manually call Object.setPrototypeOf(this, CustomError.prototype) at the end of the constructor; otherwise, the constructed instance will not be a CustomError instance. See the TypeScript FAQ for more information.

Note: Some browsers include the CustomError constructor in the stack trace when using ES2015 classes.

\n

js

\n
class CustomError extends Error {\n  constructor(foo = \"bar\", ...params) {\n    // Pass remaining arguments (including vendor specific ones) to parent constructor\n    super(...params);\n\n    // Maintains proper stack trace for where our error was thrown (only available on V8)\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, CustomError);\n    }\n\n    this.name = \"CustomError\";\n    // Custom debugging information\n    this.foo = foo;\n    this.date = new Date();\n  }\n}\n\ntry {\n  throw new CustomError(\"baz\", \"bazMessage\");\n} catch (e) {\n  console.error(e.name); // CustomError\n  console.error(e.foo); // baz\n  console.error(e.message); // bazMessage\n  console.error(e.stack); // stacktrace\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-error-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Error11216414.418410.111.01.00.10.0
Error11216414.418410.111.01.00.10.0
cause939391No7915939391661517.01.1316.9.0
columnNumberNoNo1NoNoNoNoNo4NoNoNoNoNo
fileNameNoNo1NoNoNoNoNo4NoNoNoNoNo
lineNumberNoNo1NoNoNoNoNo4NoNoNoNoNo
message11216514.418410.111.01.00.10.0
name11216414.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serialized properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 adds serialization of stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 adds serialization of stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serialized properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 adds serialization of stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 adds serialization of stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
stack31211010.56≤371841161.01.00.10.0
toString11216414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\n

\n
\n", + "global_objects/aggregateerror": "

AggregateError

\n

The AggregateError object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by Promise.any(), when all promises passed to it reject.

AggregateError is a subclass of Error.

\n
\n

Constructor

\n
AggregateError()

Creates a new AggregateError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on AggregateError.prototype and shared by all AggregateError instances.

AggregateError.prototype.constructor

The constructor function that created the instance object. For AggregateError instances, the initial value is the AggregateError constructor.

AggregateError.prototype.name

Represents the name for the type of error. For AggregateError.prototype.name, the initial value is \"AggregateError\".

These properties are own properties of each AggregateError instance.

errors

An array representing the errors that were aggregated.

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Catching an AggregateError

\n
\n

js

\n
Promise.any([Promise.reject(new Error(\"some error\"))]).catch((e) => {\n  console.log(e instanceof AggregateError); // true\n  console.log(e.message); // \"All Promises rejected\"\n  console.log(e.name); // \"AggregateError\"\n  console.log(e.errors); // [ Error: \"some error\" ]\n});\n
\n

Creating an AggregateError

\n
\n

js

\n
try {\n  throw new AggregateError([new Error(\"some error\")], \"Hello\");\n} catch (e) {\n  console.log(e instanceof AggregateError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"AggregateError\"\n  console.log(e.errors); // [ Error: \"some error\" ]\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-aggregate-error-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AggregateError858579No7114858579601414.01.215.0.0
AggregateError858579No7114858579601414.01.215.0.0
errors858579No7114858579601414.01.215.0.0
serializable_objectNoNo
103Serialized properties: name, message, cause, errors.
NoNoNoNoNo
103Serialized properties: name, message, cause, errors.
NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n

\n
\n", + "global_objects/infinity": "

Infinity

The Infinity global property is a numeric value representing infinity.

\n

Try it

\n

Value

\n
\n

The same number value as Number.POSITIVE_INFINITY.

\n
Property attributes of Infinity\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Infinity is a property of the global object. In other words, it is a variable in global scope.

The value Infinity (positive infinity) is greater than any other number.

This value behaves slightly differently than mathematical infinity; see Number.POSITIVE_INFINITY for details.

\n

Examples

\n

Using Infinity

\n
\n

js

\n
console.log(Infinity); /* Infinity */\nconsole.log(Infinity + 1); /* Infinity */\nconsole.log(Math.pow(10, 1000)); /* Infinity */\nconsole.log(Math.log(0)); /* -Infinity */\nconsole.log(1 / Infinity); /* 0 */\nconsole.log(1 / 0); /* Infinity */\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-value-properties-of-the-global-object-infinity
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Infinity11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity\n

\n
\n", + "global_objects/nan": "

NaN

The NaN global property is a value representing Not-A-Number.

\n

Try it

\n

Value

\n
\n

The same number value as Number.NaN.

\n
Property attributes of NaN\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

NaN is a property of the global object. In other words, it is a variable in global scope.

In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

There are five different types of operations that return NaN:

NaN and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that NaN !== NaN) are specified by IEEE 754. NaN's behaviors include:

NaN is also one of the falsy values in JavaScript.

\n

Examples

\n

Testing against NaN

\n
\n

To tell if a value is NaN, use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN — or, since NaN is the only value that compares unequal to itself, you can perform a self-comparison like x !== x.

\n

js

\n
NaN === NaN; // false\nNumber.NaN === NaN; // false\nisNaN(NaN); // true\nisNaN(Number.NaN); // true\nNumber.isNaN(NaN); // true\n\nfunction valueIsNaN(v) {\n  return v !== v;\n}\nvalueIsNaN(1); // false\nvalueIsNaN(NaN); // true\nvalueIsNaN(Number.NaN); // true\n
\n

However, do note the difference between isNaN() and Number.isNaN(): the former will return true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number, while the latter will return true only if the value is currently NaN:

\n

js

\n
isNaN(\"hello world\"); // true\nNumber.isNaN(\"hello world\"); // false\n
\n

For the same reason, using a BigInt value will throw an error with isNaN() and not with Number.isNaN():

\n

js

\n
isNaN(1n); // TypeError: Conversion from 'BigInt' to 'number' is not allowed.\nNumber.isNaN(1n); // false\n
\n

Additionally, some array methods cannot find NaN, while others can. Namely, the index-finding ones (indexOf(), lastIndexOf()) cannot find NaN, while the value-finding ones (includes()) can:

\n

js

\n
const arr = [2, 4, NaN, 12];\narr.indexOf(NaN); // -1\narr.includes(NaN); // true\n\n// Methods accepting a properly defined predicate can always find NaN\narr.findIndex((n) => Number.isNaN(n)); // 2\n
\n

For more information about NaN and its comparison, see Equality comparison and sameness.

\n

Observably distinct NaN values

\n
\n

There's a motivation for NaN being unequal to itself. It's possible to produce two floating point numbers with different binary representations but are both NaN, because in IEEE 754 encoding, any floating point number with exponent 0x7ff and a non-zero mantissa is NaN. In JavaScript, you can do bit-level manipulation using typed arrays.

\n

js

\n
const f2b = (x) => new Uint8Array(new Float64Array([x]).buffer);\nconst b2f = (x) => new Float64Array(x.buffer)[0];\n// Get a byte representation of NaN\nconst n = f2b(NaN);\n// Change the first bit, which is the sign bit and doesn't matter for NaN\nn[0] = 1;\nconst nan2 = b2f(n);\nconsole.log(nan2); // NaN\nconsole.log(Object.is(nan2, NaN)); // true\nconsole.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127]\nconsole.log(f2b(nan2)); // Uint8Array(8) [1, 0, 0, 0, 0, 0, 248, 127]\n
\n
\n

Silently escaping NaN

\n
\n

NaN propagates through mathematical operations, so it's usually sufficient to test for NaN once at the end of calculation to detect error conditions. The only case where NaN gets silently escaped is when using exponentiation with an exponent of 0, which immediately returns 1 without testing the base's value.

\n

js

\n
NaN ** 0 === 1; // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-value-properties-of-the-global-object-nan
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
NaN11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN\n

\n
\n", + "global_objects/undefined": "

undefined

The undefined global property represents the primitive value undefined. It is one of JavaScript's primitive types.

\n

Try it

\n

Value

\n
\n

The primitive value undefined.

\n
Property attributes of undefined\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

undefined is a property of the global object. That is, it is a variable in global scope.

In all non-legacy browsers, undefined is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

Note: While you can use undefined as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug.

\n

js

\n
// DON'T DO THIS\n\n(() => {\n  const undefined = \"foo\";\n  console.log(undefined, typeof undefined); // foo string\n})();\n\n((undefined) => {\n  console.log(undefined, typeof undefined); // foo string\n})(\"foo\");\n
\n
\n

Examples

\n

Strict equality and undefined

\n
\n

You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not initialized, and the if statement evaluates to true.

\n

js

\n
let x;\nif (x === undefined) {\n  // these statements execute\n} else {\n  // these statements do not execute\n}\n
\n

Note: The strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. This is because null is not equivalent to undefined.

See Equality comparison and sameness for details.

\n

typeof operator and undefined

\n
\n

Alternatively, typeof can be used:

\n

js

\n
let x;\nif (typeof x === \"undefined\") {\n  // these statements execute\n}\n
\n

One reason to use typeof is that it does not throw an error if the variable has not been declared.

\n

js

\n
// x has not been declared before\n// evaluates to true without errors\nif (typeof x === \"undefined\") {\n  // these statements execute\n}\n\n// Throws a ReferenceError\nif (x === undefined) {\n}\n
\n

However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.

The global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance:

\n

js

\n
if (\"x\" in window) {\n  // These statements execute only if x is defined globally\n}\n
\n
\n

void operator and undefined

\n
\n

The void operator is a third alternative.

\n

js

\n
let x;\nif (x === void 0) {\n  // these statements execute\n}\n\n// y has not been declared before\nif (y === void 0) {\n  // throws Uncaught ReferenceError: y is not defined\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-undefined
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
undefined11215.5314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined\n

\n
\n", + "global_objects/eval": "

eval()

\n

Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.

The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
eval(script)\n
\n

Parameters

\n
script

A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so import declarations (which can only exist in modules) are not allowed.

Return value

\n

The completion value of evaluating the given code. If the completion value is empty, undefined is returned. If script is not a string primitive, eval() returns the argument unchanged.

Exceptions

\n

Throws any exception that occurs during evaluation of the code, including SyntaxError if script fails to be parsed as a script.

Description

\n
\n

eval() is a function property of the global object.

The argument of the eval() function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of let is undefined), so it's recommended to not rely on statements' completion values.

In strict mode, declaring a variable named eval or re-assigning eval is a SyntaxError.

\n

js

\n
\"use strict\";\n\nconst eval = 1; // SyntaxError: Unexpected eval or arguments in strict mode\n
\n

If the argument of eval() is not a string, eval() returns the argument unchanged. In the following example, passing a String object instead of a primitive causes eval() to return the String object rather than evaluating the string.

\n

js

\n
eval(new String(\"2 + 2\")); // returns a String object containing \"2 + 2\"\neval(\"2 + 2\"); // returns 4\n
\n

To work around the issue in a generic fashion, you can coerce the argument to a string yourself before passing it to eval().

\n

js

\n
const expression = new String(\"2 + 2\");\neval(String(expression)); // returns 4\n
\n
\n

Direct and indirect eval

\n
\n

There are two modes of eval() calls: direct eval and indirect eval. Direct eval only has one form: eval( ) (the invoked function's name is eval and its value is the global eval function). Everything else, including invoking it via an aliased variable, via a member access or other expression, or through the optional chaining ?. operator, is indirect.

\n

js

\n
// Indirect call using the comma operator to return eval\n(0, eval)(\"x + y\");\n\n// Indirect call through optional chaining\neval?.(\"x + y\");\n\n// Indirect call using a variable to store and return eval\nconst geval = eval;\ngeval(\"x + y\");\n\n// Indirect call through member access\nconst obj = { eval };\nobj.eval(\"x + y\");\n
\n

Indirect eval can be seen as if the code is evaluated within a separate <script> tag. This means:

\n

Never use eval()!

\n
\n

Using direct eval() suffers from multiple problems:

There are many cases where the use of eval() or related methods can be optimized or avoided altogether.

Using indirect eval()

Consider this code:

\n

js

\n
function looseJsonParse(obj) {\n  return eval(`(${obj})`);\n}\nconsole.log(looseJsonParse(\"{ a: 4 - 1, b: function () {}, c: new Date() }\"));\n
\n

Simply using indirect eval and forcing strict mode can make the code much better:

\n

js

\n
function looseJsonParse(obj) {\n  return eval?.(`\"use strict\";(${obj})`);\n}\nconsole.log(looseJsonParse(\"{ a: 4 - 1, b: function () {}, c: new Date() }\"));\n
\n

The two code snippets above may seem to work the same way, but they do not; the first one using direct eval suffers from multiple problems.

However, using indirect eval() does not allow passing extra bindings other than existing global variables for the evaluated source to read. If you need to specify additional variables that the evaluated source should have access to, consider using the Function() constructor.

Using the Function() constructor

The Function() constructor is very similar to the indirect eval example above: it also evaluates the JavaScript source passed to it in the global scope without reading or mutating any local bindings, and therefore allows engines to do more optimizations than direct eval().

The difference between eval() and Function() is that the source string passed to Function() is parsed as a function body, not as a script. There are a few nuances — for example, you can use return statements at the top level of a function body, but not in a script.

The Function() constructor is useful if you wish to create local bindings within your eval source, by passing the variables as parameter bindings.

\n

js

\n
function Date(n) {\n  return [\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n    \"Sunday\",\n  ][n % 7 || 0];\n}\nfunction runCodeWithDateFunction(obj) {\n  return Function(\"Date\", `\"use strict\";return (${obj});`)(Date);\n}\nconsole.log(runCodeWithDateFunction(\"Date(5)\")); // Saturday\n
\n

Both eval() and Function() implicitly evaluate arbitrary code, and are forbidden in strict CSP settings. There are also additional safer (and faster!) alternatives to eval() or Function() for common use-cases.

Using bracket accessors

You should not use eval() to access properties dynamically. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval():

\n

js

\n
const obj = { a: 20, b: 30 };\nconst propName = getPropName(); // returns \"a\" or \"b\"\n\nconst result = eval(`obj.${propName}`);\n
\n

However, eval() is not necessary here — in fact, it's more error-prone, because if propName is not a valid identifier, it leads to a syntax error. Moreover, if getPropName is not a function you control, this may lead to execution of arbitrary code. Instead, use the property accessors, which are much faster and safer:

\n

js

\n
const obj = { a: 20, b: 30 };\nconst propName = getPropName(); // returns \"a\" or \"b\"\nconst result = obj[propName]; // obj[\"a\"] is the same as obj.a\n
\n

You can even use this method to access descendant properties. Using eval(), this would look like:

\n

js

\n
const obj = { a: { b: { c: 0 } } };\nconst propPath = getPropPath(); // suppose it returns \"a.b.c\"\n\nconst result = eval(`obj.${propPath}`); // 0\n
\n

Avoiding eval() here could be done by splitting the property path and looping through the different properties:

\n

js

\n
function getDescendantProp(obj, desc) {\n  const arr = desc.split(\".\");\n  while (arr.length) {\n    obj = obj[arr.shift()];\n  }\n  return obj;\n}\n\nconst obj = { a: { b: { c: 0 } } };\nconst propPath = getPropPath(); // suppose it returns \"a.b.c\"\nconst result = getDescendantProp(obj, propPath); // 0\n
\n

Setting a property that way works similarly:

\n

js

\n
function setDescendantProp(obj, desc, value) {\n  const arr = desc.split(\".\");\n  while (arr.length > 1) {\n    obj = obj[arr.shift()];\n  }\n  return (obj[arr[0]] = value);\n}\n\nconst obj = { a: { b: { c: 0 } } };\nconst propPath = getPropPath(); // suppose it returns \"a.b.c\"\nconst result = setDescendantProp(obj, propPath, 1); // obj.a.b.c is now 1\n
\n

However, beware that using bracket accessors with unconstrained input is not safe either — it may lead to object injection attacks.

Using callbacks

JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:

\n

js

\n
// Instead of setTimeout(\"…\", 1000) use:\nsetTimeout(() => {\n  // …\n}, 1000);\n\n// Instead of elt.setAttribute(\"onclick\", \"…\") use:\nelt.addEventListener(\"click\", () => {\n  // …\n});\n
\n

Closures are also helpful as a way to create parameterized functions without concatenating strings.

Using JSON

If the string you're calling eval() on contains data (for example, an array: \"[1, 2, 3]\"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data.

Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.

Passing carefully constrained data instead of arbitrary code is a good idea in general. For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.

\n

Examples

\n

Using eval()

\n
\n

In the following code, both of the statements containing eval() return 42. The first evaluates the string \"x + y + 1\"; the second evaluates the string \"42\".

\n

js

\n
const x = 2;\nconst y = 39;\nconst z = \"42\";\neval(\"x + y + 1\"); // 42\neval(z); // 42\n
\n
\n

eval() returns the completion value of statements

\n
\n

eval() returns the completion value of statements. For if, it would be the last expression or statement evaluated.

\n

js

\n
const str = \"if (a) { 1 + 1 } else { 1 + 2 }\";\nlet a = true;\nlet b = eval(str);\n\nconsole.log(`b is: ${b}`); // b is: 2\n\na = false;\nb = eval(str);\n\nconsole.log(`b is: ${b}`); // b is: 3\n
\n

The following example uses eval() to evaluate the string str. This string consists of JavaScript statements that assign z a value of 42 if x is five, and assign 0 to z otherwise. When the second statement is executed, eval() will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z, because the completion value of an assignment is the assigned value.

\n

js

\n
const x = 5;\nconst str = `if (x === 5) {\n  console.log(\"z is 42\");\n  z = 42;\n} else {\n  z = 0;\n}`;\n\nconsole.log(\"z is \", eval(str)); // z is 42  z is 42\n
\n

If you assign multiple values then the last value is returned.

\n

js

\n
let x = 5;\nconst str = `if (x === 5) {\n  console.log(\"z is 42\");\n  z = 42;\n  x = 420;\n} else {\n  z = 0;\n}`;\n\nconsole.log(\"x is\", eval(str)); // z is 42  x is 420\n
\n
\n

eval() as a string defining function requires \"(\" and \")\" as prefix and suffix

\n
\n

js

\n
// This is a function declaration\nconst fctStr1 = \"function a() {}\";\n// This is a function expression\nconst fctStr2 = \"(function b() {})\";\nconst fct1 = eval(fctStr1); // return undefined, but `a` is available as a global function now\nconst fct2 = eval(fctStr2); // return the function `b`\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-eval-x
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
eval11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\n

\n
\n", + "global_objects/isfinite": "

isFinite()

The isFinite() function determines whether a value is finite, first converting the value to a number if necessary. A finite number is one that's not NaN or ±Infinity. Because coercion inside the isFinite() function can be surprising, you may prefer to use Number.isFinite().

\n

Try it

\n

Syntax

\n
\n

js

\n
isFinite(value)\n
\n

Parameters

\n
value

The value to be tested.

Return value

\n

false if the given value is NaN, Infinity, or -Infinity after being converted to a number; otherwise, true.

Description

\n
\n

isFinite() is a function property of the global object.

When the argument to the isFinite() function is not of type Number, the value is first coerced to a number, and the resulting value is then compared against NaN and ±Infinity. This is as confusing as the behavior of isNaN — for example, isFinite(\"1\") is true.

Number.isFinite() is a more reliable way to test whether a value is a finite number value, because it returns false for any non-number input.

\n

Examples

\n

Using isFinite()

\n
\n

js

\n
isFinite(Infinity); // false\nisFinite(NaN); // false\nisFinite(-Infinity); // false\n\nisFinite(0); // true\nisFinite(2e64); // true\nisFinite(910); // true\n\n// Would've been false with the more robust Number.isFinite():\nisFinite(null); // true\nisFinite(\"0\"); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-isfinite-number
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isFinite11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite\n

\n
\n", + "global_objects/isnan": "

isNaN()

The isNaN() function determines whether a value is NaN, first converting the value to a number if necessary. Because coercion inside the isNaN() function can be surprising, you may prefer to use Number.isNaN().

\n

Try it

\n

Syntax

\n
\n

js

\n
isNaN(value)\n
\n

Parameters

\n
value

The value to be tested.

Return value

\n

true if the given value is NaN after being converted to a number; otherwise, false.

Description

\n
\n

isNaN() is a function property of the global object.

For number values, isNaN() tests if the number is the value NaN. When the argument to the isNaN() function is not of type Number, the value is first coerced to a number, and the resulting value is then compared against NaN.

This behavior of isNaN() for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively \"not numbers\", but they don't evaluate to NaN, so isNaN() returns false. Therefore, isNaN() answers neither the question \"is the input the floating point NaN value\" nor the question \"is the input not a number\".

Number.isNaN() is a more reliable way to test whether a value is the number value NaN or not. Alternatively, the expression x !== x can be used, and neither of the solutions is subject to the false positives that make the global isNaN() unreliable. To test if a value is a number, use typeof x === \"number\".

The isNaN() function answers the question \"is the input functionally equivalent to NaN when used in a number context\". If isNaN(x) returns false, you can use x in an arithmetic expression as if it's a valid number that's not NaN. If isNaN(x) returns true, x will get coerced to NaN and make most arithmetic expressions return NaN (because NaN propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable \"like\" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context.

Note: The + operator performs both number addition and string concatenation. Therefore, even if isNaN() returns false for both operands, the + operator may still return a string, because it's not used as an arithmetic operator. For example, isNaN(\"1\") returns false, but \"1\" + 1 returns \"11\". To be sure that you are working with numbers, coerce the value to a number and use Number.isNaN() to test the result.

\n

Examples

\n
\n

Note how isNaN() returns true for values that are not the value NaN but are not numbers either:

\n

js

\n
isNaN(NaN); // true\nisNaN(undefined); // true\nisNaN({}); // true\n\nisNaN(true); // false\nisNaN(null); // false\nisNaN(37); // false\n\n// Strings\nisNaN(\"37\"); // false: \"37\" is converted to the number 37 which is not NaN\nisNaN(\"37.37\"); // false: \"37.37\" is converted to the number 37.37 which is not NaN\nisNaN(\"37,5\"); // true\nisNaN(\"123ABC\"); // true: Number(\"123ABC\") is NaN\nisNaN(\"\"); // false: the empty string is converted to 0 which is not NaN\nisNaN(\" \"); // false: a string with spaces is converted to 0 which is not NaN\n\n// Dates\nisNaN(new Date()); // false; Date objects can be converted to a number (timestamp)\nisNaN(new Date().toString()); // true; the string representation of a Date object cannot be parsed as a number\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-isnan-number
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isNaN11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\n

\n
\n", + "global_objects/parsefloat": "

parseFloat()

The parseFloat() function parses a string argument and returns a floating point number.

\n

Try it

\n

Syntax

\n
\n

js

\n
parseFloat(string)\n
\n

Parameters

\n
string

The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

Return value

\n
\n

A floating point number parsed from the given string, or NaN when the first non-whitespace character cannot be converted to a number.

Note: JavaScript does not have the distinction of \"floating point numbers\" and \"integers\" on the language level. parseInt() and parseFloat() only differ in their parsing behavior, but not necessarily their return values. For example, parseInt(\"42\") and parseFloat(\"42\") would return the same value: a Number 42.

\n

Description

\n
\n

The parseFloat function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN. The number syntax it accepts can be summarized as:

Syntax-wise, parseFloat() parses a subset of the syntax that the Number() function accepts. Namely, parseFloat() does not support non-decimal literals with 0x, 0b, or 0o prefixes but supports everything else. However, parseFloat() is more lenient than Number() because it ignores trailing invalid characters, which would cause Number() to return NaN.

Similar to number literals and Number(), the number returned from parseFloat() may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the -1.7976931348623158e+3081.7976931348623158e+308 range (see Number.MAX_VALUE), -Infinity or Infinity is returned.

\n

Examples

\n

Using parseFloat()

\n
\n

The following examples all return 3.14:

\n

js

\n
parseFloat(3.14);\nparseFloat(\"3.14\");\nparseFloat(\"  3.14  \");\nparseFloat(\"314e-2\");\nparseFloat(\"0.0314E+2\");\nparseFloat(\"3.14some non-digit characters\");\nparseFloat({\n  toString() {\n    return \"3.14\";\n  },\n});\n
\n
\n

parseFloat() returning NaN

\n
\n

The following example returns NaN:

\n

js

\n
parseFloat(\"FF2\");\n
\n

Anecdotally, because the string NaN itself is invalid syntax as accepted by parseFloat(), passing \"NaN\" returns NaN as well.

\n

js

\n
parseFloat(\"NaN\"); // NaN\n
\n
\n

Returning Infinity

\n
\n

Infinity values are returned when the number is outside the double-precision 64-bit IEEE 754-2019 format range:

\n

js

\n
parseFloat(\"1.7976931348623159e+308\"); // Infinity\nparseFloat(\"-1.7976931348623159e+308\"); // -Infinity\n
\n

Infinity is also returned when the string starts with \"Infinity\" or \"-Infinity\":

\n

js

\n
parseFloat(\"Infinity\"); // Infinity\nparseFloat(\"-Infinity\"); // -Infinity\n
\n
\n

Interaction with BigInt values

\n
\n

parseFloat() does not handle BigInt values. It stops at the n character, and treats the preceding string as a normal integer, with possible loss of precision. If a BigInt value is passed to parseFloat(), it will be converted to a string, and the string will be parsed as a floating-point number, which may result in loss of precision as well.

\n

js

\n
parseFloat(900719925474099267n); // 900719925474099300\nparseFloat(\"900719925474099267n\"); // 900719925474099300\n
\n

You should pass the string to the BigInt() function instead, without the trailing n character.

\n

js

\n
BigInt(\"900719925474099267\");\n// 900719925474099267n\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-parsefloat-string
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parseFloat11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat\n

\n
\n", + "global_objects/parseint": "

parseInt()

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

\n

Try it

\n

Syntax

\n
\n

js

\n
parseInt(string)\nparseInt(string, radix)\n
\n

Parameters

\n
string

A string starting with an integer. Leading whitespace in this argument is ignored.

\nradix Optional\n

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. It is converted to a 32-bit integer; if it's nonzero and outside the range of [2, 36] after conversion, the function will always return NaN. If 0 or not provided, the radix will be inferred based on string's value. Be careful — this does not always default to 10! The description below explains in more detail what happens when radix is not provided.

Return value

\n
\n

An integer parsed from the given string, or NaN when

Note: JavaScript does not have the distinction of \"floating point numbers\" and \"integers\" on the language level. parseInt() and parseFloat() only differ in their parsing behavior, but not necessarily their return values. For example, parseInt(\"42\") and parseFloat(\"42\") would return the same value: a Number 42.

\n

Description

\n
\n

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.

If not NaN, the return value will be the integer that is the first argument taken as a number in the specified radix. (For example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.)

The radix argument is converted to a number. If it's unprovided, or if the value becomes 0, NaN or Infinity (undefined is coerced to NaN), JavaScript assumes the following:

  1. If the input string, with leading whitespace and possible +/- signs removed, begins with 0x or 0X (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexadecimal number.
  2. If the input string begins with any other value, the radix is 10 (decimal).

Note: Other prefixes like 0b, which are valid in number literals, are treated as normal digits by parseInt(). parseInt() does not treat strings beginning with a 0 character as octal values either. The only prefix that parseInt() recognizes is 0x or 0X for hexadecimal values — everything else is parsed as a decimal value if radix is missing.

If the radix is 16, parseInt() allows the string to be optionally prefixed by 0x or 0X after the optional sign character (+/-).

If the radix value (coerced if necessary) is not in range [2, 36] (inclusive) parseInt returns NaN.

For radices above 10, letters of the English alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used. The letters are case-insensitive.

parseInt understands exactly two signs: + for positive, and - for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although 1e3 technically encodes an integer (and will be correctly parsed to the integer 1000 by parseFloat()), parseInt(\"1e3\", 10) returns 1, because e is not a valid numeral in base 10. Because . is not a numeral either, the return value will always be an integer.

If the first character cannot be converted to a number with the radix in use, parseInt returns NaN. Leading whitespace is allowed.

For arithmetic purposes, the NaN value is not a number in any radix. You can call the Number.isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation result will also be NaN.

Because large numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 × 1023), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.trunc().

To convert a number to its string literal in a particular radix, use thatNumber.toString(radix).

Because parseInt() returns a number, it may suffer from loss of precision if the integer represented by the string is outside the safe range. The BigInt() function supports parsing integers of arbitrary length accurately, by returning a BigInt.

\n

Examples

\n

Using parseInt()

\n
\n

The following examples all return 15:

\n

js

\n
parseInt(\"0xF\", 16);\nparseInt(\"F\", 16);\nparseInt(\"17\", 8);\nparseInt(\"015\", 10); // but `parseInt('015', 8)` will return 13\nparseInt(\"15,123\", 10);\nparseInt(\"FXX123\", 16);\nparseInt(\"1111\", 2);\nparseInt(\"15 * 3\", 10);\nparseInt(\"15e2\", 10);\nparseInt(\"15px\", 10);\nparseInt(\"12\", 13);\n
\n

The following examples all return NaN:

\n

js

\n
parseInt(\"Hello\", 8); // Not a number at all\nparseInt(\"546\", 2); // Digits other than 0 or 1 are invalid for binary radix\n
\n

The following examples all return -15:

\n

js

\n
parseInt(\"-F\", 16);\nparseInt(\"-0F\", 16);\nparseInt(\"-0XF\", 16);\nparseInt(\"-17\", 8);\nparseInt(\"-15\", 10);\nparseInt(\"-1111\", 2);\nparseInt(\"-15e1\", 10);\nparseInt(\"-12\", 13);\n
\n

The following example returns 224:

\n

js

\n
parseInt(\"0e0\", 16);\n
\n

parseInt() does not handle BigInt values. It stops at the n character, and treats the preceding string as a normal integer, with possible loss of precision.

\n

js

\n
parseInt(\"900719925474099267n\");\n// 900719925474099300\n
\n

You should pass the string to the BigInt() function instead, without the trailing n character.

\n

js

\n
BigInt(\"900719925474099267\");\n// 900719925474099267n\n
\n

parseInt doesn't work with numeric separators:

\n

js

\n
parseInt(\"123_456\"); // 123\n
\n
\n

Using parseInt() on non-strings

\n
\n

parseInt() can have interesting results when working on non-strings combined with a high radix; for example, 36 (which makes all alphanumeric characters valid numeric digits).

\n

js

\n
parseInt(null, 36); // 1112745: The string \"null\" is 1112745 in base 36\nparseInt(undefined, 36); // 86464843759093: The string \"undefined\" is 86464843759093 in base 36\n
\n

In general, it's a bad idea to use parseInt() on non-strings, especially to use it as a substitution for Math.trunc(). It may work on small numbers:

\n

js

\n
parseInt(15.99, 10); // 15\nparseInt(-15.1, 10); // -15\n
\n

However, it only happens to work because the string representation of these numbers uses basic fractional notation (\"15.99\", \"-15.1\"), where parseInt() stops at the decimal point. Numbers greater than or equal to 1e+21 or less than or equal to 1e-7 use exponential notation (\"1.5e+22\", \"1.51e-8\") in their string representation, and parseInt() will stop at the e character or decimal point, which always comes after the first digit. This means for large and small numbers, parseInt() will return a one-digit integer:

\n

js

\n
parseInt(4.7 * 1e22, 10); // Very large number becomes 4\nparseInt(0.00000000000434, 10); // Very small number becomes 4\n\nparseInt(0.0000001, 10); // 1\nparseInt(0.000000123, 10); // 1\nparseInt(1e-7, 10); // 1\nparseInt(1000000000000000000000, 10); // 1\nparseInt(123000000000000000000000, 10); // 1\nparseInt(1e21, 10); // 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-parseint-string-radix
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parseInt11213314.418410.111.01.00.10.0
leading_zero_strings_as_decimal23122191564.425211461.51.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\n

\n
\n", + "global_objects/decodeuri": "

decodeURI()

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or a similar routine.

\n

Try it

\n

Syntax

\n
\n

js

\n
decodeURI(encodedURI)\n
\n

Parameters

\n
encodedURI

A complete, encoded Uniform Resource Identifier.

Return value

\n

A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI).

Exceptions

\n
URIError

Thrown if encodedURI contains a % not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.

Description

\n
\n

decodeURI() is a function property of the global object.

The decodeURI() function decodes the URI by treating each escape sequence in the form %XX as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, decodeURI() can determine how many more escape sequences to consume. If decodeURI() fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a URIError is thrown.

decodeURI() decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax):

; / ? : @ & = + $ , #\n
\n

Examples

\n

Decoding a Cyrillic URL

\n
\n

js

\n
decodeURI(\n  \"https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\",\n);\n// \"https://developer.mozilla.org/ru/docs/JavaScript_шеллы\"\n
\n

decodeURI() vs. decodeURIComponent()

\n
\n

decodeURI() assumes the input is a full URI, so it does not decode characters that are part of the URI syntax.

\n

js

\n
decodeURI(\n  \"https://developer.mozilla.org/docs/JavaScript%3A%20a_scripting_language\",\n);\n// \"https://developer.mozilla.org/docs/JavaScript%3A a_scripting_language\"\n\ndecodeURIComponent(\n  \"https://developer.mozilla.org/docs/JavaScript%3A%20a_scripting_language\",\n);\n// \"https://developer.mozilla.org/docs/JavaScript: a_scripting_language\"\n
\n
\n

Catching errors

\n
\n

js

\n
try {\n  const a = decodeURI(\"%E0%A4%A\");\n} catch (e) {\n  console.error(e);\n}\n\n// URIError: malformed URI sequence\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-decodeuri-encodeduri
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
decodeURI11215.571.14.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI\n

\n
\n", + "global_objects/decodeuricomponent": "

decodeURIComponent()

The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent() or by a similar routine.

\n

Try it

\n

Syntax

\n
\n

js

\n
decodeURIComponent(encodedURI)\n
\n

Parameters

\n
encodedURI

An encoded component of a Uniform Resource Identifier.

Return value

\n

A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component.

Exceptions

\n
URIError

Thrown if encodedURI contains a % not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.

Description

\n
\n

decodeURIComponent() is a function property of the global object.

decodeURIComponent() uses the same decoding algorithm as described in decodeURI(). It decodes all escape sequences, including those that are not created by encodeURIComponent, like -.!~*'().

\n

Examples

\n

Decoding a Cyrillic URL component

\n
\n

js

\n
decodeURIComponent(\"JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\");\n// \"JavaScript_шеллы\"\n
\n

Catching errors

\n
\n

js

\n
try {\n  const a = decodeURIComponent(\"%E0%A4%A\");\n} catch (e) {\n  console.error(e);\n}\n\n// URIError: malformed URI sequence\n
\n

Decoding query parameters from a URL

\n
\n

decodeURIComponent() cannot be used directly to parse query parameters from a URL. It needs a bit of preparation.

\n

js

\n
function decodeQueryParam(p) {\n  return decodeURIComponent(p.replace(/\\+/g, \" \"));\n}\n\ndecodeQueryParam(\"search+query%20%28correct%29\");\n// 'search query (correct)'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-decodeuricomponent-encodeduricomponent
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
decodeURIComponent11215.571.14.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent\n

\n
\n", + "global_objects/encodeuricomponent": "

encodeURIComponent()

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to encodeURI(), this function encodes more characters, including those that are part of the URI syntax.

\n

Try it

\n

Syntax

\n
\n

js

\n
encodeURIComponent(uriComponent)\n
\n

Parameters

\n
uriComponent

A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are converted to strings.

Return value

\n

A new string representing the provided uriComponent encoded as a URI component.

Exceptions

\n
URIError

Thrown if uriComponent contains a lone surrogate.

Description

\n
\n

encodeURIComponent() is a function property of the global object.

encodeURIComponent() uses the same encoding algorithm as described in encodeURI(). It escapes all characters except:

A–Z a–z 0–9 - _ . ! ~ * ' ( )\n

Compared to encodeURI(), encodeURIComponent() escapes a larger set of characters. Use encodeURIComponent() on user-entered fields from forms POST'd to the server — this will encode & symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes Jack & Jill, without encodeURIComponent(), the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

For application/x-www-form-urlencoded, spaces are to be replaced by +, so one may wish to follow a encodeURIComponent() replacement with an additional replacement of %20 with +.

\n

Examples

\n
\n
\n

The following example provides the special encoding required within UTF-8 Content-Disposition and Link server response header parameters (e.g., UTF-8 filenames):

\n

js

\n
const fileName = \"my file(2).txt\";\nconst header = `Content-Disposition: attachment; filename*=UTF-8''${encodeRFC5987ValueChars(\n  fileName,\n)}`;\n\nconsole.log(header);\n// \"Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt\"\n\nfunction encodeRFC5987ValueChars(str) {\n  return (\n    encodeURIComponent(str)\n      // The following creates the sequences %27 %28 %29 %2A (Note that\n      // the valid encoding of \"*\" is %2A, which necessitates calling\n      // toUpperCase() to properly encode). Although RFC3986 reserves \"!\",\n      // RFC5987 does not, so we do not need to escape it.\n      .replace(\n        /['()*]/g,\n        (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n      )\n      // The following are not required for percent-encoding per RFC5987,\n      // so we can allow for a little better readability over the wire: |`^\n      .replace(/%(7C|60|5E)/g, (str, hex) =>\n        String.fromCharCode(parseInt(hex, 16)),\n      )\n  );\n}\n
\n
\n

Encoding for RFC3986

\n
\n

The more recent RFC3986 reserves !, ', (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the IPv6 URI syntax. An RFC3986-compliant encodeURI implementation should not escape them, which is demonstrated in the encodeURI() example.

\n

js

\n
function encodeRFC3986URIComponent(str) {\n  return encodeURIComponent(str).replace(\n    /[!'()*]/g,\n    (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n}\n
\n
\n

Encoding a lone surrogate throws

\n
\n

A URIError will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:

\n

js

\n
// High-low pair OK\nencodeURIComponent(\"\\uD800\\uDFFF\"); // \"%F0%90%8F%BF\"\n\n// Lone high-surrogate code unit throws \"URIError: malformed URI sequence\"\nencodeURIComponent(\"\\uD800\");\n\n// Lone high-surrogate code unit throws \"URIError: malformed URI sequence\"\nencodeURIComponent(\"\\uDFFF\");\n
\n

You can use String.prototype.toWellFormed(), which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use String.prototype.isWellFormed() to check if a string contains lone surrogates before passing it to encodeURIComponent().

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-encodeuricomponent-uricomponent
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
encodeURIComponent11215.571.14.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\n

\n
\n", + "global_objects/escape": "

escape()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: escape() is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use encodeURIComponent() or encodeURI() if possible.

The escape() function computes a new string in which certain characters have been replaced by hexadecimal escape sequences.

\n
\n

Syntax

\n
\n

js

\n
escape(str)\n
\n

Parameters

\n
str

A string to be encoded.

Return value

\n

A new string in which certain characters have been escaped.

Description

\n
\n

escape() is a function property of the global object.

The escape() function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and @\\*_+-./. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format %XX, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format %uXXXX, left-padded with 0 if necessary.

Note: This function was used mostly for URL encoding and is partly based on the escape format in RFC 1738. The escape format is not an escape sequence in string literals. You can replace %XX with \\xXX and %uXXXX with \\uXXXX to get a string containing actual string-literal escape sequences.

\n

Examples

\n

Using escape()

\n
\n

js

\n
escape(\"abc123\"); // \"abc123\"\nescape(\"äöü\"); // \"%E4%F6%FC\"\nescape(\"ć\"); // \"%u0107\"\n\n// special characters\nescape(\"@*_+-./\"); // \"@*_+-./\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-escape-string
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
escape11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape\n

\n
\n", + "global_objects/unescape": "

unescape()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: unescape() is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use decodeURIComponent() or decodeURI() if possible.

The unescape() function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like escape().

\n
\n

Syntax

\n
\n

js

\n
unescape(str)\n
\n

Parameters

\n
str

A string to be decoded.

Return value

\n

A new string in which certain characters have been unescaped.

Description

\n
\n

unescape() is a function property of the global object.

The unescape() function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form %XX or %uXXXX (where X represents one hexadecimal digit) with the character that has the hexadecimal value XX/XXXX. If the escape sequence is not a valid escape sequence (for example, if % is followed by one or no hex digit), it is left as-is.

Note: This function was used mostly for URL encoding and is partly based on the escape format in RFC 1738. The unescape() function does not evaluate escape sequences in string literals. You can replace \\xXX with %XX and \\uXXXX with %uXXXX to get a string that can be handled by unescape().

\n

Examples

\n

Using unescape()

\n
\n

js

\n
unescape(\"abc123\"); // \"abc123\"\nunescape(\"%E4%F6%FC\"); // \"äöü\"\nunescape(\"%u0107\"); // \"ć\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-unescape-string
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unescape11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape\n

\n
\n", + "global_objects/object": "

Object

The Object type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.

\n

Description

\n
\n

Nearly all objects in JavaScript are instances of Object; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). The only objects that don't inherit from Object.prototype are those with null prototype, or descended from other null prototype objects.

Changes to the Object.prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. To make it more secure, Object.prototype is the only object in the core JavaScript language that has immutable prototype — the prototype of Object.prototype is always null and not changeable.

\n

Object prototype properties

\n
\n

You should avoid calling any Object.prototype method directly from the instance, especially those that are not intended to be polymorphic (i.e. only its initial behavior makes sense and no descending object could override it in a meaningful way). All objects descending from Object.prototype may define a custom own property that has the same name, but with entirely different semantics from what you expect. Furthermore, these properties are not inherited by null-prototype objects. All modern JavaScript utilities for working with objects are static. More specifically:

In case where a semantically equivalent static method doesn't exist, or if you really want to use the Object.prototype method, you should directly call() the Object.prototype method on your target object instead, to prevent the object from having an overriding property that produces unexpected results.

\n

js

\n
const obj = {\n  foo: 1,\n  // You should not define such a method on your own object,\n  // but you may not be able to prevent it from happening if\n  // you are receiving the object from external input\n  propertyIsEnumerable() {\n    return false;\n  },\n};\n\nobj.propertyIsEnumerable(\"foo\"); // false; unexpected result\nObject.prototype.propertyIsEnumerable.call(obj, \"foo\"); // true; expected result\n
\n
\n

Deleting a property from an object

\n

There isn't any method in an Object itself to delete its own properties (such as Map.prototype.delete()). To do so, one must use the delete operator.

null-prototype objects

\n
\n

Almost all objects in JavaScript ultimately inherit from Object.prototype (see inheritance and the prototype chain). However, you may create null-prototype objects using Object.create(null) or the object initializer syntax with __proto__: null (note: the __proto__ key in object literals is different from the deprecated Object.prototype.__proto__ property). You can also change the prototype of an existing object to null by calling Object.setPrototypeOf(obj, null).

\n

js

\n
const obj = Object.create(null);\nconst obj2 = { __proto__: null };\n
\n

An object with a null prototype can behave in unexpected ways, because it doesn't inherit any object methods from Object.prototype. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or lose information (especially if using silent error-traps that ignore errors).

For example, the lack of Object.prototype.toString() often makes debugging intractable:

\n

js

\n
const normalObj = {}; // create a normal object\nconst nullProtoObj = Object.create(null); // create an object with \"null\" prototype\n\nconsole.log(`normalObj is: ${normalObj}`); // shows \"normalObj is: [object Object]\"\nconsole.log(`nullProtoObj is: ${nullProtoObj}`); // throws error: Cannot convert object to primitive value\n\nalert(normalObj); // shows [object Object]\nalert(nullProtoObj); // throws error: Cannot convert object to primitive value\n
\n

Other methods will fail as well.

\n

js

\n
normalObj.valueOf(); // shows {}\nnullProtoObj.valueOf(); // throws error: nullProtoObj.valueOf is not a function\n\nnormalObj.hasOwnProperty(\"p\"); // shows \"true\"\nnullProtoObj.hasOwnProperty(\"p\"); // throws error: nullProtoObj.hasOwnProperty is not a function\n\nnormalObj.constructor; // shows \"Object() { [native code] }\"\nnullProtoObj.constructor; // shows \"undefined\"\n
\n

We can add the toString method back to the null-prototype object by assigning it one:

\n

js

\n
nullProtoObj.toString = Object.prototype.toString; // since new object lacks toString, add the original generic one back\n\nconsole.log(nullProtoObj.toString()); // shows \"[object Object]\"\nconsole.log(`nullProtoObj is: ${nullProtoObj}`); // shows \"nullProtoObj is: [object Object]\"\n
\n

Unlike normal objects, in which toString() is on the object's prototype, the toString() method here is an own property of nullProtoObj. This is because nullProtoObj has no (null) prototype.

You can also revert a null-prototype object back to an ordinary object using Object.setPrototypeOf(nullProtoObj, Object.prototype).

In practice, objects with null prototype are usually used as a cheap substitute for maps. The presence of Object.prototype properties will cause some bugs:

\n

js

\n
const ages = { alice: 18, bob: 27 };\n\nfunction hasPerson(name) {\n  return name in ages;\n}\n\nfunction getAge(name) {\n  return ages[name];\n}\n\nhasPerson(\"hasOwnProperty\"); // true\ngetAge(\"toString\"); // [Function: toString]\n
\n

Using a null-prototype object removes this hazard without introducing too much complexity to the hasPerson and getAge functions:

\n

js

\n
const ages = Object.create(null, {\n  alice: { value: 18, enumerable: true },\n  bob: { value: 27, enumerable: true },\n});\n\nhasPerson(\"hasOwnProperty\"); // false\ngetAge(\"toString\"); // undefined\n
\n

In such case, the addition of any method should be done cautiously, as they can be confused with the other key-value pairs stored as data.

Making your object not inherit from Object.prototype also prevents prototype pollution attacks. If a malicious script adds a property to Object.prototype, it will be accessible on every object in your program, except objects that have null prototype.

\n

js

\n
const user = {};\n\n// A malicious script:\nObject.prototype.authenticated = true;\n\n// Unexpectedly allowing unauthenticated user to pass through\nif (user.authenticated) {\n  // access confidential data\n}\n
\n

JavaScript also has built-in APIs that produce null-prototype objects, especially those that use objects as ad hoc key-value collections. For example:

The term \"null-prototype object\" often also includes any object without Object.prototype in its prototype chain. Such objects can be created with extends null when using classes.

\n

Object coercion

\n
\n

Many built-in operations that expect objects first coerce their arguments to objects. The operation can be summarized as follows:

There are two ways to achieve nearly the same effect in JavaScript.

Places that use object coercion include:

Unlike conversion to primitives, the object coercion process itself is not observable in any way, since it doesn't invoke custom code like toString or valueOf methods.

\n

Constructor

\n
Object()

Turns the input into an object.

Static methods

\n
Object.assign()

Copies the values of all enumerable own properties from one or more source objects to a target object.

Object.create()

Creates a new object with the specified prototype object and properties.

Object.defineProperties()

Adds the named properties described by the given descriptors to an object.

Object.defineProperty()

Adds the named property described by a given descriptor to an object.

Object.entries()

Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.

Object.freeze()

Freezes an object. Other code cannot delete or change its properties.

Object.fromEntries()

Returns a new object from an iterable of [key, value] pairs. (This is the reverse of Object.entries).

Object.getOwnPropertyDescriptor()

Returns a property descriptor for a named property on an object.

Object.getOwnPropertyDescriptors()

Returns an object containing all own property descriptors for an object.

Object.getOwnPropertyNames()

Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.

Object.getOwnPropertySymbols()

Returns an array of all symbol properties found directly upon a given object.

Object.getPrototypeOf()

Returns the prototype (internal [[Prototype]] property) of the specified object.

Object.groupBy()

Groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.

Object.hasOwn()

Returns true if the specified object has the indicated property as its own property, or false if the property is inherited or does not exist.

Object.is()

Compares if two values are the same value. Equates all NaN values (which differs from both IsLooselyEqual used by == and IsStrictlyEqual used by ===).

Object.isExtensible()

Determines if extending of an object is allowed.

Object.isFrozen()

Determines if an object was frozen.

Object.isSealed()

Determines if an object is sealed.

Object.keys()

Returns an array containing the names of all of the given object's own enumerable string properties.

Object.preventExtensions()

Prevents any extensions of an object.

Object.seal()

Prevents other code from deleting properties of an object.

Object.setPrototypeOf()

Sets the object's prototype (its internal [[Prototype]] property).

Object.values()

Returns an array containing the values that correspond to all of a given object's own enumerable string properties.

Instance properties

\n
\n

These properties are defined on Object.prototype and shared by all Object instances.

\nObject.prototype.__proto__ Deprecated \n

Points to the object which was used as prototype when the object was instantiated.

Object.prototype.constructor

The constructor function that created the instance object. For plain Object instances, the initial value is the Object constructor. Instances of other constructors each inherit the constructor property from their respective Constructor.prototype object.

\n

Instance methods

\n
\nObject.prototype.__defineGetter__() Deprecated \n

Associates a function with a property that, when accessed, executes that function and returns its return value.

\nObject.prototype.__defineSetter__() Deprecated \n

Associates a function with a property that, when set, executes that function which modifies the property.

\nObject.prototype.__lookupGetter__() Deprecated \n

Returns the function bound as a getter to the specified property.

\nObject.prototype.__lookupSetter__() Deprecated \n

Returns the function bound as a setter to the specified property.

Object.prototype.hasOwnProperty()

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

Object.prototype.isPrototypeOf()

Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.

Object.prototype.propertyIsEnumerable()

Returns a boolean indicating whether the specified property is the object's enumerable own property.

Object.prototype.toLocaleString()

Calls toString().

Object.prototype.toString()

Returns a string representation of the object.

Object.prototype.valueOf()

Returns the primitive value of the specified object.

Examples

\n

Constructing empty objects

\n
\n

The following example creates empty objects using the new keyword with different arguments:

\n

js

\n
const o1 = new Object();\nconst o2 = new Object(undefined);\nconst o3 = new Object(null);\n
\n
\n

Using Object() constructor to turn primitives into an Object of their respective type

\n
\n

You can use the Object() constructor to create an object wrapper of a primitive value.

The following examples create variables o1 and o2 which are objects storing Boolean and BigInt values:

\n

js

\n
// Equivalent to const o1 = new Boolean(true)\nconst o1 = new Object(true);\n\n// No equivalent because BigInt() can't be called as a constructor,\n// and calling it as a regular function won't create an object\nconst o2 = new Object(1n);\n
\n
\n

Object prototypes

\n
\n

When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.

When modifying prototypes with hooks, pass this and the arguments (the call state) to the current behavior by calling apply() on the function. This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.

\n

js

\n
const current = Object.prototype.valueOf;\n\n// Since my property \"-prop-value\" is cross-cutting and isn't always\n// on the same prototype chain, I want to modify Object.prototype:\nObject.prototype.valueOf = function (...args) {\n  if (Object.hasOwn(this, \"-prop-value\")) {\n    return this[\"-prop-value\"];\n  } else {\n    // It doesn't look like one of my objects, so let's fall back on\n    // the default behavior by reproducing the current behavior as best we can.\n    // The apply behaves like \"super\" in some other languages.\n    // Even though valueOf() doesn't take arguments, some other hook may.\n    return current.apply(this, args);\n  }\n};\n
\n

Warning: Modifying the prototype property of any built-in constructor is considered a bad practice and risks forward compatibility.

You can read more about prototypes in Inheritance and the prototype chain.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Object11213314.418410.111.01.00.10.0
Object11213314.418410.111.01.00.10.0
assign451234No3294545343295.01.04.0.0
constructor11218414.418410.111.01.00.10.0
create5124911.654.41841251.01.00.10.0
defineGetter112
1Starting with Firefox 48, this method can no longer be called at the global scope without any object. A TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case.
119.534.418410.111.01.00.10.0
defineProperties5124911.654.41841251.01.00.10.0
defineProperty51249
8In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9.
\n
11.6
5.1Also supported in Safari 5, but not on DOM objects.
4.418412
6Also supported in Safari for iOS 4.2, but not on DOM objects.
1.01.00.10.0
defineSetter112
1Starting with Firefox 48, this method can no longer be called at the global scope without any object. A TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case.
119.534.418410.111.01.00.10.0
entries541447No4110.15454474110.36.01.07.0.0
freeze61249125.14.41841251.01.00.10.0
fromEntries737963No6012.17373635212.211.01.012.0.0
getOwnPropertyDescriptor51249
8In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9.
\n
1254.41841251.01.00.10.0
getOwnPropertyDescriptors541550No411054545041106.01.07.0.0
getOwnPropertyNames512491254.41841251.01.00.10.0
getOwnPropertySymbols381236No2593838362593.01.00.12.0
getPrototypeOf5123.5912.154.418412.151.01.00.10.0
groupBy117117119No10316.4–previewpreview117117119No16.4No1.37No
hasOwn939392No7915.49393926615.417.01.1316.9.0
hasOwnProperty11215.5534.418410.111.01.00.10.0
is191222No1594.425221491.51.00.10.0
isExtensible61249125.14.41841251.01.00.10.0
isFrozen61249125.14.41841251.01.00.10.0
isPrototypeOf11219434.418410.111.01.00.10.0
isSealed61249125.14.41841251.01.00.10.0
keys512491254.41841251.01.00.10.0
lookupGetter1121119.534.418410.111.01.00.10.0
lookupSetter1121119.534.418410.111.01.00.10.0
preventExtensions61249125.14.41841251.01.00.10.0
propertyIsEnumerable11215.5434.418410.111.01.00.10.0
proto11211110.534.41841111.0No0.10.0
seal61249125.14.41841251.01.00.10.0
setPrototypeOf341231112193734312192.01.00.12.0
toLocaleString11215.5414.418410.111.01.00.10.0
toString11213314.418410.111.01.00.10.0
valueOf11214314.418410.111.01.00.10.0
values541447No4110.15454474110.36.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\n

\n
\n", + "global_objects/function": "

Function

The Function object provides methods for functions. In JavaScript, every function is actually a Function object.

\n

Constructor

\n
Function()

Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval(). However, unlike eval(), the Function constructor creates functions that execute in the global scope only.

Instance properties

\n
\n

These properties are defined on Function.prototype and shared by all Function instances.

\nFunction.prototype.arguments Deprecated Non-standard \n

Represents the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError. Use the arguments object inside function closures instead.

\nFunction.prototype.caller Deprecated Non-standard \n

Represents the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError.

Function.prototype.constructor

The constructor function that created the instance object. For Function instances, the initial value is the Function constructor.

These properties are own properties of each Function instance.

\ndisplayName Non-standard Optional\n

The display name of the function.

length

Specifies the number of arguments expected by the function.

name

The name of the function.

prototype

Used when the function is used as a constructor with the new operator. It will become the new object's prototype.

\n

Instance methods

\n
Function.prototype.apply()

Calls a function with a given this value and optional arguments provided as an array (or an array-like object).

Function.prototype.bind()

Creates a new function that, when called, has its this keyword set to a provided value, optionally with a given sequence of arguments preceding any provided when the new function is called.

Function.prototype.call()

Calls a function with a given this value and optional arguments.

Function.prototype.toString()

Returns a string representing the source code of the function. Overrides the Object.prototype.toString method.

Function.prototype[@@hasInstance]()

Specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. Called by the instanceof operator.

Examples

\n

Difference between Function constructor and function declaration

\n
\n

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using eval() with code for a function expression.

\n

js

\n
// Create a global property with `var`\nvar x = 10;\n\nfunction createFunction1() {\n  const x = 20;\n  return new Function(\"return x;\"); // this `x` refers to global `x`\n}\n\nfunction createFunction2() {\n  const x = 20;\n  function f() {\n    return x; // this `x` refers to the local `x` above\n  }\n  return f;\n}\n\nconst f1 = createFunction1();\nconsole.log(f1()); // 10\nconst f2 = createFunction2();\nconsole.log(f2()); // 20\n
\n

While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@hasInstance501550No371050505037105.01.06.5.0
Function11214314.418410.111.01.00.10.0
Function1121431≤3718410.111.01.00.10.0
apply11215.5414.418410.111.01.00.10.0
arguments11214314.418410.111.01.00.10.0
bind7124911.65.141841261.01.00.10.0
call11215.5414.418410.111.01.0
0.10.0When calling this method, thisArg does not default to the global object.
caller112189.634.418410.111.01.00.10.0
displayNameNoNo13NoNoNoNoNo14NoNoNoNoNo
length11214314.418410.111.01.00.10.0
name15141No10.564.41841161.01.00.10.0
toString11215314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\n

\n
\n", + "global_objects/boolean": "

Boolean

The Boolean object represents a truth value: true or false.

\n

Description

\n

Boolean primitives and Boolean objects

\n
\n

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

Any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true:

\n

js

\n
const x = new Boolean(false);\nif (x) {\n  // this code is executed\n}\n
\n

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:

\n

js

\n
const x = false;\nif (x) {\n  // this code is not executed\n}\n
\n

Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean value — use Boolean as a function or a double NOT instead:

\n

js

\n
const good = Boolean(expression); // use this\nconst good2 = !!expression; // or this\nconst bad = new Boolean(expression); // don't use this!\n
\n

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true.

\n

js

\n
const myFalse = new Boolean(false); // initial value of false\nconst g = Boolean(myFalse); // initial value of true\nconst myString = new String(\"Hello\"); // string object\nconst s = Boolean(myString); // initial value of true\n
\n

Warning: You should rarely find yourself using Boolean as a constructor.

\n

Boolean coercion

\n
\n

Many built-in operations that expect booleans first coerce their arguments to booleans. The operation can be summarized as follows:

Note: A legacy behavior makes document.all return false when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.

Note: Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives.

In other words, there are only a handful of values that get coerced to false — these are called falsy values. All other values are called truthy values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context.

There are two ways to achieve the same effect in JavaScript.

Note that truthiness is not the same as being loosely equal to true or false.

\n

js

\n
if ([]) {\n  console.log(\"[] is truthy\");\n}\nif ([] == false) {\n  console.log(\"[] == false\");\n}\n// [] is truthy\n// [] == false\n
\n

[] is truthy, but it's also loosely equal to false. It's truthy, because all objects are truthy. However, when comparing with false, which is a primitive, [] is also converted to a primitive, which is \"\" via Array.prototype.toString(). Comparing strings and booleans results in both being converted to numbers, and they both become 0, so [] == false is true. In general, falsiness and == false differ in the following cases:

Truthy values are even more unlikely to be loosely equal to true. All values are either truthy or falsy, but most values are loosely equal to neither true nor false.

\n

Constructor

\n
Boolean()

Creates a new Boolean object.

Instance properties

\n
\n

These properties are defined on Boolean.prototype and shared by all Boolean instances.

Boolean.prototype.constructor

The constructor function that created the instance object. For Boolean instances, the initial value is the Boolean constructor.

\n

Instance methods

\n
Boolean.prototype.toString()

Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString() method.

Boolean.prototype.valueOf()

Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf() method.

Examples

\n

Creating Boolean objects with an initial value of false

\n
\n

js

\n
const bNoParam = new Boolean();\nconst bZero = new Boolean(0);\nconst bNull = new Boolean(null);\nconst bEmptyString = new Boolean(\"\");\nconst bfalse = new Boolean(false);\n
\n

Creating Boolean objects with an initial value of true

\n
\n

js

\n
const btrue = new Boolean(true);\nconst btrueString = new Boolean(\"true\");\nconst bfalseString = new Boolean(\"false\");\nconst bSuLin = new Boolean(\"Su Lin\");\nconst bArrayProto = new Boolean([]);\nconst bObjProto = new Boolean({});\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-boolean-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Boolean11213414.418410.111.01.00.10.0
Boolean11213314.418410.111.01.00.10.0
toString11213414.418410.111.01.00.10.0
valueOf11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean\n

\n
\n", + "global_objects/symbol": "

Symbol

\n

Symbol is a built-in object whose constructor returns a symbol primitive — also called a Symbol value or just a Symbol — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.

Every Symbol() call is guaranteed to return a unique Symbol. Every Symbol.for(\"key\") call will always return the same Symbol for a given value of \"key\". When Symbol.for(\"key\") is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.

\n
\n

Description

\n
\n

To create a new primitive Symbol, you write Symbol() with an optional string as its description:

\n

js

\n
const sym1 = Symbol();\nconst sym2 = Symbol(\"foo\");\nconst sym3 = Symbol(\"foo\");\n
\n

The above code creates three new Symbols. Note that Symbol(\"foo\") does not coerce the string \"foo\" into a Symbol. It creates a new Symbol each time:

\n

js

\n
Symbol(\"foo\") === Symbol(\"foo\"); // false\n
\n

The following syntax with the new operator will throw a TypeError:

\n

js

\n
const sym = new Symbol(); // TypeError\n
\n

This prevents authors from creating an explicit Symbol wrapper object instead of a new Symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number).

If you really want to create a Symbol wrapper object, you can use the Object() function:

\n

js

\n
const sym = Symbol(\"foo\");\ntypeof sym; // \"symbol\"\nconst symObj = Object(sym);\ntypeof symObj; // \"object\"\n
\n

Because symbols are the only primitive data type that has reference identity (that is, you cannot create the same symbol twice), they behave like objects in some way. For example, they are garbage collectable and can therefore be stored in WeakMap, WeakSet, WeakRef, and FinalizationRegistry objects.

\n

Shared Symbols in the global Symbol registry

\n
\n

The above syntax using the Symbol() function will create a Symbol whose value remains unique throughout the lifetime of the program. To create Symbols available across files and even across realms (each of which has its own global scope), use the methods Symbol.for() and Symbol.keyFor() to set and retrieve Symbols from the global Symbol registry.

Note that the \"global Symbol registry\" is only a fictitious concept and may not correspond to any internal data structure in the JavaScript engine — and even if such a registry exists, its content is not available to the JavaScript code, except through the for() and keyFor() methods.

The method Symbol.for(tokenString) takes a string key and returns a symbol value from the registry, while Symbol.keyFor(symbolValue) takes a symbol value and returns the string key corresponding to it. Each is the other's inverse, so the following is true:

\n

js

\n
Symbol.keyFor(Symbol.for(\"tokenString\")) === \"tokenString\"; // true\n
\n

Because registered symbols can be arbitrarily created anywhere, they behave almost exactly like the strings they wrap. Therefore, they are not guaranteed to be unique and are not garbage collectable. Therefore, registered symbols are disallowed in WeakMap, WeakSet, WeakRef, and FinalizationRegistry objects.

\n

Well-known Symbols

\n
\n

All static properties of the Symbol constructor are Symbols themselves, whose values are constant across realms. They are known as well-known Symbols, and their purpose is to serve as \"protocols\" for certain built-in JavaScript operations, allowing users to customize the language's behavior. For example, if a constructor function has a method with Symbol.hasInstance as its name, this method will encode its behavior with the instanceof operator.

Prior to well-known Symbols, JavaScript used normal properties to implement certain built-in operations. For example, the JSON.stringify function will attempt to call each object's toJSON() method, and the String function will call the object's toString() and valueOf() methods. However, as more operations are added to the language, designating each operation a \"magic property\" can break backward compatibility and make the language's behavior harder to reason with. Well-known Symbols allow the customizations to be \"invisible\" from normal code, which typically only read string properties.

In MDN and other sources, well-known symbol values are stylized by prefixing @@. For example, Symbol.hasInstance is written as @@hasInstance. This is because symbols don't have actual literal formats, but using Symbol.hasInstance does not reflect the ability of using other aliases to refer to the same symbol. This is like the difference between Function.name and \"Function\".

Well-known symbols do not have the concept of garbage collectability, because they come in a fixed set and are unique throughout the lifetime of the program, similar to intrinsic objects such as Array.prototype, so they are also allowed in WeakMap, WeakSet, WeakRef, and FinalizationRegistry objects.

\n

Finding Symbol properties on objects

\n

The method Object.getOwnPropertySymbols() returns an array of Symbols and lets you find Symbol properties on a given object. Note that every object is initialized with no own Symbol properties, so that this array will be empty unless you've set Symbol properties on the object.

Constructor

\n
Symbol()

Creates a new Symbol object. It is not a constructor in the traditional sense, because it can only be called as a function, instead of being constructed with new Symbol().

Static properties

\n
\n

The static properties are all well-known Symbols. In these Symbols' descriptions, we will use language like \"Symbol.hasInstance is a method determining…\", but bear in mind that this is referring to the semantic of an object's method having this Symbol as the method name (because well-known Symbols act as \"protocols\"), not describing the value of the Symbol itself.

Symbol.asyncIterator

A method that returns the default AsyncIterator for an object. Used by for await...of.

Symbol.hasInstance

A method determining if a constructor object recognizes an object as its instance. Used by instanceof.

Symbol.isConcatSpreadable

A Boolean value indicating if an object should be flattened to its array elements. Used by Array.prototype.concat().

Symbol.iterator

A method returning the default iterator for an object. Used by for...of.

Symbol.match

A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by String.prototype.match().

Symbol.matchAll

A method that returns an iterator, that yields matches of the regular expression against a string. Used by String.prototype.matchAll().

Symbol.replace

A method that replaces matched substrings of a string. Used by String.prototype.replace().

Symbol.search

A method that returns the index within a string that matches the regular expression. Used by String.prototype.search().

Symbol.species

A constructor function that is used to create derived objects.

Symbol.split

A method that splits a string at the indices that match a regular expression. Used by String.prototype.split().

Symbol.toPrimitive

A method converting an object to a primitive value.

Symbol.toStringTag

A string value used for the default description of an object. Used by Object.prototype.toString().

Symbol.unscopables

An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.

\n

Static methods

\n
Symbol.for()

Searches for existing Symbols with the given key and returns it if found. Otherwise a new Symbol gets created in the global Symbol registry with key.

Symbol.keyFor()

Retrieves a shared Symbol key from the global Symbol registry for the given Symbol.

Instance properties

\n
\n

These properties are defined on Symbol.prototype and shared by all Symbol instances.

Symbol.prototype.constructor

The constructor function that created the instance object. For Symbol instances, the initial value is the Symbol constructor.

Symbol.prototype.description

A read-only string containing the description of the Symbol.

Symbol.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Symbol\". This property is used in Object.prototype.toString(). However, because Symbol also has its own toString() method, this property is not used unless you call Object.prototype.toString.call() with a symbol as thisArg.

\n

Instance methods

\n
Symbol.prototype.toString()

Returns a string containing the description of the Symbol. Overrides the Object.prototype.toString() method.

Symbol.prototype.valueOf()

Returns the Symbol. Overrides the Object.prototype.valueOf() method.

Symbol.prototype[@@toPrimitive]()

Returns the Symbol.

Examples

\n

Using the typeof operator with Symbols

\n
\n

The typeof operator can help you to identify Symbols.

\n

js

\n
typeof Symbol() === \"symbol\";\ntypeof Symbol(\"foo\") === \"symbol\";\ntypeof Symbol.iterator === \"symbol\";\n
\n
\n

Symbol type conversions

\n
\n

Some things to note when working with type conversion of Symbols.

\n

Symbols and for...in iteration

\n
\n

Symbols are not enumerable in for...in iterations. In addition, Object.getOwnPropertyNames() will not return Symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these.

\n

js

\n
const obj = {};\n\nobj[Symbol(\"a\")] = \"a\";\nobj[Symbol.for(\"b\")] = \"b\";\nobj[\"c\"] = \"c\";\nobj.d = \"d\";\n\nfor (const i in obj) {\n  console.log(i);\n}\n// \"c\" \"d\"\n
\n
\n

Symbols and JSON.stringify()

\n
\n

Symbol-keyed properties will be completely ignored when using JSON.stringify():

\n

js

\n
JSON.stringify({ [Symbol(\"foo\")]: \"foo\" });\n// '{}'\n
\n

For more details, see JSON.stringify().

\n

Symbol wrapper objects as property keys

\n
\n

When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped Symbol:

\n

js

\n
const sym = Symbol(\"foo\");\nconst obj = { [sym]: 1 };\nobj[sym]; // 1\nobj[Object(sym)]; // still 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@toPrimitive471544No341047474434105.01.06.0.0
Symbol381236No2593838362593.01.00.12.0
Symbol38
12Edge 12 included Symbol properties in JSON.stringify() output.
36No2593838362593.01.00.12.0
asyncIterator637957No5011.16363574611.38.01.010.0.0
description707963No5712.1
12No support for an undefined description.
\n
7070634912.2
12No support for an undefined description.
\n
10.01.011.0.0
for401236No2794040362794.01.00.12.0
hasInstance501550No371050505037105.01.06.5.0
isConcatSpreadable481548No351048484835105.01.06.0.0
iterator431236No301043433630104.01.00.12.0
keyFor401236No2794040362794.01.00.12.0
match507940No371050504037105.01.06.0.0
matchAll737967No6013737367521311.01.012.0.0
replace507949No371050504937105.01.06.0.0
search507949No371050504937105.01.06.0.0
species511341No381051514141105.01.06.5.0
split507949No371050504937105.01.06.0.0
toPrimitive471544No341047474434105.01.06.0.0
toString381236No2593838362593.01.00.12.0
toStringTag491551No361049495136105.01.06.0.0
unscopables381248No2593838482593.01.00.12.0
valueOf381236No2593838362593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\n

\n
\n", + "global_objects/encodeuri": "

encodeURI()

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to encodeURIComponent(), this function encodes fewer characters, preserving those that are part of the URI syntax.

\n

Try it

\n

Syntax

\n
\n

js

\n
encodeURI(uri)\n
\n

Parameters

\n
uri

A string to be encoded as a URI.

Return value

\n

A new string representing the provided string encoded as a URI.

Exceptions

\n
URIError

Thrown if uri contains a lone surrogate.

Description

\n
\n

encodeURI() is a function property of the global object.

The encodeURI() function escapes characters by UTF-8 code units, with each octet encoded in the format %XX, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause encodeURI() to throw a URIError.

encodeURI() escapes all characters except:

A–Z a–z 0–9 - _ . ! ~ * ' ( )\n\n; / ? : @ & = + $ , #\n

The characters on the second line are characters that may be part of the URI syntax, and are only escaped by encodeURIComponent(). Both encodeURI() and encodeURIComponent() do not encode the characters -.!~*'(), known as \"unreserved marks\", which do not have a reserved purpose but are allowed in a URI \"as is\". (See RFC2396)

The encodeURI() function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning:

\n

url

\n
http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor\n
\n
\n

Examples

\n

encodeURI() vs. encodeURIComponent()

\n
\n

encodeURI() differs from encodeURIComponent() as follows:

\n

js

\n
const set1 = \";/?:@&=+$,#\"; // Reserved Characters\nconst set2 = \"-.!~*'()\"; // Unreserved Marks\nconst set3 = \"ABC abc 123\"; // Alphanumeric Characters + Space\n\nconsole.log(encodeURI(set1)); // ;/?:@&=+$,#\nconsole.log(encodeURI(set2)); // -.!~*'()\nconsole.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)\n\nconsole.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23\nconsole.log(encodeURIComponent(set2)); // -.!~*'()\nconsole.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)\n
\n

Note that encodeURI() by itself cannot form proper HTTP GET and POST requests, such as for XMLHttpRequest, because &, +, and = are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent(), however, does encode these characters.

\n

Encoding a lone surrogate throws

\n
\n

A URIError will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:

\n

js

\n
// High-low pair OK\nencodeURI(\"\\uD800\\uDFFF\"); // \"%F0%90%8F%BF\"\n\n// Lone high-surrogate code unit throws \"URIError: malformed URI sequence\"\nencodeURI(\"\\uD800\");\n\n// Lone low-surrogate code unit throws \"URIError: malformed URI sequence\"\nencodeURI(\"\\uDFFF\");\n
\n

You can use String.prototype.toWellFormed(), which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use String.prototype.isWellFormed() to check if a string contains lone surrogates before passing it to encodeURI().

\n

Encoding for RFC3986

\n
\n

The more recent RFC3986 makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ', (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format.

\n

js

\n
function encodeRFC3986URI(str) {\n  return encodeURI(str)\n    .replace(/%5B/g, \"[\")\n    .replace(/%5D/g, \"]\")\n    .replace(\n      /[!'()*]/g,\n      (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n    );\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-encodeuri-uri
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
encodeURI11215.571.14.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI\n

\n
\n", + "global_objects/evalerror": "

EvalError

\n

The EvalError object indicates an error regarding the global eval() function. This exception is not thrown by JavaScript anymore, however the EvalError object remains for compatibility.

EvalError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

EvalError is a subclass of Error.

\n
\n

Constructor

\n
EvalError()

Creates a new EvalError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on EvalError.prototype and shared by all EvalError instances.

EvalError.prototype.constructor

The constructor function that created the instance object. For EvalError instances, the initial value is the EvalError constructor.

EvalError.prototype.name

Represents the name for the type of error. For EvalError.prototype.name, the initial value is \"EvalError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Creating an EvalError

\n
\n

js

\n
try {\n  throw new EvalError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof EvalError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"EvalError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-evalerror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
EvalError11215.5514.418410.111.01.00.10.0
EvalError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError\n

\n
\n", + "global_objects/rangeerror": "

RangeError

The RangeError object indicates an error when a value is not in the set or range of allowed values.

\n

Description

\n
\n

A RangeError is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.

This can be encountered when:

RangeError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

RangeError is a subclass of Error.

\n

Constructor

\n
RangeError()

Creates a new RangeError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on RangeError.prototype and shared by all RangeError instances.

RangeError.prototype.constructor

The constructor function that created the instance object. For RangeError instances, the initial value is the RangeError constructor.

RangeError.prototype.name

Represents the name for the type of error. For RangeError.prototype.name, the initial value is \"RangeError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Using RangeError (for numeric values)

\n
\n

js

\n
function check(n) {\n  if (!(n >= -500 && n <= 500)) {\n    throw new RangeError(\"The argument must be between -500 and 500.\");\n  }\n}\n\ntry {\n  check(2000);\n} catch (error) {\n  if (error instanceof RangeError) {\n    // Handle the error\n  }\n}\n
\n

Using RangeError (for non-numeric values)

\n
\n

js

\n
function check(value) {\n  if (![\"apple\", \"banana\", \"carrot\"].includes(value)) {\n    throw new RangeError(\n      'The argument must be an \"apple\", \"banana\", or \"carrot\".',\n    );\n  }\n}\n\ntry {\n  check(\"cabbage\");\n} catch (error) {\n  if (error instanceof RangeError) {\n    // Handle the error\n  }\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-rangeerror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
RangeError11215.5514.418410.111.01.00.10.0
RangeError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError\n

\n
\n", + "global_objects/referenceerror": "

ReferenceError

\n

The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

ReferenceError is a subclass of Error.

\n
\n

Constructor

\n
ReferenceError()

Creates a new ReferenceError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on ReferenceError.prototype and shared by all ReferenceError instances.

ReferenceError.prototype.constructor

The constructor function that created the instance object. For ReferenceError instances, the initial value is the ReferenceError constructor.

ReferenceError.prototype.name

Represents the name for the type of error. For ReferenceError.prototype.name, the initial value is \"ReferenceError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Catching a ReferenceError

\n
\n

js

\n
try {\n  let a = undefinedVariable;\n} catch (e) {\n  console.log(e instanceof ReferenceError); // true\n  console.log(e.message); // \"undefinedVariable is not defined\"\n  console.log(e.name); // \"ReferenceError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a ReferenceError

\n
\n

js

\n
try {\n  throw new ReferenceError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof ReferenceError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"ReferenceError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-referenceerror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ReferenceError11215.5514.418410.111.01.00.10.0
ReferenceError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError\n

\n
\n", + "global_objects/syntaxerror": "

SyntaxError

\n

The SyntaxError object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.

SyntaxError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

SyntaxError is a subclass of Error.

\n
\n

Constructor

\n
SyntaxError()

Creates a new SyntaxError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on SyntaxError.prototype and shared by all SyntaxError instances.

SyntaxError.prototype.constructor

The constructor function that created the instance object. For SyntaxError instances, the initial value is the SyntaxError constructor.

SyntaxError.prototype.name

Represents the name for the type of error. For SyntaxError.prototype.name, the initial value is \"SyntaxError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Catching a SyntaxError

\n
\n

js

\n
try {\n  eval(\"hoo bar\");\n} catch (e) {\n  console.log(e instanceof SyntaxError); // true\n  console.log(e.message);\n  console.log(e.name); // \"SyntaxError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a SyntaxError

\n
\n

js

\n
try {\n  throw new SyntaxError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof SyntaxError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"SyntaxError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-syntaxerror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
SyntaxError11215.5514.418410.111.01.00.10.0
SyntaxError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError\n

\n
\n", + "global_objects/typeerror": "

TypeError

\n

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.

A TypeError may be thrown when:

TypeError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

TypeError is a subclass of Error.

\n
\n

Constructor

\n
TypeError()

Creates a new TypeError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on TypeError.prototype and shared by all TypeError instances.

TypeError.prototype.constructor

The constructor function that created the instance object. For TypeError instances, the initial value is the TypeError constructor.

TypeError.prototype.name

Represents the name for the type of error. For TypeError.prototype.name, the initial value is \"TypeError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Catching a TypeError

\n
\n

js

\n
try {\n  null.f();\n} catch (e) {\n  console.log(e instanceof TypeError); // true\n  console.log(e.message); // \"null has no properties\"\n  console.log(e.name); // \"TypeError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a TypeError

\n
\n

js

\n
try {\n  throw new TypeError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof TypeError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"TypeError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-typeerror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
TypeError11215.5514.418410.111.01.00.10.0
TypeError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError\n

\n
\n", + "global_objects/internalerror": "

InternalError

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The InternalError object indicates an error that occurred internally in the JavaScript engine.

Example cases are mostly when something is too large, e.g.:

InternalError is a subclass of Error.

\n
\n

Constructor

\n
\nInternalError() Non-standard \n

Creates a new InternalError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on InternalError.prototype and shared by all InternalError instances.

InternalError.prototype.constructor

The constructor function that created the instance object. For InternalError instances, the initial value is the InternalError constructor.

InternalError.prototype.name

Represents the name for the type of error. For InternalError.prototype.name, the initial value is \"InternalError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Too much recursion

\n
\n

This recursive function runs 10 times, as per the exit condition.

\n

js

\n
function loop(x) {\n  // \"x >= 10\" is the exit condition\n  if (x >= 10) return;\n\n  // do stuff\n  loop(x + 1); // the recursive call\n}\nloop(0);\n
\n

Setting this condition to an extremely high value, may not work:

\n

js

\n
function loop(x) {\n  if (x >= 1000000000000) return;\n\n  // do stuff\n  loop(x + 1);\n}\nloop(0);\n\n// InternalError: too much recursion\n
\n

For more information, see InternalError: too much recursion.

\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
InternalErrorNoNo1NoNoNoNoNo4NoNoNoNoNo
InternalErrorNoNo1NoNoNoNoNo4NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError\n

\n
\n", + "global_objects/number": "

Number

\n

Number values represent floating-point numbers like 37 or -9.25.

The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

\n
\n

Description

\n
\n

Numbers are most commonly expressed in literal forms like 255 or 3.14159. The lexical grammar contains a more detailed reference.

\n

js

\n
255; // two-hundred and fifty-five\n255.0; // same number\n255 === 255.0; // true\n255 === 0xff; // true (hexadecimal notation)\n255 === 0b11111111; // true (binary notation)\n255 === 0.255e3; // true (decimal exponential notation)\n
\n

A number literal like 37 in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript also has a BigInt type, but it's not designed to replace Number for everyday uses. 37 is still a number, not a BigInt.)

When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN.

\n

js

\n
Number(\"123\"); // returns the number 123\nNumber(\"123\") === 123; // true\n\nNumber(\"unicorn\"); // NaN\nNumber(undefined); // NaN\n
\n
\n

Number encoding

\n
\n

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision. Very briefly, an IEEE 754 double-precision number uses 64 bits to represent 3 parts:

The mantissa (also called significand) is the part of the number representing the actual value (significant digits). The exponent is the power of 2 that the mantissa should be multiplied by. Thinking about it as scientific notation:

Number = ( 1 ) sign ( 1 + mantissa ) 2 exponent \\text{Number} = ({-1})^{\\text{sign}} \\cdot (1 + \\text{mantissa}) \\cdot 2^{\\text{exponent}}

The mantissa is stored with 52 bits, interpreted as digits after 1.… in a binary fractional number. Therefore, the mantissa's precision is 2-52 (obtainable via Number.EPSILON), or about 15 to 17 decimal places; arithmetic above that level of precision is subject to rounding.

The largest value a number can hold is 21023 × (2 - 2-52) (with the exponent being 1023 and the mantissa being 0.1111… in base 2), which is obtainable via Number.MAX_VALUE. Values higher than that are replaced with the special number constant Infinity.

Integers can only be represented without loss of precision in the range -253 + 1 to 253 - 1, inclusive (obtainable via Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER), because the mantissa can only hold 53 bits (including the leading 1).

More details on this are described in the ECMAScript standard.

\n

Number coercion

\n
\n

Many built-in operations that expect numbers first coerce their arguments to numbers (which is largely why Number objects behave similarly to number primitives). The operation can be summarized as follows:

There are two ways to achieve nearly the same effect in JavaScript.

Number.parseFloat() and Number.parseInt() are similar to Number() but only convert strings, and have slightly different parsing rules. For example, parseInt() doesn't recognize the decimal point, and parseFloat() doesn't recognize the 0x prefix.

Integer conversion

Some operations expect integers, most notably those that work with array/string indices, date/time components, and number radixes. After performing the number coercion steps above, the result is truncated to an integer (by discarding the fractional part). If the number is ±Infinity, it's returned as-is. If the number is NaN or -0, it's returned as 0. The result is therefore always an integer (which is not -0) or ±Infinity.

Notably, when converted to integers, both undefined and null become 0, because undefined is converted to NaN, which also becomes 0.

Fixed-width number conversion

JavaScript has some lower-level functions that deal with the binary encoding of integer numbers, most notably bitwise operators and TypedArray objects. Bitwise operators always convert the operands to 32-bit integers. In these cases, after converting the value to a number, the number is then normalized to the given width by first truncating the fractional part and then taking the lowest bits in the integer's two's complement encoding.

\n

js

\n
new Int32Array([1.1, 1.9, -1.1, -1.9]); // Int32Array(4) [ 1, 1, -1, -1 ]\n\nnew Int8Array([257, -257]); // Int8Array(2) [ 1, -1 ]\n// 257 = 0001 0000 0001\n//     =      0000 0001 (mod 2^8)\n//     = 1\n// -257 = 1110 1111 1111\n//      =      1111 1111 (mod 2^8)\n//      = -1 (as signed integer)\n\nnew Uint8Array([257, -257]); // Uint8Array(2) [ 1, 255 ]\n// -257 = 1110 1111 1111\n//      =      1111 1111 (mod 2^8)\n//      = 255 (as unsigned integer)\n
\n
\n

Constructor

\n
\n
Number()

Creates a new Number value.

When Number is called as a constructor (with new), it creates a Number object, which is not a primitive. For example, typeof new Number(42) === \"object\", and new Number(42) !== 42 (although new Number(42) == 42).

Warning: You should rarely find yourself using Number as a constructor.

\n

Static properties

\n
Number.EPSILON

The smallest interval between two representable numbers.

Number.MAX_SAFE_INTEGER

The maximum safe integer in JavaScript (253 - 1).

Number.MAX_VALUE

The largest positive representable number.

Number.MIN_SAFE_INTEGER

The minimum safe integer in JavaScript (-(253 - 1)).

Number.MIN_VALUE

The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).

Number.NaN

Special \"Not a Number\" value.

Number.NEGATIVE_INFINITY

Special value representing negative infinity. Returned on overflow.

Number.POSITIVE_INFINITY

Special value representing infinity. Returned on overflow.

Static methods

\n
Number.isFinite()

Determine whether the passed value is a finite number.

Number.isInteger()

Determine whether the passed value is an integer.

Number.isNaN()

Determine whether the passed value is NaN.

Number.isSafeInteger()

Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).

Number.parseFloat()

This is the same as the global parseFloat() function.

Number.parseInt()

This is the same as the global parseInt() function.

Instance properties

\n
\n

These properties are defined on Number.prototype and shared by all Number instances.

Number.prototype.constructor

The constructor function that created the instance object. For Number instances, the initial value is the Number constructor.

\n

Instance methods

\n
Number.prototype.toExponential()

Returns a string representing the number in exponential notation.

Number.prototype.toFixed()

Returns a string representing the number in fixed-point notation.

Number.prototype.toLocaleString()

Returns a string with a language sensitive representation of this number. Overrides the Object.prototype.toLocaleString() method.

Number.prototype.toPrecision()

Returns a string representing the number to a specified precision in fixed-point or exponential notation.

Number.prototype.toString()

Returns a string representing the specified object in the specified radix (\"base\"). Overrides the Object.prototype.toString() method.

Number.prototype.valueOf()

Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.

Examples

\n

Using the Number object to assign values to numeric variables

\n
\n

The following example uses the Number object's properties to assign values to several numeric variables:

\n

js

\n
const biggestNum = Number.MAX_VALUE;\nconst smallestNum = Number.MIN_VALUE;\nconst infiniteNum = Number.POSITIVE_INFINITY;\nconst negInfiniteNum = Number.NEGATIVE_INFINITY;\nconst notANum = Number.NaN;\n
\n
\n

Integer range for Number

\n
\n

The following example shows the minimum and maximum integer values that can be represented as Number object.

\n

js

\n
const biggestInt = Number.MAX_SAFE_INTEGER; // (2**53 - 1) => 9007199254740991\nconst smallestInt = Number.MIN_SAFE_INTEGER; // -(2**53 - 1) => -9007199254740991\n
\n

When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to Number type.

A possible workaround is to use String instead.

Larger numbers can be represented using the BigInt type.

\n

Using Number() to convert a Date object

\n
\n

The following example converts the Date object to a numerical value using Number as a function:

\n

js

\n
const d = new Date(\"1995-12-17T03:24:00\");\nconsole.log(Number(d));\n
\n

This logs 819199440000.

\n

Convert numeric strings and null to numbers

\n
\n

js

\n
Number(\"123\"); // 123\nNumber(\"123\") === 123; // true\nNumber(\"12.3\"); // 12.3\nNumber(\"12.00\"); // 12\nNumber(\"123e-1\"); // 12.3\nNumber(\"\"); // 0\nNumber(null); // 0\nNumber(\"0x11\"); // 17\nNumber(\"0b11\"); // 3\nNumber(\"0o11\"); // 9\nNumber(\"foo\"); // NaN\nNumber(\"100a\"); // NaN\nNumber(\"-Infinity\"); // -Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
EPSILON341225No2193734252192.01.00.12.0
MAX_SAFE_INTEGER341231No2193734312192.01.00.12.0
MAX_VALUE11214314.418410.111.01.00.10.0
MIN_SAFE_INTEGER341231No2193734312192.01.00.12.0
MIN_VALUE11214314.418410.111.01.00.10.0
NEGATIVE_INFINITY11214314.418410.111.01.00.10.0
NaN11214314.418410.111.01.00.10.0
Number11213314.418410.111.01.00.10.0
POSITIVE_INFINITY11214314.418410.111.01.00.10.0
Number11213314.418410.111.01.00.10.0
isFinite191216No1594.425161491.51.00.10.0
isInteger341216No2193734162192.01.00.12.0
isNaN251215No1594.425151491.51.00.10.0
isSafeInteger341232No2193734322192.01.00.12.0
parseFloat341225No2193734252192.01.00.12.0
parseInt341225No2193734252192.01.00.12.0
toExponential11215.5724.418410.111.01.00.10.0
toFixed11215.5724.418410.111.01.00.10.0
toLocaleString1
12Before Edge 18, numbers are rounded to 15 decimal digits. For example, (1000000000000005).toLocaleString('en-US') returns \"1,000,000,000,000,010\".
1
5In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, (1000000000000005).toLocaleString('en-US') returns \"1,000,000,000,000,010\".
414.418410.111.01.00.10.0
toPrecision11215.5724.418410.111.01.00.10.0
toString11213414.418410.111.01.00.10.0
valueOf11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\n

\n
\n", + "global_objects/bigint": "

BigInt

BigInt values represent numeric values which are too large to be represented by the number primitive.

\n

Description

\n
\n

A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending n to the end of an integer literal, or by calling the BigInt() function (without the new operator) and giving it an integer value or string value.

\n

js

\n
const previouslyMaxSafeInteger = 9007199254740991n;\n\nconst alsoHuge = BigInt(9007199254740991);\n// 9007199254740991n\n\nconst hugeString = BigInt(\"9007199254740991\");\n// 9007199254740991n\n\nconst hugeHex = BigInt(\"0x1fffffffffffff\");\n// 9007199254740991n\n\nconst hugeOctal = BigInt(\"0o377777777777777777\");\n// 9007199254740991n\n\nconst hugeBin = BigInt(\n  \"0b11111111111111111111111111111111111111111111111111111\",\n);\n// 9007199254740991n\n
\n

BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in Math object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.

\n

Type information

\n
\n

When tested against typeof, a BigInt value (bigint primitive) will give \"bigint\":

\n

js

\n
typeof 1n === \"bigint\"; // true\ntypeof BigInt(\"1\") === \"bigint\"; // true\n
\n

A BigInt value can also be wrapped in an Object:

\n

js

\n
typeof Object(1n) === \"object\"; // true\n
\n
\n

Operators

\n
\n

Most operators support BigInts, however most do not permit operands to be of mixed types — both operands must be BigInt or neither:

The boolean-returning operators allow mixing numbers and BigInts as operands:

A couple of operators do not support BigInt at all:

Special cases:

\n

js

\n
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n\nconst maxPlusOne = previousMaxSafe + 1n; // 9007199254740992n\nconst theFuture = previousMaxSafe + 2n; // 9007199254740993n, this works now!\nconst multi = previousMaxSafe * 2n; // 18014398509481982n\nconst subtr = multi - 10n; // 18014398509481972n\nconst mod = multi % 10n; // 2n\nconst bigN = 2n ** 54n; // 18014398509481984n\nbigN * -1n; // -18014398509481984n\nconst expected = 4n / 2n; // 2n\nconst truncated = 5n / 2n; // 2n, not 2.5n\n
\n
\n

Comparisons

\n
\n

A BigInt value is not strictly equal to a Number value, but it is loosely so:

\n

js

\n
0n === 0; // false\n0n == 0; // true\n
\n

A Number value and a BigInt value may be compared as usual:

\n

js

\n
1n < 2; // true\n2n > 1; // true\n2 > 2; // false\n2n > 2; // false\n2n >= 2; // true\n
\n

BigInt values and Number values may be mixed in arrays and sorted:

\n

js

\n
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];\n// [4n, 6, -12n, 10, 4, 0, 0n]\n\nmixed.sort(); // default sorting behavior\n// [ -12n, 0, 0n, 10, 4n, 4, 6 ]\n\nmixed.sort((a, b) => a - b);\n// won't work since subtraction will not work with mixed types\n// TypeError: can't convert BigInt value to Number value\n\n// sort with an appropriate numeric comparator\nmixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n// [ -12n, 0, 0n, 4n, 4, 6, 10 ]\n
\n

Note that comparisons with Object-wrapped BigInt values act as with other objects, only indicating equality when the same object instance is compared:

\n

js

\n
Object(0n) === 0n; // false\nObject(0n) === Object(0n); // false\n\nconst o = Object(0n);\no === o; // true\n
\n

Because coercing between Number values and BigInt values can lead to loss of precision, the following are recommended:

\n

Conditionals

\n
\n

A BigInt value follows the same conversion rules as Numbers when:

Namely, only 0n is falsy; everything else is truthy.

\n

js

\n
if (0n) {\n  console.log(\"Hello from the if!\");\n} else {\n  console.log(\"Hello from the else!\");\n}\n// \"Hello from the else!\"\n\n0n || 12n; // 12n\n0n && 12n; // 0n\nBoolean(0n); // false\nBoolean(12n); // true\n!12n; // false\n!0n; // true\n
\n
\n

Cryptography

\n

The operations supported on BigInt values are not constant-time and are thus open to timing attacks. JavaScript BigInts therefore could be dangerous for use in cryptography without mitigating factors. As a very generic example, an attacker could measure the time difference between 101n ** 65537n and 17n ** 9999n, and deduce the magnitude of secrets, such as private keys, based on the time elapsed. If you still have to use BigInts, take a look at the Timing attack FAQ for general advice regarding the issue.

Use within JSON

\n
\n

Using JSON.stringify() with any BigInt value will raise a TypeError, as BigInt values aren't serialized in JSON by default. However, JSON.stringify() specifically leaves a backdoor for BigInt values: it would try to call the BigInt's toJSON() method. (It doesn't do so for any other primitive values.) Therefore, you can implement your own toJSON() method (which is one of the few cases where patching built-in objects is not explicitly discouraged):

\n

js

\n
BigInt.prototype.toJSON = function () {\n  return this.toString();\n};\n
\n

Instead of throwing, JSON.stringify() now produces a string like this:

\n

js

\n
console.log(JSON.stringify({ a: 1n }));\n// {\"a\":\"1\"}\n
\n

If you do not wish to patch BigInt.prototype, you can use the replacer parameter of JSON.stringify to serialize BigInt values:

\n

js

\n
const replacer = (key, value) =>\n  typeof value === \"bigint\" ? value.toString() : value;\n\nconst data = {\n  number: 1,\n  big: 18014398509481982n,\n};\nconst stringified = JSON.stringify(data, replacer);\n\nconsole.log(stringified);\n// {\"number\":1,\"big\":\"18014398509481982\"}\n
\n

If you have JSON data containing values you know will be large integers, you can use the reviver parameter of JSON.parse to handle them:

\n

js

\n
const reviver = (key, value) => (key === \"big\" ? BigInt(value) : value);\n\nconst payload = '{\"number\":1,\"big\":\"18014398509481982\"}';\nconst parsed = JSON.parse(payload, reviver);\n\nconsole.log(parsed);\n// { number: 1, big: 18014398509481982n }\n
\n

Note: While it's possible to make the replacer of JSON.stringify() generic and properly serialize BigInt values for all objects, the reviver of JSON.parse() must be specific to the payload shape you expect, because the serialization is lossy: it's not possible to distinguish between a string that represents a BigInt and a normal string.

\n

BigInt coercion

\n
\n

Many built-in operations that expect BigInts first coerce their arguments to BigInts. The operation can be summarized as follows:

The best way to achieve nearly the same effect in JavaScript is through the BigInt() function: BigInt(x) uses the same algorithm to convert x, except that Numbers don't throw a TypeError, but are converted to BigInts if they are integers.

Note that built-in operations expecting BigInts often truncate the BigInt to a fixed width after coercion. This includes BigInt.asIntN(), BigInt.asUintN(), and methods of BigInt64Array and BigUint64Array.

\n

Constructor

\n
BigInt()

Creates a new BigInt value.

Static methods

\n
BigInt.asIntN()

Clamps a BigInt value to a signed integer value, and returns that value.

BigInt.asUintN()

Clamps a BigInt value to an unsigned integer value, and returns that value.

Instance properties

\n
\n

These properties are defined on BigInt.prototype and shared by all BigInt instances.

BigInt.prototype.constructor

The constructor function that created the instance object. For BigInt instances, the initial value is the BigInt constructor.

BigInt.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"BigInt\". This property is used in Object.prototype.toString(). However, because BigInt also has its own toString() method, this property is not used unless you call Object.prototype.toString.call() with a BigInt as thisArg.

\n

Instance methods

\n
BigInt.prototype.toLocaleString()

Returns a string with a language-sensitive representation of this BigInt value. Overrides the Object.prototype.toLocaleString() method.

BigInt.prototype.toString()

Returns a string representing this BigInt value in the specified radix (base). Overrides the Object.prototype.toString() method.

BigInt.prototype.valueOf()

Returns this BigInt value. Overrides the Object.prototype.valueOf() method.

Examples

\n

Calculating Primes

\n
\n

js

\n
// Returns true if the passed BigInt value is a prime number\nfunction isPrime(p) {\n  for (let i = 2n; i * i <= p; i++) {\n    if (p % i === 0n) return false;\n  }\n  return true;\n}\n\n// Takes a BigInt value as an argument, returns nth prime number as a BigInt value\nfunction nthPrime(nth) {\n  let maybePrime = 2n;\n  let prime = 0n;\n\n  while (nth >= 0n) {\n    if (isPrime(maybePrime)) {\n      nth--;\n      prime = maybePrime;\n    }\n    maybePrime++;\n  }\n\n  return prime;\n}\n\nnthPrime(20n);\n// 73n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigInt677968No541467676848149.01.010.4.0
BigInt677968No541467676848149.01.010.4.0
asIntN677968No541467676848149.01.010.4.0
asUintN677968No541467676848149.01.010.4.0
toLocaleString677968No541467676848149.01.010.4.0
toString677968No541467676848149.01.010.4.0
valueOf677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\n

\n
\n", + "global_objects/math": "

Math

\n

The Math namespace object contains static properties and methods for mathematical constants and functions.

Math works with the Number type. It doesn't work with BigInt.

\n
\n

Description

\n
\n

Unlike most global objects, Math is not a constructor. You cannot use it with the new operator or invoke the Atomics object as a function. All properties and methods of Math are static.

Note: Many Math functions have a precision that's implementation-dependent.

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

\n

Static properties

\n
Math.E

Euler's number and the base of natural logarithms; approximately 2.718.

Math.LN10

Natural logarithm of 10; approximately 2.303.

Math.LN2

Natural logarithm of 2; approximately 0.693.

Math.LOG10E

Base-10 logarithm of E; approximately 0.434.

Math.LOG2E

Base-2 logarithm of E; approximately 1.443.

Math.PI

Ratio of a circle's circumference to its diameter; approximately 3.14159.

Math.SQRT1_2

Square root of ½; approximately 0.707.

Math.SQRT2

Square root of 2; approximately 1.414.

Math[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Math\". This property is used in Object.prototype.toString().

Static methods

\n
Math.abs()

Returns the absolute value of x.

Math.acos()

Returns the arccosine of x.

Math.acosh()

Returns the hyperbolic arccosine of x.

Math.asin()

Returns the arcsine of x.

Math.asinh()

Returns the hyperbolic arcsine of a number.

Math.atan()

Returns the arctangent of x.

Math.atan2()

Returns the arctangent of the quotient of its arguments.

Math.atanh()

Returns the hyperbolic arctangent of x.

Math.cbrt()

Returns the cube root of x.

Math.ceil()

Returns the smallest integer greater than or equal to x.

Math.clz32()

Returns the number of leading zero bits of the 32-bit integer x.

Math.cos()

Returns the cosine of x.

Math.cosh()

Returns the hyperbolic cosine of x.

Math.exp()

Returns ex, where x is the argument, and e is Euler's number (2.718…, the base of the natural logarithm).

Math.expm1()

Returns subtracting 1 from exp(x).

Math.floor()

Returns the largest integer less than or equal to x.

Math.fround()

Returns the nearest single precision float representation of x.

Math.hypot()

Returns the square root of the sum of squares of its arguments.

Math.imul()

Returns the result of the 32-bit integer multiplication of x and y.

Math.log()

Returns the natural logarithm (㏒e; also, ㏑) of x.

Math.log10()

Returns the base-10 logarithm of x.

Math.log1p()

Returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x.

Math.log2()

Returns the base-2 logarithm of x.

Math.max()

Returns the largest of zero or more numbers.

Math.min()

Returns the smallest of zero or more numbers.

Math.pow()

Returns base x to the exponent power y (that is, xy).

Math.random()

Returns a pseudo-random number between 0 and 1.

Math.round()

Returns the value of the number x rounded to the nearest integer.

Math.sign()

Returns the sign of the x, indicating whether x is positive, negative, or zero.

Math.sin()

Returns the sine of x.

Math.sinh()

Returns the hyperbolic sine of x.

Math.sqrt()

Returns the positive square root of x.

Math.tan()

Returns the tangent of x.

Math.tanh()

Returns the hyperbolic tangent of x.

Math.trunc()

Returns the integer portion of x, removing any fractional digits.

Examples

\n

Converting between degrees and radians

\n
\n

The trigonometric functions sin(), cos(), tan(), asin(), acos(), atan(), and atan2() expect (and return) angles in radians.

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

\n

js

\n
function degToRad(degrees) {\n  return degrees * (Math.PI / 180);\n}\n\nfunction radToDeg(rad) {\n  return rad / (Math.PI / 180);\n}\n
\n
\n

Calculating the height of an equilateral triangle

\n
\n

If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

An equilateral triangle where a perpendicular of one edge is drawn from the opposite vertex, forming a right triangle with three sides marked as \"adjacent\", \"opposite\", and \"hypotenuse\". The angle between the \"adjacent\" and \"hypotenuse\" sides is 60 degrees.

In JavaScript, we can do this with the following:

\n

js

\n
50 * Math.tan(degToRad(60));\n
\n

We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians.

\n

Returning a random integer between two bounds

\n
\n

This can be achieved with a combination of Math.random() and Math.floor():

\n

js

\n
function random(min, max) {\n  const num = Math.floor(Math.random() * (max - min + 1)) + min;\n  return num;\n}\n\nrandom(1, 10);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
E11213314.418410.111.01.00.10.0
LN1011213314.418410.111.01.00.10.0
LN211213314.418410.111.01.00.10.0
LOG10E11213314.418410.111.01.00.10.0
LOG2E11213314.418410.111.01.00.10.0
PI11213314.418410.111.01.00.10.0
SQRT1_211213314.418410.111.01.00.10.0
SQRT211213314.418410.111.01.00.10.0
Math11213314.418410.111.01.00.10.0
abs11213314.418410.111.01.00.10.0
acos11213314.418410.111.01.00.10.0
acosh381225No2583838252583.01.00.12.0
asin11213314.418410.111.01.00.10.0
asinh381225No2583838252583.01.00.12.0
atan11213314.418410.111.01.00.10.0
atan211214314.418410.111.01.00.10.0
atanh381225No2583838252583.01.00.12.0
cbrt381225No2583838252583.01.00.12.0
ceil11213314.418410.111.01.00.10.0
clz32381231No2573838312573.01.00.12.0
cos11213314.418410.111.01.00.10.0
cosh381225No2583838252583.01.00.12.0
exp11213314.418410.111.01.00.10.0
expm1381225No2583838252583.01.00.12.0
floor11213314.418410.111.01.00.10.0
fround381226No2583838262583.01.00.12.0
hypot381227No2583838272583.01.00.12.0
imul281220No1674.428201571.51.00.12.0
log11213314.418410.111.01.00.10.0
log10381225No2583838252583.01.00.12.0
log1p381225No2583838252583.01.00.12.0
log2381225No2583838252583.01.00.12.0
max11213314.418410.111.01.00.10.0
min11213314.418410.111.01.00.10.0
pow11213314.418410.111.01.00.10.0
random11213314.418410.111.01.00.10.0
round11213314.418410.111.01.00.10.0
sign381225No2593838252593.01.00.12.0
sin11213314.418410.111.01.00.10.0
sinh381225No2583838252583.01.00.12.0
sqrt11213314.418410.111.01.00.10.0
tan11213314.418410.111.01.00.10.0
tanh381225No2583838252583.01.00.12.0
trunc381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math\n

\n
\n", + "global_objects/date": "

Date

\n

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).

Note: TC39 is working on Temporal, a new Date/Time API. Read more about it on the Igalia blog. It is not yet ready for production use!

\n
\n

Description

\n

The epoch, timestamps, and invalid date

\n
\n

A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is timezone-agnostic and uniquely defines an instant in history.

Note: While the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

The maximum timestamp representable by a Date object is slightly smaller than the maximum safe integer (Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991). A Date object can represent a maximum of ±8,640,000,000,000,000 milliseconds, or ±100,000,000 (one hundred million) days, relative to the epoch. This is the range from April 20, 271821 BC to September 13, 275760 AD. Any attempt to represent a time outside this range results in the Date object holding a timestamp value of NaN, which is an \"Invalid Date\".

\n

js

\n
console.log(new Date(8.64e15).toString()); // \"Sat Sep 13 275760 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nconsole.log(new Date(8.64e15 + 1).toString()); // \"Invalid Date\"\n
\n

There are various methods that allow you to interact with the timestamp stored in the date:

\n

Date components and time zones

\n
\n

A date is represented internally as a single number, the timestamp. When interacting with it, the timestamp needs to be interpreted as a structured date-and-time representation. There are always two ways to interpret a timestamp: as a local time or as a Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. The local timezone is not stored in the date object, but is determined by the host environment (user's device).

Note: UTC should not be confused with the Greenwich Mean Time (GMT), because they are not always equal — this is explained in more detail in the linked Wikipedia page.

For example, the timestamp 0 represents a unique instant in history, but it can be interpreted in two ways:

The getTimezoneOffset() method returns the difference between UTC and the local time in minutes. Note that the timezone offset does not only depend on the current timezone, but also on the time represented by the Date object, because of daylight saving time and historical changes. In essence, the timezone offset is the offset from UTC time, at the time represented by the Date object and at the location of the host environment.

There are two groups of Date methods: one group gets and sets various date components by interpreting the timestamp as a local time, while the other uses UTC.

The Date() constructor can be called with two or more arguments, in which case they are interpreted as the year, month, day, hour, minute, second, and millisecond, respectively, in local time. Date.UTC() works similarly, but it interprets the components as UTC time and also accepts a single argument representing the year.

Note: Some methods, including the Date() constructor, Date.UTC(), and the deprecated getYear()/setYear() methods, interpret a two-digit year as a year in the 1900s. For example, new Date(99, 5, 24) is interpreted as June 24, 1999, not June 24, 99. See Interpretation of two-digit years for more information.

When a segment overflows or underflows its expected range, it usually \"carries over to\" or \"borrows from\" the higher segment. For example, if the month is set to 12 (months are zero-based, so December is 11), it become the January of the next year. If the day of month is set to 0, it becomes the last day of the previous month. This also applies to dates specified with the date time string format.

\n

Date time string format

\n
\n

There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the date time string format, a simplification of the ISO 8601 calendar date extended format. The format is as follows:

YYYY-MM-DDTHH:mm:ss.sssZ\n

Various components can be omitted, so the following are all valid:

For example, \"2011-10-10\" (date-only form), \"2011-10-10T14:48:00\" (date-time form), or \"2011-10-10T14:48:00.000+09:00\" (date-time form with milliseconds and time zone) are all valid date time strings.

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. This is due to a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility. See Broken Parser – A Web Reality Issue.

Date.parse() and the Date() constructor both accept strings in the date time string format as input. Furthermore, implementations are allowed to support other date formats when the input fails to match this format.

The toISOString() method returns a string representation of the date in the date time string format, with the time zone offset always set to Z (UTC).

Note: You are encouraged to make sure your input conforms to the date time string format above for maximum compatibility, because support for other formats is not guaranteed. However, there are some formats that are supported in all major implementations — like RFC 2822 format — in which case their usage can be acceptable. Always conduct cross-browser tests to ensure your code works in all target browsers. A library can help if many different formats are to be accommodated.

Non-standard strings can be parsed in any way as desired by the implementation, including the time zone — most implementations use the local time zone by default. Implementations are not required to return invalid date for out-of-bounds date components, although they usually do. A string may have in-bounds date components (with the bounds defined above), but does not represent a date in reality (for example, \"February 30\"). Implementations behave inconsistently in this case. The Date.parse() page offers more examples about these non-standard cases.

\n

Other ways to format a date

\n
\n

See the Formats of toString method return values section for examples.

\n

Constructor

\n
Date()

When called as a constructor, returns a new Date object. When called as a function, returns a string representation of the current date and time.

Static methods

\n
Date.now()

Returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.

Date.parse()

Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.

Date.UTC()

Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.

Instance properties

\n
\n

These properties are defined on Date.prototype and shared by all Date instances.

Date.prototype.constructor

The constructor function that created the instance object. For Date instances, the initial value is the Date constructor.

\n

Instance methods

\n
Date.prototype.getDate()

Returns the day of the month (131) for the specified date according to local time.

Date.prototype.getDay()

Returns the day of the week (06) for the specified date according to local time.

Date.prototype.getFullYear()

Returns the year (4 digits for 4-digit years) of the specified date according to local time.

Date.prototype.getHours()

Returns the hour (023) in the specified date according to local time.

Date.prototype.getMilliseconds()

Returns the milliseconds (0999) in the specified date according to local time.

Date.prototype.getMinutes()

Returns the minutes (059) in the specified date according to local time.

Date.prototype.getMonth()

Returns the month (011) in the specified date according to local time.

Date.prototype.getSeconds()

Returns the seconds (059) in the specified date according to local time.

Date.prototype.getTime()

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

Date.prototype.getTimezoneOffset()

Returns the time-zone offset in minutes for the current locale.

Date.prototype.getUTCDate()

Returns the day (date) of the month (131) in the specified date according to universal time.

Date.prototype.getUTCDay()

Returns the day of the week (06) in the specified date according to universal time.

Date.prototype.getUTCFullYear()

Returns the year (4 digits for 4-digit years) in the specified date according to universal time.

Date.prototype.getUTCHours()

Returns the hours (023) in the specified date according to universal time.

Date.prototype.getUTCMilliseconds()

Returns the milliseconds (0999) in the specified date according to universal time.

Date.prototype.getUTCMinutes()

Returns the minutes (059) in the specified date according to universal time.

Date.prototype.getUTCMonth()

Returns the month (011) in the specified date according to universal time.

Date.prototype.getUTCSeconds()

Returns the seconds (059) in the specified date according to universal time.

\nDate.prototype.getYear() Deprecated \n

Returns the year (usually 2–3 digits) in the specified date according to local time. Use getFullYear() instead.

Date.prototype.setDate()

Sets the day of the month for a specified date according to local time.

Date.prototype.setFullYear()

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.

Date.prototype.setHours()

Sets the hours for a specified date according to local time.

Date.prototype.setMilliseconds()

Sets the milliseconds for a specified date according to local time.

Date.prototype.setMinutes()

Sets the minutes for a specified date according to local time.

Date.prototype.setMonth()

Sets the month for a specified date according to local time.

Date.prototype.setSeconds()

Sets the seconds for a specified date according to local time.

Date.prototype.setTime()

Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

Date.prototype.setUTCDate()

Sets the day of the month for a specified date according to universal time.

Date.prototype.setUTCFullYear()

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.

Date.prototype.setUTCHours()

Sets the hour for a specified date according to universal time.

Date.prototype.setUTCMilliseconds()

Sets the milliseconds for a specified date according to universal time.

Date.prototype.setUTCMinutes()

Sets the minutes for a specified date according to universal time.

Date.prototype.setUTCMonth()

Sets the month for a specified date according to universal time.

Date.prototype.setUTCSeconds()

Sets the seconds for a specified date according to universal time.

\nDate.prototype.setYear() Deprecated \n

Sets the year (usually 2–3 digits) for a specified date according to local time. Use setFullYear() instead.

Date.prototype.toDateString()

Returns the \"date\" portion of the Date as a human-readable string like 'Thu Apr 12 2018'.

Date.prototype.toISOString()

Converts a date to a string following the ISO 8601 Extended Format.

Date.prototype.toJSON()

Returns a string representing the Date using toISOString(). Intended for use by JSON.stringify().

Date.prototype.toLocaleDateString()

Returns a string with a locality sensitive representation of the date portion of this date based on system settings.

Date.prototype.toLocaleString()

Returns a string with a locality-sensitive representation of this date. Overrides the Object.prototype.toLocaleString() method.

Date.prototype.toLocaleTimeString()

Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.

Date.prototype.toString()

Returns a string representing the specified Date object. Overrides the Object.prototype.toString() method.

Date.prototype.toTimeString()

Returns the \"time\" portion of the Date as a human-readable string.

Date.prototype.toUTCString()

Converts a date to a string using the UTC timezone.

Date.prototype.valueOf()

Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf() method.

Date.prototype[@@toPrimitive]()

Converts this Date object to a primitive value.

Examples

\n

Several ways to create a Date object

\n
\n

The following examples show several ways to create JavaScript dates:

Note: Creating a date from a string has a lot of behavior inconsistencies. See date time string format for caveats on using different formats.

\n

js

\n
const today = new Date();\nconst birthday = new Date(\"December 17, 1995 03:24:00\"); // DISCOURAGED: may not work in all runtimes\nconst birthday2 = new Date(\"1995-12-17T03:24:00\"); // This is standardized and will work reliably\nconst birthday3 = new Date(1995, 11, 17); // the month is 0-indexed\nconst birthday4 = new Date(1995, 11, 17, 3, 24, 0);\nconst birthday5 = new Date(628021800000); // passing epoch timestamp\n
\n
\n

Formats of toString method return values

\n
\n

js

\n
const date = new Date(\"2020-05-12T23:50:21.817Z\");\ndate.toString(); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)\ndate.toDateString(); // Tue May 12 2020\ndate.toTimeString(); // 18:50:21 GMT-0500 (Central Daylight Time)\ndate[Symbol.toPrimitive](\"string\"); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)\n\ndate.toISOString(); // 2020-05-12T23:50:21.817Z\ndate.toJSON(); // 2020-05-12T23:50:21.817Z\n\ndate.toUTCString(); // Tue, 12 May 2020 23:50:21 GMT\n\ndate.toLocaleString(); // 5/12/2020, 6:50:21 PM\ndate.toLocaleDateString(); // 5/12/2020\ndate.toLocaleTimeString(); // 6:50:21 PM\n
\n

To get Date, Month and Year or Time

\n
\n

js

\n
const date = new Date(\"2000-01-17T16:45:30\");\nconst [month, day, year] = [\n  date.getMonth(),\n  date.getDate(),\n  date.getFullYear(),\n];\n// [0, 17, 2000] as month are 0-indexed\nconst [hour, minutes, seconds] = [\n  date.getHours(),\n  date.getMinutes(),\n  date.getSeconds(),\n];\n// [16, 45, 30]\n
\n

Interpretation of two-digit years

\n
\n

new Date() exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a new Date() call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the year 1900, but in other cases, as an offset from the year 2000.

\n

js

\n
let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)\ndate = new Date(22, 1); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)\ndate = new Date(\"2/1/22\"); // Tue Feb 01 2022 00:00:00 GMT+0000 (GMT)\n\n// Legacy method; always interprets two-digit year values as relative to 1900\ndate.setYear(98);\ndate.toString(); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)\ndate.setYear(22);\ndate.toString(); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)\n
\n

So, to create and get dates between the years 0 and 99, instead use the preferred setFullYear() and getFullYear() methods:.

\n

js

\n
// Preferred method; never interprets any value as being a relative offset,\n// but instead uses the year value as-is\ndate.setFullYear(98);\ndate.getFullYear(); // 98 (not 1998)\ndate.setFullYear(22);\ndate.getFullYear(); // 22 (not 1922, not 2022)\n
\n
\n

Calculating elapsed time

\n
\n

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted.

\n

js

\n
// Using Date objects\nconst start = Date.now();\n\n// The event to time goes here:\ndoSomethingForALongTime();\nconst end = Date.now();\nconst elapsed = end - start; // elapsed time in milliseconds\n
\n
\n

js

\n
// Using built-in methods\nconst start = new Date();\n\n// The event to time goes here:\ndoSomethingForALongTime();\nconst end = new Date();\nconst elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds\n
\n
\n

js

\n
// To test a function and get back its return\nfunction printElapsedTime(testFn) {\n  const startTime = Date.now();\n  const result = testFn();\n  const endTime = Date.now();\n\n  console.log(`Elapsed time: ${String(endTime - startTime)} milliseconds`);\n  return result;\n}\n\nconst yourFunctionReturn = printElapsedTime(yourFunction);\n
\n

Note: In browsers that support the Web Performance API's high-resolution time feature, Performance.now() can provide more reliable and precise measurements of elapsed time than Date.now().

\n

Get the number of seconds since the ECMAScript Epoch

\n
\n
\n

js

\n
const seconds = Math.floor(Date.now() / 1000);\n
\n

In this case, it's important to return only an integer—so a simple division won't do. It's also important to only return actually elapsed seconds. (That's why this code uses Math.floor(), and not Math.round().)

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@toPrimitive471544No341047474434105.01.06.0.0
Date11213314.418410.111.01.00.10.0
UTC11213314.418410.111.01.00.10.0
Date1121
3The ISO8601 Date Format is not supported in Internet Explorer 8 or earlier.
314.418410.111.01.00.10.0
getDate11213314.418410.111.01.00.10.0
getDay11213314.418410.111.01.00.10.0
getFullYear11214414.418410.111.01.00.10.0
getHours11213314.418410.111.01.00.10.0
getMilliseconds11214414.418410.111.01.00.10.0
getMinutes11214314.418410.111.01.00.10.0
getMonth11214314.418410.111.01.00.10.0
getSeconds11214314.418410.111.01.00.10.0
getTime11214314.418410.111.01.00.10.0
getTimezoneOffset11215314.418410.111.01.00.10.0
getUTCDate11214414.418410.111.01.00.10.0
getUTCDay11214414.418410.111.01.00.10.0
getUTCFullYear11214414.418410.111.01.00.10.0
getUTCHours11214414.418410.111.01.00.10.0
getUTCMilliseconds11214414.418410.111.01.00.10.0
getUTCMinutes11214414.418410.111.01.00.10.0
getUTCMonth11214414.418410.111.01.00.10.0
getUTCSeconds11214414.418410.111.01.00.10.0
getYear11213314.418410.111.01.00.10.0
now1121910.544.41841441.01.00.10.0
parse11213314.418410.111.01.00.10.0
setDate11213314.418410.111.01.00.10.0
setFullYear11214414.418410.111.01.00.10.0
setHours11213314.418410.111.01.00.10.0
setMilliseconds11214414.418410.111.01.00.10.0
setMinutes11213314.418410.111.01.00.10.0
setMonth11213314.418410.111.01.00.10.0
setSeconds11213314.418410.111.01.00.10.0
setTime11213314.418410.111.01.00.10.0
setUTCDate11214414.418410.111.01.00.10.0
setUTCFullYear11214414.418410.111.01.00.10.0
setUTCHours11214414.418410.111.01.00.10.0
setUTCMilliseconds11214414.418410.111.01.00.10.0
setUTCMinutes11214414.418410.111.01.00.10.0
setUTCMonth11214414.418410.111.01.00.10.0
setUTCSeconds11214414.418410.111.01.00.10.0
setYear11213314.418410.111.01.00.10.0
toDateString11215.5514.418410.111.01.00.10.0
toGMTString11213314.418410.111.01.00.10.0
toISOString3121910.54≤37184113.21.01.00.10.0
toJSON3121810.54≤37184113.21.01.00.10.0
toLocaleDateString11215.5514.418410.111.01.00.10.0
toLocaleString11213314.418410.111.01.00.10.0
toLocaleTimeString11215.5514.418410.111.01.00.10.0
toString11213314.418410.111.01.00.10.0
toTimeString11215.5514.418410.111.01.00.10.0
toUTCString11214414.418410.111.01.00.10.0
valueOf11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date\n

\n
\n", + "global_objects/string": "

String

The String object is used to represent and manipulate a sequence of characters.

\n

Description

\n

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.

Creating strings

\n
\n

Strings can be created as primitives, from string literals, or as objects, using the String() constructor:

\n

js

\n
const string1 = \"A string primitive\";\nconst string2 = 'Also a string primitive';\nconst string3 = `Yet another string primitive`;\n
\n
\n

js

\n
const string4 = new String(\"A String object\");\n
\n

String primitives and string objects share many behaviors, but have other important differences and caveats. See \"String primitives and String objects\" below.

String literals can be specified using single or double quotes, which are treated identically, or using the backtick character `. This last form specifies a template literal: with this form you can interpolate expressions. For more information on the syntax of string literals, see lexical grammar.

\n

Character access

\n
\n

There are two ways to access an individual character in a string. The first is the charAt() method:

\n

js

\n
\"cat\".charAt(1); // gives value \"a\"\n
\n

The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:

\n

js

\n
\"cat\"[1]; // gives value \"a\"\n
\n

When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.)

\n

Comparing strings

\n
\n

Use the less-than and greater-than operators to compare strings:

\n

js

\n
const a = \"a\";\nconst b = \"b\";\nif (a < b) {\n  // true\n  console.log(`${a} is less than ${b}`);\n} else if (a > b) {\n  console.log(`${a} is greater than ${b}`);\n} else {\n  console.log(`${a} and ${b} are equal.`);\n}\n
\n

Note that all comparison operators, including === and ==, compare strings case-sensitively. A common way to compare strings case-insensitively is to convert both to the same case (upper or lower) before comparing them.

\n

js

\n
function areEqualCaseInsensitive(str1, str2) {\n  return str1.toUpperCase() === str2.toUpperCase();\n}\n
\n

The choice of whether to transform by toUpperCase() or toLowerCase() is mostly arbitrary, and neither one is fully robust when extending beyond the Latin alphabet. For example, the German lowercase letter ß and ss are both transformed to SS by toUpperCase(), while the Turkish letter ı would be falsely reported as unequal to I by toLowerCase() unless specifically using toLocaleLowerCase(\"tr\").

\n

js

\n
const areEqualInUpperCase = (str1, str2) =>\n  str1.toUpperCase() === str2.toUpperCase();\nconst areEqualInLowerCase = (str1, str2) =>\n  str1.toLowerCase() === str2.toLowerCase();\n\nareEqualInUpperCase(\"ß\", \"ss\"); // true; should be false\nareEqualInLowerCase(\"ı\", \"I\"); // false; should be true\n
\n

A locale-aware and robust solution for testing case-insensitive equality is to use the Intl.Collator API or the string's localeCompare() method — they share the same interface — with the sensitivity option set to \"accent\" or \"base\".

\n

js

\n
const areEqual = (str1, str2, locale = \"en-US\") =>\n  str1.localeCompare(str2, locale, { sensitivity: \"accent\" }) === 0;\n\nareEqual(\"ß\", \"ss\", \"de\"); // false\nareEqual(\"ı\", \"I\", \"tr\"); // true\n
\n

The localeCompare() method enables string comparison in a similar fashion as strcmp() — it allows sorting strings in a locale-aware manner.

\n

String primitives and String objects

\n
\n

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup on the wrapper object instead.

\n

js

\n
const strPrim = \"foo\"; // A literal is a string primitive\nconst strPrim2 = String(1); // Coerced into the string primitive \"1\"\nconst strPrim3 = String(true); // Coerced into the string primitive \"true\"\nconst strObj = new String(strPrim); // String with new returns a string wrapper object.\n\nconsole.log(typeof strPrim); // \"string\"\nconsole.log(typeof strPrim2); // \"string\"\nconsole.log(typeof strPrim3); // \"string\"\nconsole.log(typeof strObj); // \"object\"\n
\n

Warning: You should rarely find yourself using String as a constructor.

String primitives and String objects also give different results when using eval(). Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

\n

js

\n
const s1 = \"2 + 2\"; // creates a string primitive\nconst s2 = new String(\"2 + 2\"); // creates a String object\nconsole.log(eval(s1)); // returns the number 4\nconsole.log(eval(s2)); // returns the string \"2 + 2\"\n
\n

For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.

A String object can always be converted to its primitive counterpart with the valueOf() method.

\n

js

\n
console.log(eval(s2.valueOf())); // returns the number 4\n
\n
\n

String coercion

\n
\n

Many built-in operations that expect strings first coerce their arguments to strings (which is largely why String objects behave similarly to string primitives). The operation can be summarized as follows:

There are several ways to achieve nearly the same effect in JavaScript.

Depending on your use case, you may want to use `${x}` (to mimic built-in behavior) or String(x) (to handle symbol values without throwing an error), but you should not use \"\" + x.

\n

UTF-16 characters, Unicode code points, and grapheme clusters

\n
\n

Strings are represented fundamentally as sequences of UTF-16 code units. In UTF-16 encoding, every code unit is exact 16 bits long. This means there are a maximum of 216, or 65536 possible characters representable as single UTF-16 code units. This character set is called the basic multilingual plane (BMP), and includes the most common characters like the Latin, Greek, Cyrillic alphabets, as well as many East Asian characters. Each code unit can be written in a string with \\u followed by exactly four hex digits.

However, the entire Unicode character set is much, much bigger than 65536. The extra characters are stored in UTF-16 as surrogate pairs, which are pairs of 16-bit code units that represent a single character. To avoid ambiguity, the two parts of the pair must be between 0xD800 and 0xDFFF, and these code units are not used to encode single-code-unit characters. (More precisely, leading surrogates, also called high-surrogate code units, have values between 0xD800 and 0xDBFF, inclusive, while trailing surrogates, also called low-surrogate code units, have values between 0xDC00 and 0xDFFF, inclusive.) Each Unicode character, comprised of one or two UTF-16 code units, is also called a Unicode code point. Each Unicode code point can be written in a string with \\u{xxxxxx} where xxxxxx represents 1–6 hex digits.

A \"lone surrogate\" is a 16-bit code unit satisfying one of the descriptions below:

Lone surrogates do not represent any Unicode character. Although most JavaScript built-in methods handle them correctly because they all work based on UTF-16 code units, lone surrogates are often not valid values when interacting with other systems — for example, encodeURI() will throw a URIError for lone surrogates, because URI encoding uses UTF-8 encoding, which does not have any encoding for lone surrogates. Strings not containing any lone surrogates are called well-formed strings, and are safe to be used with functions that do not deal with UTF-16 (such as encodeURI() or TextEncoder). You can check if a string is well-formed with the isWellFormed() method, or sanitize lone surrogates with the toWellFormed() method.

On top of Unicode characters, there are certain sequences of Unicode characters that should be treated as one visual unit, known as a grapheme cluster. The most common case is emojis: many emojis that have a range of variations are actually formed by multiple emojis, usually joined by the <ZWJ> (U+200D) character.

You must be careful which level of characters you are iterating on. For example, split(\"\") will split by UTF-16 code units and will separate surrogate pairs. String indexes also refer to the index of each UTF-16 code unit. On the other hand, @@iterator() iterates by Unicode code points. Iterating through grapheme clusters will require some custom code.

\n

js

\n
\"😄\".split(\"\"); // ['\\ud83d', '\\ude04']; splits into two lone surrogates\n\n// \"Backhand Index Pointing Right: Dark Skin Tone\"\n[...\"👉🏿\"]; // ['👉', '🏿']\n// splits into the basic \"Backhand Index Pointing Right\" emoji and\n// the \"Dark skin tone\" emoji\n\n// \"Family: Man, Boy\"\n[...\"👨‍👦\"]; // [ '👨', '‍', '👦' ]\n// splits into the \"Man\" and \"Boy\" emoji, joined by a ZWJ\n\n// The United Nations flag\n[...\"🇺🇳\"]; // [ '🇺', '🇳' ]\n// splits into two \"region indicator\" letters \"U\" and \"N\".\n// All flag emojis are formed by joining two region indicator letters\n
\n
\n

Constructor

\n
String()

Creates a new String object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.

Static methods

\n
String.fromCharCode()

Returns a string created by using the specified sequence of Unicode values.

String.fromCodePoint()

Returns a string created by using the specified sequence of code points.

String.raw()

Returns a string created from a raw template string.

Instance properties

\n
\n

These properties are defined on String.prototype and shared by all String instances.

String.prototype.constructor

The constructor function that created the instance object. For String instances, the initial value is the String constructor.

These properties are own properties of each String instance.

length

Reflects the length of the string. Read-only.

\n

Instance methods

\n
String.prototype.at()

Returns the character (exactly one UTF-16 code unit) at the specified index. Accepts negative integers, which count back from the last string character.

String.prototype.charAt()

Returns the character (exactly one UTF-16 code unit) at the specified index.

String.prototype.charCodeAt()

Returns a number that is the UTF-16 code unit value at the given index.

String.prototype.codePointAt()

Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified pos.

String.prototype.concat()

Combines the text of two (or more) strings and returns a new string.

String.prototype.endsWith()

Determines whether a string ends with the characters of the string searchString.

String.prototype.includes()

Determines whether the calling string contains searchString.

String.prototype.indexOf()

Returns the index within the calling String object of the first occurrence of searchValue, or -1 if not found.

String.prototype.isWellFormed()

Returns a boolean indicating whether this string contains any lone surrogates.

String.prototype.lastIndexOf()

Returns the index within the calling String object of the last occurrence of searchValue, or -1 if not found.

String.prototype.localeCompare()

Returns a number indicating whether the reference string compareString comes before, after, or is equivalent to the given string in sort order.

String.prototype.match()

Used to match regular expression regexp against a string.

String.prototype.matchAll()

Returns an iterator of all regexp's matches.

String.prototype.normalize()

Returns the Unicode Normalization Form of the calling string value.

String.prototype.padEnd()

Pads the current string from the end with a given string and returns a new string of the length targetLength.

String.prototype.padStart()

Pads the current string from the start with a given string and returns a new string of the length targetLength.

String.prototype.repeat()

Returns a string consisting of the elements of the object repeated count times.

String.prototype.replace()

Used to replace occurrences of searchFor using replaceWith. searchFor may be a string or Regular Expression, and replaceWith may be a string or function.

String.prototype.replaceAll()

Used to replace all occurrences of searchFor using replaceWith. searchFor may be a string or Regular Expression, and replaceWith may be a string or function.

String.prototype.search()

Search for a match between a regular expression regexp and the calling string.

String.prototype.slice()

Extracts a section of a string and returns a new string.

String.prototype.split()

Returns an array of strings populated by splitting the calling string at occurrences of the substring sep.

String.prototype.startsWith()

Determines whether the calling string begins with the characters of string searchString.

\nString.prototype.substr() Deprecated \n

Returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.

String.prototype.substring()

Returns a new string containing characters of the calling string from (or between) the specified index (or indices).

String.prototype.toLocaleLowerCase()

The characters within a string are converted to lowercase while respecting the current locale.

For most languages, this will return the same as toLowerCase().

String.prototype.toLocaleUpperCase()

The characters within a string are converted to uppercase while respecting the current locale.

For most languages, this will return the same as toUpperCase().

String.prototype.toLowerCase()

Returns the calling string value converted to lowercase.

String.prototype.toString()

Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

String.prototype.toUpperCase()

Returns the calling string value converted to uppercase.

String.prototype.toWellFormed()

Returns a string where all lone surrogates of this string are replaced with the Unicode replacement character U+FFFD.

String.prototype.trim()

Trims whitespace from the beginning and end of the string.

String.prototype.trimEnd()

Trims whitespace from the end of the string.

String.prototype.trimStart()

Trims whitespace from the beginning of the string.

String.prototype.valueOf()

Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.

String.prototype[@@iterator]()

Returns a new iterator object that iterates over the code points of a String value, returning each code point as a String value.

HTML wrapper methods

\n
\n

Warning: Deprecated. Avoid these methods.

They are of limited use, as they are based on a very old HTML standard and provide only a subset of the currently available HTML tags and attributes. Many of them create deprecated or non-standard markup today. In addition, they do simple string concatenation without any validation or sanitation, which makes them a potential security threat when directly inserted using innerHTML. Use DOM APIs such as document.createElement() instead.

\nString.prototype.anchor() Deprecated \n

<a name=\"name\"> (hypertext target)

\nString.prototype.big() Deprecated \n
<big>
\nString.prototype.blink() Deprecated \n

<blink>

\nString.prototype.bold() Deprecated \n
<b>
\nString.prototype.fixed() Deprecated \n
<tt>
\nString.prototype.fontcolor() Deprecated \n

<font color=\"color\">

\nString.prototype.fontsize() Deprecated \n

<font size=\"size\">

\nString.prototype.italics() Deprecated \n
<i>
\nString.prototype.link() Deprecated \n

<a href=\"url\"> (link to URL)

\nString.prototype.small() Deprecated \n
<small>
\nString.prototype.strike() Deprecated \n
<strike>
\nString.prototype.sub() Deprecated \n
<sub>
\nString.prototype.sup() Deprecated \n
<sup>

Note that these methods do not check if the string itself contains HTML tags, so it's possible to create invalid HTML:

\n

js

\n
\"</b>\".bold(); // <b></b></b>\n
\n

The only escaping they do is to replace \" in the attribute value (for anchor(), fontcolor(), fontsize(), and link()) with &quot;.

\n

js

\n
\"foo\".anchor('\"Hello\"'); // <a name=\"&quot;Hello&quot;\">foo</a>\n
\n
\n

Examples

\n

String conversion

\n
\n

The String() function is a more reliable way of converting values to strings than calling the toString() method of the value, as the former works when used on null and undefined. For example:

\n

js

\n
// You cannot access properties on null or undefined\n\nconst nullVar = null;\nnullVar.toString(); // TypeError: Cannot read properties of null\nString(nullVar); // \"null\"\n\nconst undefinedVar = undefined;\nundefinedVar.toString(); // TypeError: Cannot read properties of undefined\nString(undefinedVar); // \"undefined\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No259383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
2593.01.00.12.0
String11213314.418410.111.01.00.10.0
String11213314.418410.111.01.00.10.0
anchor112
1Starting with version 17, the quotation mark (\") is replaced by its HTML reference character (\") in strings supplied for the name parameter.
No314.418410.111.01.00.10.0
at929290No7815.49292906515.416.01.1216.6.0
big11213314.418410.111.01.00.10.0
blink11213314.418410.111.01.00.10.0
bold11213314.418410.111.01.00.10.0
charAt11213314.418410.111.01.00.10.0
charCodeAt11214414.418410.111.01.00.10.0
codePointAt411229No2894141292894.01.04.0.0
concat11214414.418410.111.01.00.10.0
endsWith411217No2893736172493.01.04.0.0
fixed11213314.418410.111.01.00.10.0
fontcolor11213314.418410.111.01.00.10.0
fontsize11213314.418410.111.01.00.10.0
fromCharCode11214414.418410.111.01.00.10.0
fromCodePoint411229No2894141292894.01.04.0.0
includes41124018–48No28941414018–482894.01.04.0.0
indexOf11213314.418410.111.01.00.10.0
isWellFormed111111119No9716.4111111119No16.422.01.3220.0.0
italics11213314.418410.111.01.00.10.0
lastIndexOf11216314.418410.111.01.00.10.0
length11213314.418410.111.01.00.10.0
link11213314.418410.111.01.00.10.0
localeCompare11215.5734.418410.111.01.00.10.0
match11214414.418410.111.01.00.10.0
matchAll737967No6013737367521311.01.012.0.0
normalize341231No211037343121102.01.00.12.0
padEnd571548No441057574843107.01.08.0.0
padStart571548No441057574843107.01.08.0.0
raw411234No2894141342894.01.04.0.0
repeat411224No2894136242893.01.04.0.0
replace11215.5
4–5.5A replacement function as second argument is not supported.
\n
414.418410.111.01.00.10.0
replaceAll858577No7113.18585796013.414.01.215.0.0
search11214414.418410.111.01.00.10.0
slice11214414.418410.111.01.00.10.0
small11213314.418410.111.01.00.10.0
split11214314.418410.111.01.00.10.0
startsWith411217No2893736172493.01.04.0.0
strike11213314.418410.111.01.00.10.0
sub11213314.418410.111.01.00.10.0
substr11214414.418410.111.01.00.10.0
substring11213314.418410.111.01.00.10.0
sup11213314.418410.111.01.00.10.0
toLocaleLowerCase11215.541.34.418410.111.01.00.10.0
toLocaleUpperCase11215.541.34.418410.111.01.00.10.0
toLowerCase11213314.418410.111.01.00.10.0
toString11213314.418410.111.01.00.10.0
toUpperCase11213314.418410.111.01.00.10.0
toWellFormed111111119No9716.4111111119No16.422.01.3220.0.0
trim4123.51010.55≤371841151.01.00.10.0
trimEnd6647912613.5No53151266≤3766186144714129.01.01.01.010.0.00.12.0
trimStart6647912613.5No53151266≤3766186144714129.01.01.01.010.0.00.12.0
unicode_code_point_escapes112404414.4184010.111.01.00.10.0
valueOf11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\n

\n
\n", + "global_objects/regexp": "

RegExp

\n

The RegExp object is used for matching text with a pattern.

For an introduction to regular expressions, read the Regular expressions chapter in the JavaScript guide. For detailed information of regular expression syntax, read the regular expression reference.

\n
\n

Description

\n

Literal notation and constructor

\n
\n

There are two ways to create a RegExp object: a literal notation and a constructor.

The following three expressions create the same regular expression object:

\n

js

\n
const re = /ab+c/i; // literal notation\n// OR\nconst re = new RegExp(\"ab+c\", \"i\"); // constructor with string pattern as first argument\n// OR\nconst re = new RegExp(/ab+c/, \"i\"); // constructor with regular expression literal as first argument\n
\n

Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. More about the process can be found in dotnet docs.

The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the RegExp object, new RegExp('ab+c'), results in runtime compilation of the regular expression.

Use a string as the first argument to the RegExp() constructor when you want to build the regular expression from dynamic input.

\n

Flags in constructor

\n
\n

The expression new RegExp(/ab+c/, flags) will create a new RegExp using the source of the first parameter and the flags provided by the second.

When using the constructor function, the normal string escape rules (preceding special characters with \\ when included in a string) are necessary.

For example, the following are equivalent:

\n

js

\n
const re = /\\w+/;\n// OR\nconst re = new RegExp(\"\\\\w+\");\n
\n
\n

Special handling for regexes

\n
\n

Note: Whether something is a \"regex\" can be duck-typed. It doesn't have to be a RegExp!

Some built-in methods would treat regexes specially. They decide whether x is a regex through multiple steps:

  1. \nx must be an object (not a primitive).
  2. If x[Symbol.match] is not undefined, check if it's truthy.
  3. Otherwise, if x[Symbol.match] is undefined, check if x had been created with the RegExp constructor. (This step should rarely happen, since if x is a RegExp object that have not been tampered with, it should have a Symbol.match property.)

Note that in most cases, it would go through the Symbol.match check, which means:

This choice was made because @@match is the most indicative property that something is intended to be used for matching. (exec could also be used, but because it's not a symbol property, there would be too many false positives.) The places that treat regexes specially include:

For example, String.prototype.endsWith() would coerce all inputs to strings, but it would throw if the argument is a regex, because it's only designed to match strings, and using a regex is likely a developer mistake.

\n

js

\n
\"foobar\".endsWith({ toString: () => \"bar\" }); // true\n\"foobar\".endsWith(/bar/); // TypeError: First argument to String.prototype.endsWith must not be a regular expression\n
\n

You can get around the check by setting @@match to a falsy value that's not undefined. This would mean that the regex cannot be used for String.prototype.match() (since without @@match, match() would construct a new RegExp object with the two enclosing slashes added by re.toString()), but it can be used for virtually everything else.

\n

js

\n
const re = /bar/g;\nre[Symbol.match] = false;\n\"/bar/g\".endsWith(re); // true\nre.exec(\"bar\"); // [ 'bar', index: 0, input: 'bar', groups: undefined ]\n\"bar & bar\".replace(re, \"foo\"); // 'foo & foo'\n
\n
\n

Perl-like RegExp properties

\n

Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. (Perl is the programming language from which JavaScript modeled its regular expressions.) See also deprecated RegExp properties.

Constructor

\n
RegExp()

Creates a new RegExp object.

Static properties

\n
\nRegExp.$1, …, RegExp.$9 Deprecated \n

Static read-only properties that contain parenthesized substring matches.

\nRegExp.input ($_) Deprecated \n

A static property that contains the last string against which a regular expression was successfully matched.

\nRegExp.lastMatch ($&) Deprecated \n

A static read-only property that contains the last matched substring.

\nRegExp.lastParen ($+) Deprecated \n

A static read-only property that contains the last parenthesized substring match.

\nRegExp.leftContext ($`) Deprecated \n

A static read-only property that contains the substring preceding the most recent match.

\nRegExp.rightContext ($') Deprecated \n

A static read-only property that contains the substring following the most recent match.

RegExp[@@species]

The constructor function that is used to create derived objects.

Instance properties

\n
\n

These properties are defined on RegExp.prototype and shared by all RegExp instances.

RegExp.prototype.constructor

The constructor function that created the instance object. For RegExp instances, the initial value is the RegExp constructor.

RegExp.prototype.dotAll

Whether . matches newlines or not.

RegExp.prototype.flags

A string that contains the flags of the RegExp object.

RegExp.prototype.global

Whether to test the regular expression against all possible matches in a string, or only against the first.

RegExp.prototype.hasIndices

Whether the regular expression result exposes the start and end indices of captured substrings.

RegExp.prototype.ignoreCase

Whether to ignore case while attempting a match in a string.

RegExp.prototype.multiline

Whether or not to search in strings across multiple lines.

RegExp.prototype.source

The text of the pattern.

RegExp.prototype.sticky

Whether or not the search is sticky.

RegExp.prototype.unicode

Whether or not Unicode features are enabled.

RegExp.prototype.unicodeSets

Whether or not the v flag, an upgrade to the u mode, is enabled.

These properties are own properties of each RegExp instance.

lastIndex

The index at which to start the next match.

\n

Instance methods

\n
\nRegExp.prototype.compile() Deprecated \n

(Re-)compiles a regular expression during execution of a script.

RegExp.prototype.exec()

Executes a search for a match in its string parameter.

RegExp.prototype.test()

Tests for a match in its string parameter.

RegExp.prototype.toString()

Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

RegExp.prototype[@@match]()

Performs match to given string and returns match result.

RegExp.prototype[@@matchAll]()

Returns all matches of the regular expression against a string.

RegExp.prototype[@@replace]()

Replaces matches in given string with new substring.

RegExp.prototype[@@search]()

Searches the match in given string and returns the index the pattern found in the string.

RegExp.prototype[@@split]()

Splits given string into an array by separating the string into substrings.

Examples

\n

Using a regular expression to change data format

\n
\n

The following script uses the String.prototype.replace() method to match a name in the format first last and output it in the format last, first.

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

\n

js

\n
const re = /(\\w+)\\s(\\w+)/;\nconst str = \"Maria Cruz\";\nconst newstr = str.replace(re, \"$2, $1\");\nconsole.log(newstr);\n
\n

This displays \"Cruz, Maria\".

\n

Using regular expression to split lines with different line endings/ends of line/line breaks

\n
\n

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

\n

js

\n
const text = \"Some text\\nAnd some more\\r\\nAnd yet\\rThis is the end\";\nconst lines = text.split(/\\r\\n|\\r|\\n/);\nconsole.log(lines); // [ 'Some text', 'And some more', 'And yet', 'This is the end' ]\n
\n

Note that the order of the patterns in the regular expression matters.

\n

Using regular expression on multiple lines

\n
\n

js

\n
const s = \"Please yes\\nmake my day!\";\n\ns.match(/yes.*day/);\n// Returns null\n\ns.match(/yes[^]*day/);\n// Returns [\"yes\\nmake my day\"]\n
\n

Using a regular expression with the sticky flag

\n
\n

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

\n

js

\n
const str = \"#foo#\";\nconst regex = /foo/y;\n\nregex.lastIndex = 1;\nregex.test(str); // true\nregex.lastIndex = 5;\nregex.test(str); // false (lastIndex is taken into account with sticky flag)\nregex.lastIndex; // 0 (reset after match failure)\n
\n
\n

The difference between the sticky flag and the global flag

\n
\n

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

\n

js

\n
const re = /\\d/y;\nlet r;\nwhile ((r = re.exec(\"123 456\"))) {\n  console.log(r, \"AND re.lastIndex\", re.lastIndex);\n}\n\n// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1\n// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2\n// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3\n//  … and no more match.\n
\n

With the global flag g, all 6 digits would be matched, not just 3.

\n

Regular expression and Unicode characters

\n
\n

\\w and \\W only matches ASCII based characters; for example, a to z, A to Z, 0 to 9, and _.

To match characters from other languages such as Cyrillic or Hebrew, use \\uhhhh, where hhhh is the character's Unicode value in hexadecimal.

This example demonstrates how one can separate out Unicode characters from a word.

\n

js

\n
const text = \"Образец text на русском языке\";\nconst regex = /[\\u0400-\\u04FF]+/g;\n\nconst match = regex.exec(text);\nconsole.log(match[0]); // 'Образец'\nconsole.log(regex.lastIndex); // 7\n\nconst match2 = regex.exec(text);\nconsole.log(match2[0]); // 'на' (did not log 'text')\nconsole.log(regex.lastIndex); // 15\n\n// and so on\n
\n

The Unicode property escapes feature provides a simpler way to target particular Unicode ranges, by allowing for statements like \\p{scx=Cyrl} (to match any Cyrillic letter), or \\p{L}/u (to match a letter from any language).

\n

Extracting subdomain name from URL

\n
\n
\n

js

\n
const url = \"http://xxx.domain.com\";\nconsole.log(/^https?:\\/\\/(.+?)\\./.exec(url)[1]); // 'xxx'\n
\n

Note: Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

\n

Building a regular expression from dynamic inputs

\n
\n

js

\n
const breakfasts = [\"bacon\", \"eggs\", \"oatmeal\", \"toast\", \"cereal\"];\nconst order = \"Let me get some bacon and eggs, please\";\n\norder.match(new RegExp(`\\\\b(${breakfasts.join(\"|\")})\\\\b`, \"g\"));\n// Returns ['bacon', 'eggs']\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp-regular-expression-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@match501349No371050504937105.01.06.0.0
@@matchAll737967No601373736752135.01.012.0.0
@@replace507949No371050504937105.01.06.0.0
@@search501349No371050504937105.01.06.0.0
@@species501349No371050504937105.01.06.5.0
@@split507949No371050504937105.01.06.0.0
RegExp11214514.418410.111.01.00.10.0
RegExp11214514.418410.111.01.00.10.0
compile1121463.14.418410.121.01.00.10.0
dotAll627978No4911.16262794611.38.01.08.10.0
exec11214514.418410.111.01.00.10.0
flags497937No3994949374195.01.06.0.0
global11215.5514.418410.111.01.00.10.0
hasIndices909088No7615909088641515.01.816.0.0
ignoreCase11215.5514.418410.111.01.00.10.0
input11215.51534.41841411.01.00.10.0
lastIndex11215.5514.418410.111.01.00.10.0
lastMatch11215.510.534.41841111.01.00.10.0
lastParen11215.510.534.41841111.01.00.10.0
leftContext11215.5834.418410.111.01.00.10.0
multiline11215.5514.418410.111.01.00.10.0
n11214514.418410.111.01.00.10.0
rightContext11215.5834.418410.111.01.00.10.0
source11214514.418410.111.01.00.10.0
sticky49133No36104949436105.01.06.0.0
test11214514.418410.111.01.00.10.0
toString11214514.418410.111.01.00.10.0
unicode50
12Case folding is implemented in version 13
46No371050504637105.01.0
6.0.0Case folding is implemented in version 8.6.0
unicodeSets112112116No9817112112116No17No1.3220.0.0
\n

Firefox-specific notes

\n
\n

Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now undefined instead of an empty string:

\n

js

\n
// Firefox 33 or older\n\"x\".replace(/x(.)?/g, (m, group) => {\n  console.log(`group: ${JSON.stringify(group)}`);\n});\n// group: \"\"\n\n// Firefox 34 or newer\n\"x\".replace(/x(.)?/g, (m, group) => {\n  console.log(`group: ${group}`);\n});\n// group: undefined\n
\n

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined (bug 1053944).

\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\n

\n
\n", + "global_objects/int8array": "

Int8Array

\n

The Int8Array typed array represents an array of 8-bit signed integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Int8Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Int8Array()

Creates a new Int8Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Int8Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of Int8Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Int8Array.prototype and shared by all Int8Array instances.

Int8Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of a Int8Array.

Int8Array.prototype.constructor

The constructor function that created the instance object. For Int8Array instances, the initial value is the Int8Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create an Int8Array

\n
\n

js

\n
// From a length\nconst int8 = new Int8Array(2);\nint8[0] = 42;\nconsole.log(int8[0]); // 42\nconsole.log(int8.length); // 2\nconsole.log(int8.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Int8Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int8Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Int8Array(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int8FromIterable = new Int8Array(iterable);\nconsole.log(int8FromIterable);\n// Int8Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int8Array71241011.65.14184124.21.01.00.10.0
Int8Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array\n

\n
\n", + "global_objects/uint8array": "

Uint8Array

\n

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Uint8Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Uint8Array()

Creates a new Uint8Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Uint8Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of Uint8Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Uint8Array.prototype and shared by all Uint8Array instances.

Uint8Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of a Uint8Array.

Uint8Array.prototype.constructor

The constructor function that created the instance object. For Uint8Array instances, the initial value is the Uint8Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Uint8Array

\n
\n

js

\n
// From a length\nconst uint8 = new Uint8Array(2);\nuint8[0] = 42;\nconsole.log(uint8[0]); // 42\nconsole.log(uint8.length); // 2\nconsole.log(uint8.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Uint8Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint8Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Uint8Array(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint8FromIterable = new Uint8Array(iterable);\nconsole.log(uint8FromIterable);\n// Uint8Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint8Array71241011.65.14184124.21.01.00.10.0
Uint8Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array\n

\n
\n", + "global_objects/uint8clampedarray": "

Uint8ClampedArray

\n

The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0–255. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Uint8ClampedArray is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Uint8ClampedArray()

Creates a new Uint8ClampedArray object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Uint8ClampedArray.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of Uint8ClampedArray.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Uint8ClampedArray.prototype and shared by all Uint8ClampedArray instances.

Uint8ClampedArray.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 1 in the case of a Uint8ClampedArray.

Uint8ClampedArray.prototype.constructor

The constructor function that created the instance object. For Uint8ClampedArray instances, the initial value is the Uint8ClampedArray constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Uint8ClampedArray

\n
\n

js

\n
// From a length\nconst uint8c = new Uint8ClampedArray(2);\nuint8c[0] = 42;\nuint8c[1] = 1337;\nconsole.log(uint8c[0]); // 42\nconsole.log(uint8c[1]); // 255 (clamped)\nconsole.log(uint8c.length); // 2\nconsole.log(uint8c.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Uint8ClampedArray([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint8ClampedArray(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Uint8ClampedArray(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint8cFromIterable = new Uint8ClampedArray(iterable);\nconsole.log(uint8cFromIterable);\n// Uint8ClampedArray [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint8ClampedArray71241011.65.14184124.21.01.00.10.0
Uint8ClampedArray71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray\n

\n
\n", + "global_objects/int16array": "

Int16Array

\n

The Int16Array typed array represents an array of 16-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Int16Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Int16Array()

Creates a new Int16Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Int16Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 2 in the case of Int16Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Int16Array.prototype and shared by all Int16Array instances.

Int16Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 2 in the case of a Int16Array.

Int16Array.prototype.constructor

The constructor function that created the instance object. For Int16Array instances, the initial value is the Int16Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create an Int16Array

\n
\n

js

\n
// From a length\nconst int16 = new Int16Array(2);\nint16[0] = 42;\nconsole.log(int16[0]); // 42\nconsole.log(int16.length); // 2\nconsole.log(int16.BYTES_PER_ELEMENT); // 2\n\n// From an array\nconst x = new Int16Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int16Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(16);\nconst z = new Int16Array(buffer, 2, 4);\nconsole.log(z.byteOffset); // 2\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int16FromIterable = new Int16Array(iterable);\nconsole.log(int16FromIterable);\n// Int16Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int16Array71241011.65.14184124.21.01.00.10.0
Int16Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array\n

\n
\n", + "global_objects/uint16array": "

Uint16Array

\n

The Uint16Array typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Uint16Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Uint16Array()

Creates a new Uint16Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Uint16Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 2 in the case of Uint16Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Uint16Array.prototype and shared by all Uint16Array instances.

Uint16Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 2 in the case of a Uint16Array.

Uint16Array.prototype.constructor

The constructor function that created the instance object. For Uint16Array instances, the initial value is the Uint16Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Uint16Array

\n
\n

js

\n
// From a length\nconst uint16 = new Uint16Array(2);\nuint16[0] = 42;\nconsole.log(uint16[0]); // 42\nconsole.log(uint16.length); // 2\nconsole.log(uint16.BYTES_PER_ELEMENT); // 2\n\n// From an array\nconst x = new Uint16Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint16Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(16);\nconst z = new Uint16Array(buffer, 2, 4);\nconsole.log(z.byteOffset); // 2\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint16FromIterable = new Uint16Array(iterable);\nconsole.log(uint16FromIterable);\n// Uint16Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint16Array71241011.65.14184124.21.01.00.10.0
Uint16Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array\n

\n
\n", + "global_objects/int32array": "

Int32Array

\n

The Int32Array typed array represents an array of 32-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Int32Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Int32Array()

Creates a new Int32Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Int32Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of Int32Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Int32Array.prototype and shared by all Int32Array instances.

Int32Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of a Int32Array.

Int32Array.prototype.constructor

The constructor function that created the instance object. For Int32Array instances, the initial value is the Int32Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create an Int32Array

\n
\n

js

\n
// From a length\nconst int32 = new Int32Array(2);\nint32[0] = 42;\nconsole.log(int32[0]); // 42\nconsole.log(int32.length); // 2\nconsole.log(int32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Int32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Int32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int32FromIterable = new Int32Array(iterable);\nconsole.log(int32FromIterable);\n// Int32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int32Array71241011.65.14184124.21.01.00.10.0
Int32Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array\n

\n
\n", + "global_objects/urierror": "

URIError

\n

The URIError object represents an error when a global URI handling function was used in a wrong way.

URIError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

URIError is a subclass of Error.

\n
\n

Constructor

\n
URIError()

Creates a new URIError object.

Instance properties

\n
\n

Also inherits instance properties from its parent Error.

These properties are defined on URIError.prototype and shared by all URIError instances.

URIError.prototype.constructor

The constructor function that created the instance object. For URIError instances, the initial value is the URIError constructor.

URIError.prototype.name

Represents the name for the type of error. For URIError.prototype.name, the initial value is \"URIError\".

\n

Instance methods

\n

Inherits instance methods from its parent Error.

Examples

\n

Catching an URIError

\n
\n

js

\n
try {\n  decodeURIComponent(\"%\");\n} catch (e) {\n  console.log(e instanceof URIError); // true\n  console.log(e.message); // \"malformed URI sequence\"\n  console.log(e.name); // \"URIError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating an URIError

\n
\n

js

\n
try {\n  throw new URIError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof URIError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"URIError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-urierror
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
URIError11215.5514.418410.111.01.00.10.0
URIError11215.5514.418410.111.01.00.10.0
serializable_object7779
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
No64No7777
103[\"Version 103 serializable properties: name, message, cause, fileName, lineNumber and columnNumber.\", \"Version 104 also serializes stack in the main thread (window.postMessage() and structuredClone()).\", \"Version 110 also serializes stack in workers (worker.postMessage() and structuredClone()).\"]
55No12.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError\n

\n
\n", + "global_objects/array": "

Array

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.

\n

Description

\n
\n

In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics:

\n

Array indices

\n
\n

Array objects cannot use arbitrary strings as element indexes (as in an associative array) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

Array elements are object properties in the same way that toString is a property (to be specific, however, toString() is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:

\n

js

\n
arr.0; // a syntax error\n
\n

JavaScript syntax requires properties beginning with a digit to be accessed using bracket notation instead of dot notation. It's also possible to quote the array indices (e.g., years['2'] instead of years[2]), although usually not necessary.

The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true:

\n

js

\n
console.log(years[\"2\"] !== years[\"02\"]);\n
\n

Only years['2'] is an actual array index. years['02'] is an arbitrary string property that will not be visited in array iteration.

\n

Relationship between length and numerical properties

\n
\n

A JavaScript array's length property and numerical properties are connected.

Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into account the value of an array's length property when they're called.

Other methods (e.g., push(), splice(), etc.) also result in updates to an array's length property.

\n

js

\n
const fruits = [];\nfruits.push(\"banana\", \"apple\", \"peach\");\nconsole.log(fruits.length); // 3\n
\n

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly:

\n

js

\n
fruits[5] = \"mango\";\nconsole.log(fruits[5]); // 'mango'\nconsole.log(Object.keys(fruits)); // ['0', '1', '2', '5']\nconsole.log(fruits.length); // 6\n
\n

Increasing the length extends the array by adding empty slots without creating any new elements — not even undefined.

\n

js

\n
fruits.length = 10;\nconsole.log(fruits); // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4]\nconsole.log(Object.keys(fruits)); // ['0', '1', '2', '5']\nconsole.log(fruits.length); // 10\nconsole.log(fruits[8]); // undefined\n
\n

Decreasing the length property does, however, delete elements.

\n

js

\n
fruits.length = 2;\nconsole.log(Object.keys(fruits)); // ['0', '1']\nconsole.log(fruits.length); // 2\n
\n

This is explained further on the length page.

\n

Array methods and empty slots

\n
\n

Empty slots in sparse arrays behave inconsistently between array methods. Generally, the older methods will skip empty slots, while newer ones treat them as undefined.

Among methods that iterate through multiple elements, the following do an in check before accessing the index and do not conflate empty slots with undefined:

For exactly how they treat empty slots, see the page for each method.

These methods treat empty slots as if they are undefined:

\n

Copying methods and mutating methods

\n
\n

Some methods do not mutate the existing array that the method was called on, but instead return a new array. They do so by first constructing a new array and then populating it with elements. The copy always happens shallowly — the method never copies anything beyond the initially created array. Elements of the original array(s) are copied into the new array as follows:

Other methods mutate the array that the method was called on, in which case their return value differs depending on the method: sometimes a reference to the same array, sometimes the length of the new array.

The following methods create new arrays by accessing this.constructor[Symbol.species] to determine the constructor to use:

The following methods always create new arrays with the Array base constructor:

The following table lists the methods that mutate the original array, and the corresponding non-mutating alternative:

An easy way to change a mutating method into a non-mutating alternative is to use the spread syntax or slice() to create a copy first:

\n

js

\n
arr.copyWithin(0, 1, 2); // mutates arr\nconst arr2 = arr.slice().copyWithin(0, 1, 2); // does not mutate arr\nconst arr3 = [...arr].copyWithin(0, 1, 2); // does not mutate arr\n
\n
\n

Iterative methods

\n
\n

Many array methods take a callback function as an argument. The callback function is called sequentially and at most once for each element in the array, and the return value of the callback function is used to determine the return value of the method. They all share the same signature:

\n

js

\n
method(callbackFn, thisArg)\n
\n

Where callbackFn takes three arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array that the method was called upon.

What callbackFn is expected to return depends on the array method that was called.

The thisArg argument (defaults to undefined) will be used as the this value when calling callbackFn. The this value ultimately observable by callbackFn is determined according to the usual rules: if callbackFn is non-strict, primitive this values are wrapped into objects, and undefined/null is substituted with globalThis. The thisArg argument is irrelevant for any callbackFn defined with an arrow function, as arrow functions don't have their own this binding.

All iterative methods are copying and generic, although they behave differently with empty slots.

The following methods are iterative:

In particular, every(), find(), findIndex(), findLast(), findLastIndex(), and some() do not always invoke callbackFn on every element — they stop iteration as soon as the return value is determined.

There are two other methods that take a callback function and run it at most once for each element in the array, but they have slightly different signatures from typical iterative methods (for example, they don't accept thisArg):

The sort() method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't accept thisArg, and may invoke the callback multiple times on an index.

\n

Generic array methods

\n
\n

Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the length property and the indexed elements. This means that they can be called on array-like objects as well.

\n

js

\n
const arrayLike = {\n  0: \"a\",\n  1: \"b\",\n  length: 2,\n};\nconsole.log(Array.prototype.join.call(arrayLike, \"+\")); // 'a+b'\n
\n

Normalization of the length property

The length property is converted to an integer and then clamped to the range between 0 and 253 - 1. NaN becomes 0, so even when length is not present or is undefined, it behaves as if it has value 0.

The language avoids setting length to an unsafe integer. All built-in methods will throw a TypeError if length will be set to a number greater than 253 - 1. However, because the length property of arrays throws an error if it's set to greater than 232 - 1, the safe integer threshold is usually not reached unless the method is called on a non-array object.

\n

js

\n
Array.prototype.flat.call({}); // []\n
\n

Some array methods set the length property of the array object. They always set the value after normalization, so length always ends as an integer.

\n

js

\n
const a = { length: 0.7 };\nArray.prototype.push.call(a);\nconsole.log(a.length); // 0\n
\n

Array-like objects

The term array-like object refers to any object that doesn't throw during the length conversion process described above. In practice, such object is expected to actually have a length property and to have indexed elements in the range 0 to length - 1. (If it doesn't have all indices, it will be functionally equivalent to a sparse array.) Any integer index less than zero or greater than length - 1 is ignored when an array method operates on an array-like object.

Many DOM objects are array-like — for example, NodeList and HTMLCollection. The arguments object is also array-like. You can call array methods on them even if they don't have these methods themselves.

\n

js

\n
function f() {\n  console.log(Array.prototype.join.call(arguments, \"+\"));\n}\n\nf(\"a\", \"b\"); // 'a+b'\n
\n
\n

Constructor

\n
Array()

Creates a new Array object.

Static properties

\n
Array[@@species]

Returns the Array constructor.

Static methods

\n
Array.from()

Creates a new Array instance from an iterable or array-like object.

Array.fromAsync()

Creates a new Array instance from an async iterable, iterable, or array-like object.

Array.isArray()

Returns true if the argument is an array, or false otherwise.

Array.of()

Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.

Instance properties

\n
\n

These properties are defined on Array.prototype and shared by all Array instances.

Array.prototype.constructor

The constructor function that created the instance object. For Array instances, the initial value is the Array constructor.

Array.prototype[@@unscopables]

Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with statement-binding purposes.

These properties are own properties of each Array instance.

length

Reflects the number of elements in an array.

\n

Instance methods

\n
Array.prototype.at()

Returns the array item at the given index. Accepts negative integers, which count back from the last item.

Array.prototype.concat()

Returns a new array that is the calling array joined with other array(s) and/or value(s).

Array.prototype.copyWithin()

Copies a sequence of array elements within an array.

Array.prototype.entries()

Returns a new array iterator object that contains the key/value pairs for each index in an array.

Array.prototype.every()

Returns true if every element in the calling array satisfies the testing function.

Array.prototype.fill()

Fills all the elements of an array from a start index to an end index with a static value.

Array.prototype.filter()

Returns a new array containing all elements of the calling array for which the provided filtering function returns true.

Array.prototype.find()

Returns the value of the first element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

Array.prototype.findIndex()

Returns the index of the first element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

Array.prototype.findLast()

Returns the value of the last element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

Array.prototype.findLastIndex()

Returns the index of the last element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

Array.prototype.flat()

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Array.prototype.flatMap()

Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.

Array.prototype.forEach()

Calls a function for each element in the calling array.

Array.prototype.includes()

Determines whether the calling array contains a value, returning true or false as appropriate.

Array.prototype.indexOf()

Returns the first (least) index at which a given element can be found in the calling array.

Array.prototype.join()

Joins all elements of an array into a string.

Array.prototype.keys()

Returns a new array iterator that contains the keys for each index in the calling array.

Array.prototype.lastIndexOf()

Returns the last (greatest) index at which a given element can be found in the calling array, or -1 if none is found.

Array.prototype.map()

Returns a new array containing the results of invoking a function on every element in the calling array.

Array.prototype.pop()

Removes the last element from an array and returns that element.

Array.prototype.push()

Adds one or more elements to the end of an array, and returns the new length of the array.

Array.prototype.reduce()

Executes a user-supplied \"reducer\" callback function on each element of the array (from left to right), to reduce it to a single value.

Array.prototype.reduceRight()

Executes a user-supplied \"reducer\" callback function on each element of the array (from right to left), to reduce it to a single value.

Array.prototype.reverse()

Reverses the order of the elements of an array in place. (First becomes the last, last becomes first.)

Array.prototype.shift()

Removes the first element from an array and returns that element.

Array.prototype.slice()

Extracts a section of the calling array and returns a new array.

Array.prototype.some()

Returns true if at least one element in the calling array satisfies the provided testing function.

Array.prototype.sort()

Sorts the elements of an array in place and returns the array.

Array.prototype.splice()

Adds and/or removes elements from an array.

Array.prototype.toLocaleString()

Returns a localized string representing the calling array and its elements. Overrides the Object.prototype.toLocaleString() method.

Array.prototype.toReversed()

Returns a new array with the elements in reversed order, without modifying the original array.

Array.prototype.toSorted()

Returns a new array with the elements sorted in ascending order, without modifying the original array.

Array.prototype.toSpliced()

Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.

Array.prototype.toString()

Returns a string representing the calling array and its elements. Overrides the Object.prototype.toString() method.

Array.prototype.unshift()

Adds one or more elements to the front of an array, and returns the new length of the array.

Array.prototype.values()

Returns a new array iterator object that contains the values for each index in the array.

Array.prototype.with()

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

Array.prototype[@@iterator]()

An alias for the values() method by default.

Examples

\n
\n

This section provides some examples of common array operations in JavaScript.

Note: If you're not yet familiar with array basics, consider first reading JavaScript First Steps: Arrays, which explains what arrays are, and includes other examples of common array operations.

\n

Create an array

\n
\n

This example shows three ways to create new array: first using array literal notation, then using the Array() constructor, and finally using String.prototype.split() to build the array from a string.

\n

js

\n
// 'fruits' array created using array literal notation.\nconst fruits = [\"Apple\", \"Banana\"];\nconsole.log(fruits.length);\n// 2\n\n// 'fruits2' array created using the Array() constructor.\nconst fruits2 = new Array(\"Apple\", \"Banana\");\nconsole.log(fruits2.length);\n// 2\n\n// 'fruits3' array created using String.prototype.split().\nconst fruits3 = \"Apple, Banana\".split(\", \");\nconsole.log(fruits3.length);\n// 2\n
\n
\n

Create a string from an array

\n
\n

This example uses the join() method to create a string from the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\nconst fruitsString = fruits.join(\", \");\nconsole.log(fruitsString);\n// \"Apple, Banana\"\n
\n
\n

Access an array item by its index

\n
\n

This example shows how to access items in the fruits array by specifying the index number of their position in the array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\n\n// The index of an array's first element is always 0.\nfruits[0]; // Apple\n\n// The index of an array's second element is always 1.\nfruits[1]; // Banana\n\n// The index of an array's last element is always one\n// less than the length of the array.\nfruits[fruits.length - 1]; // Banana\n\n// Using an index number larger than the array's length\n// returns 'undefined'.\nfruits[99]; // undefined\n
\n
\n

Find the index of an item in an array

\n
\n

This example uses the indexOf() method to find the position (index) of the string \"Banana\" in the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\nconsole.log(fruits.indexOf(\"Banana\"));\n// 1\n
\n
\n

Check if an array contains a certain item

\n
\n

This example shows two ways to check if the fruits array contains \"Banana\" and \"Cherry\": first with the includes() method, and then with the indexOf() method to test for an index value that's not -1.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\n\nfruits.includes(\"Banana\"); // true\nfruits.includes(\"Cherry\"); // false\n\n// If indexOf() doesn't return -1, the array contains the given item.\nfruits.indexOf(\"Banana\") !== -1; // true\nfruits.indexOf(\"Cherry\") !== -1; // false\n
\n
\n

Append an item to an array

\n
\n

This example uses the push() method to append a new string to the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\nconst newLength = fruits.push(\"Orange\");\nconsole.log(fruits);\n// [\"Apple\", \"Banana\", \"Orange\"]\nconsole.log(newLength);\n// 3\n
\n
\n

Remove the last item from an array

\n
\n

This example uses the pop() method to remove the last item from the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Orange\"];\nconst removedItem = fruits.pop();\nconsole.log(fruits);\n// [\"Apple\", \"Banana\"]\nconsole.log(removedItem);\n// Orange\n
\n

Note: pop() can only be used to remove the last item from an array. To remove multiple items from the end of an array, see the next example.

\n

Remove multiple items from the end of an array

\n
\n

This example uses the splice() method to remove the last 3 items from the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Strawberry\", \"Mango\", \"Cherry\"];\nconst start = -3;\nconst removedItems = fruits.splice(start);\nconsole.log(fruits);\n// [\"Apple\", \"Banana\"]\nconsole.log(removedItems);\n// [\"Strawberry\", \"Mango\", \"Cherry\"]\n
\n
\n

Truncate an array down to just its first N items

\n
\n

This example uses the splice() method to truncate the fruits array down to just its first 2 items.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Strawberry\", \"Mango\", \"Cherry\"];\nconst start = 2;\nconst removedItems = fruits.splice(start);\nconsole.log(fruits);\n// [\"Apple\", \"Banana\"]\nconsole.log(removedItems);\n// [\"Strawberry\", \"Mango\", \"Cherry\"]\n
\n
\n

Remove the first item from an array

\n
\n

This example uses the shift() method to remove the first item from the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\nconst removedItem = fruits.shift();\nconsole.log(fruits);\n// [\"Banana\"]\nconsole.log(removedItem);\n// Apple\n
\n

Note: shift() can only be used to remove the first item from an array. To remove multiple items from the beginning of an array, see the next example.

\n

Remove multiple items from the beginning of an array

\n
\n

This example uses the splice() method to remove the first 3 items from the fruits array.

\n

js

\n
const fruits = [\"Apple\", \"Strawberry\", \"Cherry\", \"Banana\", \"Mango\"];\nconst start = 0;\nconst deleteCount = 3;\nconst removedItems = fruits.splice(start, deleteCount);\nconsole.log(fruits);\n// [\"Banana\", \"Mango\"]\nconsole.log(removedItems);\n// [\"Apple\", \"Strawberry\", \"Cherry\"]\n
\n
\n

Add a new first item to an array

\n
\n

This example uses the unshift() method to add, at index 0, a new item to the fruits array — making it the new first item in the array.

\n

js

\n
const fruits = [\"Banana\", \"Mango\"];\nconst newLength = fruits.unshift(\"Strawberry\");\nconsole.log(fruits);\n// [\"Strawberry\", \"Banana\", \"Mango\"]\nconsole.log(newLength);\n// 3\n
\n
\n

Remove a single item by index

\n
\n

This example uses the splice() method to remove the string \"Banana\" from the fruits array — by specifying the index position of \"Banana\".

\n

js

\n
const fruits = [\"Strawberry\", \"Banana\", \"Mango\"];\nconst start = fruits.indexOf(\"Banana\");\nconst deleteCount = 1;\nconst removedItems = fruits.splice(start, deleteCount);\nconsole.log(fruits);\n// [\"Strawberry\", \"Mango\"]\nconsole.log(removedItems);\n// [\"Banana\"]\n
\n
\n

Remove multiple items by index

\n
\n

This example uses the splice() method to remove the strings \"Banana\" and \"Strawberry\" from the fruits array — by specifying the index position of \"Banana\", along with a count of the number of total items to remove.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Strawberry\", \"Mango\"];\nconst start = 1;\nconst deleteCount = 2;\nconst removedItems = fruits.splice(start, deleteCount);\nconsole.log(fruits);\n// [\"Apple\", \"Mango\"]\nconsole.log(removedItems);\n// [\"Banana\", \"Strawberry\"]\n
\n
\n

Replace multiple items in an array

\n
\n

This example uses the splice() method to replace the last 2 items in the fruits array with new items.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Strawberry\"];\nconst start = -2;\nconst deleteCount = 2;\nconst removedItems = fruits.splice(start, deleteCount, \"Mango\", \"Cherry\");\nconsole.log(fruits);\n// [\"Apple\", \"Mango\", \"Cherry\"]\nconsole.log(removedItems);\n// [\"Banana\", \"Strawberry\"]\n
\n
\n

Iterate over an array

\n
\n

This example uses a for...of loop to iterate over the fruits array, logging each item to the console.

\n

js

\n
const fruits = [\"Apple\", \"Mango\", \"Cherry\"];\nfor (const fruit of fruits) {\n  console.log(fruit);\n}\n// Apple\n// Mango\n// Cherry\n
\n

But for...of is just one of many ways to iterate over any array; for more ways, see Loops and iteration, and see the documentation for the every(), filter(), flatMap(), map(), reduce(), and reduceRight() methods — and see the next example, which uses the forEach() method.

\n

Call a function on each element in an array

\n
\n

This example uses the forEach() method to call a function on each element in the fruits array; the function causes each item to be logged to the console, along with the item's index number.

\n

js

\n
const fruits = [\"Apple\", \"Mango\", \"Cherry\"];\nfruits.forEach((item, index, array) => {\n  console.log(item, index);\n});\n// Apple 0\n// Mango 1\n// Cherry 2\n
\n
\n

Merge multiple arrays together

\n
\n

This example uses the concat() method to merge the fruits array with a moreFruits array, to produce a new combinedFruits array. Notice that fruits and moreFruits remain unchanged.

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Strawberry\"];\nconst moreFruits = [\"Mango\", \"Cherry\"];\nconst combinedFruits = fruits.concat(moreFruits);\nconsole.log(combinedFruits);\n// [\"Apple\", \"Banana\", \"Strawberry\", \"Mango\", \"Cherry\"]\n\n// The 'fruits' array remains unchanged.\nconsole.log(fruits);\n// [\"Apple\", \"Banana\", \"Strawberry\"]\n\n// The 'moreFruits' array also remains unchanged.\nconsole.log(moreFruits);\n// [\"Mango\", \"Cherry\"]\n
\n
\n

Copy an array

\n
\n

This example shows three ways to create a new array from the existing fruits array: first by using spread syntax, then by using the from() method, and then by using the slice() method.

\n

js

\n
const fruits = [\"Strawberry\", \"Mango\"];\n\n// Create a copy using spread syntax.\nconst fruitsCopy = [...fruits];\n// [\"Strawberry\", \"Mango\"]\n\n// Create a copy using the from() method.\nconst fruitsCopy2 = Array.from(fruits);\n// [\"Strawberry\", \"Mango\"]\n\n// Create a copy using the slice() method.\nconst fruitsCopy3 = fruits.slice();\n// [\"Strawberry\", \"Mango\"]\n
\n

All built-in array-copy operations (spread syntax, Array.from(), Array.prototype.slice(), and Array.prototype.concat()) create shallow copies. If you instead want a deep copy of an array, you can use JSON.stringify() to convert the array to a JSON string, and then JSON.parse() to convert the string back into a new array that's completely independent from the original array.

\n

js

\n
const fruitsDeepCopy = JSON.parse(JSON.stringify(fruits));\n
\n

You can also create deep copies using the structuredClone() method, which has the advantage of allowing transferable objects in the source to be transferred to the new copy, rather than just cloned.

Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, or alias, to the original array; that is, the original array's name and the new variable name are just two names for the exact same object (and so will always evaluate as strictly equivalent). Therefore, if you make any changes at all either to the value of the original array or to the value of the new variable, the other will change, too:

\n

js

\n
const fruits = [\"Strawberry\", \"Mango\"];\nconst fruitsAlias = fruits;\n// 'fruits' and 'fruitsAlias' are the same object, strictly equivalent.\nfruits === fruitsAlias; // true\n// Any changes to the 'fruits' array change 'fruitsAlias' too.\nfruits.unshift(\"Apple\", \"Banana\");\nconsole.log(fruits);\n// ['Apple', 'Banana', 'Strawberry', 'Mango']\nconsole.log(fruitsAlias);\n// ['Apple', 'Banana', 'Strawberry', 'Mango']\n
\n
\n

Creating a two-dimensional array

\n
\n

The following creates a chessboard as a two-dimensional array of strings. The first move is made by copying the 'p' in board[6][4] to board[4][4]. The old position at [6][4] is made blank.

\n

js

\n
const board = [\n  [\"R\", \"N\", \"B\", \"Q\", \"K\", \"B\", \"N\", \"R\"],\n  [\"P\", \"P\", \"P\", \"P\", \"P\", \"P\", \"P\", \"P\"],\n  [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"],\n  [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"],\n  [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"],\n  [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"],\n  [\"p\", \"p\", \"p\", \"p\", \"p\", \"p\", \"p\", \"p\"],\n  [\"r\", \"n\", \"b\", \"q\", \"k\", \"b\", \"n\", \"r\"],\n];\n\nconsole.log(`${board.join(\"\\n\")}\\n\\n`);\n\n// Move King's Pawn forward 2\nboard[4][4] = board[6][4];\nboard[6][4] = \" \";\nconsole.log(board.join(\"\\n\"));\n
\n

Here is the output:

R,N,B,Q,K,B,N,R\nP,P,P,P,P,P,P,P\n , , , , , , ,\n , , , , , , ,\n , , , , , , ,\n , , , , , , ,\np,p,p,p,p,p,p,p\nr,n,b,q,k,b,n,r\n\nR,N,B,Q,K,B,N,R\nP,P,P,P,P,P,P,P\n , , , , , , ,\n , , , , , , ,\n , , , ,p, , ,\n , , , , , , ,\np,p,p,p, ,p,p,p\nr,n,b,q,k,b,n,r\n
\n

Using an array to tabulate a set of values

\n
\n
\n

js

\n
const values = [];\nfor (let x = 0; x < 10; x++) {\n  values.push([2 ** x, 2 * x ** 2]);\n}\nconsole.table(values);\n
\n

Results in

// The first column is the index\n0  1    0\n1  2    2\n2  4    8\n3  8    18\n4  16   32\n5  32   50\n6  64   72\n7  128  98\n8  256  128\n9  512  162\n
\n

Creating an array using the result of a match

\n
\n

The result of a match between a RegExp and a string can create a JavaScript array that has properties and elements which provide information about the match. Such an array is returned by RegExp.prototype.exec() and String.prototype.match().

For example:

\n

js

\n
// Match one d followed by one or more b's followed by one d\n// Remember matched b's and the following d\n// Ignore case\n\nconst myRe = /d(b+)(d)/i;\nconst execResult = myRe.exec(\"cdbBdbsbz\");\n\nconsole.log(execResult.input); // 'cdbBdbsbz'\nconsole.log(execResult.index); // 1\nconsole.log(execResult); // [ \"dbBd\", \"bB\", \"d\" ]\n
\n

For more information about the result of a match, see the RegExp.prototype.exec() and String.prototype.match() pages.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
@@species517948No381051514841105.01.06.5.0
@@unscopables381248No251038384825103.01.00.12.0
Array1121441≤3718410.111.01.00.10.0
Array1121441≤3718410.111.01.00.10.0
at929290No7815.49292906515.416.01.1216.6.0
concat11215.5414.418410.111.01.00.10.0
copyWithin451232No3294545323295.01.04.0.0
entries381228No2583838282583.01.00.12.0
every1121.599.53≤3718410.111.01.00.10.0
fill451231No3284545313285.01.04.0.0
filter1121.599.53≤3718410.111.01.00.10.0
find451225No328454543285.01.04.0.0
findIndex451225No328454543285.01.04.0.0
findLast9797104No8315.497971046815.418.01.1618.0.0
findLastIndex9797104No8315.497971046815.418.01.1618.0.0
flat697962No5612696962481210.01.011.0.0
flatMap697962No5612696962481210.01.011.0.0
forEach1121.599.53≤3718410.111.01.00.10.0
from451232No3294545323295.01.04.0.0
fromAsyncNoNo115NoNo16.4NoNo115No16.4NoNoNo
includes471443No3494747433495.01.06.0.0
indexOf1121.599.53≤3718410.111.01.00.10.0
isArray4124910.554.41841451.01.00.10.0
join11215.5414.418410.111.01.00.10.0
keys381228No2583838282583.01.00.12.0
lastIndexOf1121.599.53≤3718410.111.01.00.10.0
length1121441≤3718410.111.01.00.10.0
map1121.599.53≤3718410.111.01.00.10.0
of451225No2693939252694.01.04.0.0
pop11215.5414.418410.111.01.00.10.0
push11215.5414.418410.111.01.00.10.0
reduce3123910.54≤37184143.21.01.00.10.0
reduceRight3123910.54≤37184143.21.01.00.10.0
reverse11215.5414.418410.111.01.00.10.0
shift11215.5414.418410.111.01.00.10.0
slice11214414.418410.111.01.00.10.0
some1121.599.53≤3718410.111.01.00.10.0
sort11215.5414.418410.111.01.00.10.0
splice1121
5.5From Internet Explorer 5.5 through 8, all elements of the array will not be deleted if deleteCount is omitted. This behavior was fixed in Internet Explorer 9.
414.418410.111.01.00.10.0
toLocaleString11215.541≤3718410.111.01.00.10.0
toReversed110110115No9616110110115741621.01.3120.0.0
toSorted110110115No9616110110115741621.01.3120.0.0
toSpliced110110115No9616110110115741621.01.3120.0.0
toString1121441≤3718410.111.01.00.10.0
unshift11215.5414.418410.111.01.00.10.0
values661460No5396666604799.01.010.9.00.12.0–4.0.0
with110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\n

\n
\n", + "global_objects/uint32array": "

Uint32Array

\n

The Uint32Array typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Uint32Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Uint32Array()

Creates a new Uint32Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Uint32Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of Uint32Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Uint32Array.prototype and shared by all Uint32Array instances.

Uint32Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of a Uint32Array.

Uint32Array.prototype.constructor

The constructor function that created the instance object. For Uint32Array instances, the initial value is the Uint32Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Uint32Array

\n
\n

js

\n
// From a length\nconst uint32 = new Uint32Array(2);\nuint32[0] = 42;\nconsole.log(uint32[0]); // 42\nconsole.log(uint32.length); // 2\nconsole.log(uint32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Uint32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Uint32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint32FromIterable = new Uint32Array(iterable);\nconsole.log(uint32FromIterable);\n// Uint32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint32Array71241011.65.14184124.21.01.00.10.0
Uint32Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array\n

\n
\n", + "global_objects/bigint64array": "

BigInt64Array

\n

The BigInt64Array typed array represents an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

BigInt64Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
BigInt64Array()

Creates a new BigInt64Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

BigInt64Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of BigInt64Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on BigInt64Array.prototype and shared by all BigInt64Array instances.

BigInt64Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of a BigInt64Array.

BigInt64Array.prototype.constructor

The constructor function that created the instance object. For BigInt64Array instances, the initial value is the BigInt64Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a BigInt64Array

\n
\n

js

\n
// From a length\nconst bigint64 = new BigInt64Array(2);\nbigint64[0] = 42n;\nconsole.log(bigint64[0]); // 42n\nconsole.log(bigint64.length); // 2\nconsole.log(bigint64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new BigInt64Array([21n, 31n]);\nconsole.log(x[1]); // 31n\n\n// From another TypedArray\nconst y = new BigInt64Array(x);\nconsole.log(y[0]); // 21n\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new BigInt64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1n, 2n, 3n];\n})();\nconst bigint64FromIterable = new BigInt64Array(iterable);\nconsole.log(bigint64FromIterable);\n// BigInt64Array [1n, 2n, 3n]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigInt64Array677968No541567676848159.01.010.4.0
BigInt64Array677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array\n

\n
\n", + "global_objects/biguint64array": "

BigUint64Array

\n

The BigUint64Array typed array represents an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

BigUint64Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
BigUint64Array()

Creates a new BigUint64Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

BigUint64Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of BigUint64Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on BigUint64Array.prototype and shared by all BigUint64Array instances.

BigUint64Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of a BigUint64Array.

BigUint64Array.prototype.constructor

The constructor function that created the instance object. For BigUint64Array instances, the initial value is the BigUint64Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a BigUint64Array

\n
\n

js

\n
// From a length\nconst biguint64 = new BigUint64Array(2);\nbiguint64[0] = 42n;\nconsole.log(biguint64[0]); // 42n\nconsole.log(biguint64.length); // 2\nconsole.log(biguint64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new BigUint64Array([21n, 31n]);\nconsole.log(x[1]); // 31n\n\n// From another TypedArray\nconst y = new BigUint64Array(x);\nconsole.log(y[0]); // 21n\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new BigUint64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1n, 2n, 3n];\n})();\nconst biguint64FromIterable = new BigUint64Array(iterable);\nconsole.log(biguint64FromIterable);\n// BigUint64Array [1n, 2n, 3n]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigUint64Array677968No541567676848159.01.010.4.0
BigUint64Array677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array\n

\n
\n", + "global_objects/float32array": "

Float32Array

\n

The Float32Array typed array represents an array of 32-bit floating point numbers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Float32Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Float32Array()

Creates a new Float32Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Float32Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of Float32Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Float32Array.prototype and shared by all Float32Array instances.

Float32Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 4 in the case of a Float32Array.

Float32Array.prototype.constructor

The constructor function that created the instance object. For Float32Array instances, the initial value is the Float32Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Float32Array

\n
\n

js

\n
// From a length\nconst float32 = new Float32Array(2);\nfloat32[0] = 42;\nconsole.log(float32[0]); // 42\nconsole.log(float32.length); // 2\nconsole.log(float32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Float32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Float32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Float32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst float32FromIterable = new Float32Array(iterable);\nconsole.log(float32FromIterable);\n// Float32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Float32Array71241011.65.14184124.21.01.00.10.0
Float32Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array\n

\n
\n", + "global_objects/float64array": "

Float64Array

\n

The Float64Array typed array represents an array of 64-bit floating point numbers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Float64Array is a subclass of the hidden TypedArray class.

\n
\n

Constructor

\n
Float64Array()

Creates a new Float64Array object.

Static properties

\n
\n

Also inherits static properties from its parent TypedArray.

Float64Array.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of Float64Array.

\n

Static methods

\n

Inherits static methods from its parent TypedArray.

Instance properties

\n
\n

Also inherits instance properties from its parent TypedArray.

These properties are defined on Float64Array.prototype and shared by all Float64Array instances.

Float64Array.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size. 8 in the case of a Float64Array.

Float64Array.prototype.constructor

The constructor function that created the instance object. For Float64Array instances, the initial value is the Float64Array constructor.

\n

Instance methods

\n

Inherits instance methods from its parent TypedArray.

Examples

\n

Different ways to create a Float64Array

\n
\n

js

\n
// From a length\nconst float64 = new Float64Array(2);\nfloat64[0] = 42;\nconsole.log(float64[0]); // 42\nconsole.log(float64.length); // 2\nconsole.log(float64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new Float64Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Float64Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new Float64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst float64FromIterable = new Float64Array(iterable);\nconsole.log(float64FromIterable);\n// Float64Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# table-49
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Float64Array71241011.65.14184124.21.01.00.10.0
Float64Array71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array\n

\n
\n", + "global_objects/map": "

Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

\n

Try it

\n

Description

\n
\n

Map objects are collections of key-value pairs. A key in the Map may only occur once; it is unique in the Map's collection. A Map object is iterated by key-value pairs — a for...of loop returns a 2-member array of [key, value] for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the set() method (that is, there wasn't a key with the same value already in the map when set() was called).

The specification requires maps to be implemented \"that, on average, provide access times that are sublinear on the number of elements in the collection\". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

\n

Key equality

\n

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated 0 and -0 as different. Check browser compatibility.) This means NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator.

Objects vs. Maps

\n
\n

Object is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Object has been used as Map historically.

However, there are important differences that make Map preferable in some cases:

Map Object
Accidental Keys A Map does not contain any keys by default. It only contains what is explicitly put into it.

An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.

Note: This can be bypassed by using Object.create(null), but this is seldom done.

Security A Map is safe to use with user-provided keys and values.

Setting user-provided key-value pairs on an Object may allow an attacker to override the object's prototype, which can lead to object injection attacks . Like the accidental keys issue, this can also be mitigated by using a null-prototype object.

Key Types A Map's keys can be any value (including functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol.
Key Order

The keys in Map are ordered in a simple, straightforward way: A Map object iterates entries, keys, and values in the order of entry insertion.

Although the keys of an ordinary Object are ordered now, this was not always the case, and the order is complex. As a result, it's best not to rely on property order.

The order was first defined for own properties only in ECMAScript 2015; ECMAScript 2020 defines order for inherited properties as well. But note that no single mechanism iterates all of an object's properties; the various mechanisms each include different subsets of properties. (for-in includes only enumerable string-keyed properties; Object.keys includes only own, enumerable, string-keyed properties; Object.getOwnPropertyNames includes own, string-keyed properties even if non-enumerable; Object.getOwnPropertySymbols does the same for just Symbol-keyed properties, etc.)

Size

The number of items in a Map is easily retrieved from its size property. Determining the number of items in an Object is more roundabout and less efficient. A common way to do it is through the length of the array returned from Object.keys().
Iteration A Map is an iterable, so it can be directly iterated.

Object does not implement an iteration protocol, and so objects are not directly iterable using the JavaScript for...of statement (by default).

Note:

  • An object can implement the iteration protocol, or you can get an iterable for an object using Object.keys or Object.entries.
  • The for...in statement allows you to iterate over the enumerable properties of an object.
Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for Map by using JSON.stringify() with its replacer argument, and by using JSON.parse() with its reviver argument. See the Stack Overflow question How do you JSON.stringify an ES6 Map?).

Native support for serialization from Object to JSON, using JSON.stringify().

Native support for parsing from JSON to Object, using JSON.parse().

\n

Setting object properties

\n
\n

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:

\n

js

\n
const wrongMap = new Map();\nwrongMap[\"bla\"] = \"blaa\";\nwrongMap[\"bla2\"] = \"blaaa2\";\n\nconsole.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }\n
\n

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Other operations on the data fail:

\n

js

\n
wrongMap.has(\"bla\"); // false\nwrongMap.delete(\"bla\"); // false\nconsole.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }\n
\n

The correct usage for storing data in the Map is through the set(key, value) method.

\n

js

\n
const contacts = new Map();\ncontacts.set(\"Jessie\", { phone: \"213-555-1234\", address: \"123 N 1st Ave\" });\ncontacts.has(\"Jessie\"); // true\ncontacts.get(\"Hilary\"); // undefined\ncontacts.set(\"Hilary\", { phone: \"617-555-4321\", address: \"321 S 2nd St\" });\ncontacts.get(\"Jessie\"); // {phone: \"213-555-1234\", address: \"123 N 1st Ave\"}\ncontacts.delete(\"Raymond\"); // false\ncontacts.delete(\"Jessie\"); // true\nconsole.log(contacts.size); // 1\n
\n
\n

Map-like browser APIs

\n
\n

Map (or \"maplike objects\") are Web API interfaces that behave in many ways like a Map.

Just like Map, entries can be iterated in the same order that they were added to the object. Map-like objects and Map also have properties and methods that share the same name and behavior. However unlike Map they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition. For example, RTCStatsReport is a Map-like object that must use strings for keys and objects for values. This is defined in the specification IDL below:

\n

webidl

\n
interface RTCStatsReport {\n  readonly maplike<DOMString, object>;\n};\n
\n

Map-like objects are either read-only or read-writable (see the readonly keyword in the IDL above).

The methods and properties have the same behavior as the equivalent entities in Map, except for the restriction on the types of the keys and values.

The following are examples of read-only Map-like browser objects:

\n

Constructor

\n
Map()

Creates a new Map object.

Static properties

\n
Map[@@species]

The constructor function that is used to create derived objects.

Static methods

\n
Map.groupBy()

Groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.

Instance properties

\n
\n

These properties are defined on Map.prototype and shared by all Map instances.

Map.prototype.constructor

The constructor function that created the instance object. For Map instances, the initial value is the Map constructor.

Map.prototype.size

Returns the number of key/value pairs in the Map object.

Map.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Map\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Map.prototype.clear()

Removes all key-value pairs from the Map object.

Map.prototype.delete()

Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. map.has(key) will return false afterwards.

Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of [key, value] for each element in the Map object in insertion order.

Map.prototype.forEach()

Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.

Map.prototype.get()

Returns the value associated to the passed key, or undefined if there is none.

Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the Map object or not.

Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

Map.prototype.set()

Sets the value for the passed key in the Map object. Returns the Map object.

Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the Map object in insertion order.

Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of [key, value] for each element in the Map object in insertion order.

Examples

\n

Using the Map object

\n
\n

js

\n
const myMap = new Map();\n\nconst keyString = \"a string\";\nconst keyObj = {};\nconst keyFunc = function () {};\n\n// setting the values\nmyMap.set(keyString, \"value associated with 'a string'\");\nmyMap.set(keyObj, \"value associated with keyObj\");\nmyMap.set(keyFunc, \"value associated with keyFunc\");\n\nconsole.log(myMap.size); // 3\n\n// getting the values\nconsole.log(myMap.get(keyString)); // \"value associated with 'a string'\"\nconsole.log(myMap.get(keyObj)); // \"value associated with keyObj\"\nconsole.log(myMap.get(keyFunc)); // \"value associated with keyFunc\"\n\nconsole.log(myMap.get(\"a string\")); // \"value associated with 'a string'\", because keyString === 'a string'\nconsole.log(myMap.get({})); // undefined, because keyObj !== {}\nconsole.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}\n
\n

Using NaN as Map keys

\n
\n

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:

\n

js

\n
const myMap = new Map();\nmyMap.set(NaN, \"not a number\");\n\nmyMap.get(NaN);\n// \"not a number\"\n\nconst otherNaN = Number(\"foo\");\nmyMap.get(otherNaN);\n// \"not a number\"\n
\n
\n

Iterating Map with for...of

\n
\n

Maps can be iterated using a for...of loop:

\n

js

\n
const myMap = new Map();\nmyMap.set(0, \"zero\");\nmyMap.set(1, \"one\");\n\nfor (const [key, value] of myMap) {\n  console.log(`${key} = ${value}`);\n}\n// 0 = zero\n// 1 = one\n\nfor (const key of myMap.keys()) {\n  console.log(key);\n}\n// 0\n// 1\n\nfor (const value of myMap.values()) {\n  console.log(value);\n}\n// zero\n// one\n\nfor (const [key, value] of myMap.entries()) {\n  console.log(`${key} = ${value}`);\n}\n// 0 = zero\n// 1 = one\n
\n
\n

Iterating Map with forEach()

\n
\n

Maps can be iterated using the forEach() method:

\n

js

\n
myMap.forEach((value, key) => {\n  console.log(`${key} = ${value}`);\n});\n// 0 = zero\n// 1 = one\n
\n
\n

Relation with Array objects

\n
\n

js

\n
const kvArray = [\n  [\"key1\", \"value1\"],\n  [\"key2\", \"value2\"],\n];\n\n// Use the regular Map constructor to transform a 2D key-value Array into a map\nconst myMap = new Map(kvArray);\n\nconsole.log(myMap.get(\"key1\")); // \"value1\"\n\n// Use Array.from() to transform a map into a 2D key-value Array\nconsole.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray\n\n// A succinct way to do the same, using the spread syntax\nconsole.log([...myMap]);\n\n// Or use the keys() or values() iterators, and convert them to an array\nconsole.log(Array.from(myMap.keys())); // [\"key1\", \"key2\"]\n
\n

Cloning and merging Maps

\n
\n

Just like Arrays, Maps can be cloned:

\n

js

\n
const original = new Map([[1, \"one\"]]);\n\nconst clone = new Map(original);\n\nconsole.log(clone.get(1)); // one\nconsole.log(original === clone); // false (useful for shallow comparison)\n
\n

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:

\n

js

\n
const first = new Map([\n  [1, \"one\"],\n  [2, \"two\"],\n  [3, \"three\"],\n]);\n\nconst second = new Map([\n  [1, \"uno\"],\n  [2, \"dos\"],\n]);\n\n// Merge two maps. The last repeated key wins.\n// Spread syntax essentially converts a Map to an Array\nconst merged = new Map([...first, ...second]);\n\nconsole.log(merged.get(1)); // uno\nconsole.log(merged.get(2)); // dos\nconsole.log(merged.get(3)); // three\n
\n

Maps can be merged with Arrays, too:

\n

js

\n
const first = new Map([\n  [1, \"one\"],\n  [2, \"two\"],\n  [3, \"three\"],\n]);\n\nconst second = new Map([\n  [1, \"uno\"],\n  [2, \"dos\"],\n]);\n\n// Merge maps with an array. The last repeated key wins.\nconst merged = new Map([...first, ...second, [1, \"eins\"]]);\n\nconsole.log(merged.get(1)); // eins\nconsole.log(merged.get(2)); // dos\nconsole.log(merged.get(3)); // three\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
@@species511341No381051514141105.01.06.5.0
@@toStringTag447951No319.1444451329.34.01.06.0.0
Map381213112583838142583.01.00.12.0
Map381213112583838142583.01.00.12.0
clear381219112583838192583.01.00.12.0
delete381213112583838142583.01.00.12.0
entries381220No2583838202583.01.00.12.0
forEach381225112583838252583.01.00.12.0
get381213112583838142583.01.00.12.0
groupBy117117119No10316.4–previewpreview117117119No16.4No1.37No
has381213112583838142583.01.00.12.0
key_equality_for_zeros381229No2593838292593.01.04.0.0
keys381220No2583838202583.01.00.12.0
set381213
11Returns 'undefined' instead of the 'Map' object.
2583838142583.01.00.12.0
size3812
19From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
112583838
19From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
2583.01.00.12.0
values381220No2583838202583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\n

\n
\n", + "global_objects/set": "

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

\n

Description

\n
\n

Set objects are collections of values. A value in the set may only occur once; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. The insertion order corresponds to the order in which each element was inserted into the set by the add() method successfully (that is, there wasn't an identical element already in the set when add() was called).

The specification requires sets to be implemented \"that, on average, provide access times that are sublinear on the number of elements in the collection\". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

\n

Value equality

\n

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated 0 and -0 as different. Check browser compatibility.) This means NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator.

Performance

\n

The has method checks if a value is in the set, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the set. In particular, it is, on average, faster than the Array.prototype.includes method when an array has a length equal to a set's size.

Set-like browser APIs

\n
\n

Browser Set (or \"setlike objects\") are Web API interfaces that behave in many ways like a Set.

Just like Set, elements can be iterated in the same order that they were added to the object. Set-like objects and Set also have properties and methods that share the same name and behavior. However unlike Set they only allow a specific predefined type for each entry.

The allowed types are set in the specification IDL definition. For example, GPUSupportedFeatures is a Set-like object that must use strings as the key/value. This is defined in the specification IDL below:

\n

webidl

\n
interface GPUSupportedFeatures {\n  readonly setlike<DOMString>;\n};\n
\n

Set-like objects are either read-only or read-writable (see the readonly keyword in the IDL above).

The methods and properties have the same behavior as the equivalent entities in Set, except for the restriction on the types of the entry.

The following are examples of read-only Set-like browser objects:

The following are examples of writable Set-like browser objects:

\n

Constructor

\n
Set()

Creates a new Set object.

Static properties

\n
Set[@@species]

The constructor function that is used to create derived objects.

Instance properties

\n
\n

These properties are defined on Set.prototype and shared by all Set instances.

Set.prototype.constructor

The constructor function that created the instance object. For Set instances, the initial value is the Set constructor.

Set.prototype.size

Returns the number of values in the Set object.

Set.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Set\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Set.prototype.add()

Inserts a new element with a specified value in to a Set object, if there isn't an element with the same value already in the Set.

Set.prototype.clear()

Removes all elements from the Set object.

Set.prototype.delete()

Removes the element associated to the value and returns a boolean asserting whether an element was successfully removed or not. Set.prototype.has(value) will return false afterwards.

Set.prototype.entries()

Returns a new iterator object that contains [value, value] for each element in the Set object, in insertion order. This is similar to the Map object, so that each entry's key is the same as its value for a Set.

Set.prototype.forEach()

Calls callbackFn once for each value present in the Set object, in insertion order. If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackFn.

Set.prototype.has()

Returns a boolean asserting whether an element is present with the given value in the Set object or not.

Set.prototype.keys()

An alias for Set.prototype.values().

Set.prototype.values()

Returns a new iterator object that yields the values for each element in the Set object in insertion order.

Set.prototype[@@iterator]()

Returns a new iterator object that yields the values for each element in the Set object in insertion order.

Examples

\n

Using the Set object

\n
\n

js

\n
const mySet1 = new Set();\n\nmySet1.add(1); // Set(1) { 1 }\nmySet1.add(5); // Set(2) { 1, 5 }\nmySet1.add(5); // Set(2) { 1, 5 }\nmySet1.add(\"some text\"); // Set(3) { 1, 5, 'some text' }\nconst o = { a: 1, b: 2 };\nmySet1.add(o);\n\nmySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okay\n\nmySet1.has(1); // true\nmySet1.has(3); // false, since 3 has not been added to the set\nmySet1.has(5); // true\nmySet1.has(Math.sqrt(25)); // true\nmySet1.has(\"Some Text\".toLowerCase()); // true\nmySet1.has(o); // true\n\nmySet1.size; // 5\n\nmySet1.delete(5); // removes 5 from the set\nmySet1.has(5); // false, 5 has been removed\n\nmySet1.size; // 4, since we just removed one value\n\nmySet1.add(5); // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletion\n\nconsole.log(mySet1); // Set(5) { 1, \"some text\", {…}, {…}, 5 }\n
\n

Iterating sets

\n
\n

The iteration over a set visits elements in insertion order.

\n

js

\n
for (const item of mySet1) {\n  console.log(item);\n}\n// 1, \"some text\", { \"a\": 1, \"b\": 2 }, { \"a\": 1, \"b\": 2 }, 5\n\nfor (const item of mySet1.keys()) {\n  console.log(item);\n}\n// 1, \"some text\", { \"a\": 1, \"b\": 2 }, { \"a\": 1, \"b\": 2 }, 5\n\nfor (const item of mySet1.values()) {\n  console.log(item);\n}\n// 1, \"some text\", { \"a\": 1, \"b\": 2 }, { \"a\": 1, \"b\": 2 }, 5\n\n// key and value are the same here\nfor (const [key, value] of mySet1.entries()) {\n  console.log(key);\n}\n// 1, \"some text\", { \"a\": 1, \"b\": 2 }, { \"a\": 1, \"b\": 2 }, 5\n\n// Convert Set object to an Array object, with Array.from\nconst myArr = Array.from(mySet1); // [1, \"some text\", {\"a\": 1, \"b\": 2}, {\"a\": 1, \"b\": 2}, 5]\n\n// the following will also work if run in an HTML document\nmySet1.add(document.body);\nmySet1.has(document.querySelector(\"body\")); // true\n\n// converting between Set and Array\nconst mySet2 = new Set([1, 2, 3, 4]);\nconsole.log(mySet2.size); // 4\nconsole.log([...mySet2]); // [1, 2, 3, 4]\n\n// intersect can be simulated via\nconst intersection = new Set([...mySet1].filter((x) => mySet2.has(x)));\n\n// difference can be simulated via\nconst difference = new Set([...mySet1].filter((x) => !mySet2.has(x)));\n\n// Iterate set entries with forEach()\nmySet2.forEach((value) => {\n  console.log(value);\n});\n// 1\n// 2\n// 3\n// 4\n
\n
\n

Implementing basic set operations

\n
\n

js

\n
function isSuperset(set, subset) {\n  for (const elem of subset) {\n    if (!set.has(elem)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction union(setA, setB) {\n  const _union = new Set(setA);\n  for (const elem of setB) {\n    _union.add(elem);\n  }\n  return _union;\n}\n\nfunction intersection(setA, setB) {\n  const _intersection = new Set();\n  for (const elem of setB) {\n    if (setA.has(elem)) {\n      _intersection.add(elem);\n    }\n  }\n  return _intersection;\n}\n\nfunction symmetricDifference(setA, setB) {\n  const _difference = new Set(setA);\n  for (const elem of setB) {\n    if (_difference.has(elem)) {\n      _difference.delete(elem);\n    } else {\n      _difference.add(elem);\n    }\n  }\n  return _difference;\n}\n\nfunction difference(setA, setB) {\n  const _difference = new Set(setA);\n  for (const elem of setB) {\n    _difference.delete(elem);\n  }\n  return _difference;\n}\n\n// Examples\nconst setA = new Set([1, 2, 3, 4]);\nconst setB = new Set([2, 3]);\nconst setC = new Set([3, 4, 5, 6]);\n\nisSuperset(setA, setB); // returns true\nunion(setA, setC); // returns Set {1, 2, 3, 4, 5, 6}\nintersection(setA, setC); // returns Set {3, 4}\nsymmetricDifference(setA, setC); // returns Set {1, 2, 5, 6}\ndifference(setA, setC); // returns Set {1, 2}\n
\n

Relation to arrays

\n
\n

js

\n
const myArray = [\"value1\", \"value2\", \"value3\"];\n\n// Use the regular Set constructor to transform an Array into a Set\nconst mySet = new Set(myArray);\n\nmySet.has(\"value1\"); // returns true\n\n// Use the spread syntax to transform a set into an Array.\nconsole.log([...mySet]); // Will show you exactly the same Array as myArray\n
\n

Remove duplicate elements from an array

\n
\n

js

\n
// Use to remove duplicate elements from an array\n\nconst numbers = [2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5];\n\nconsole.log([...new Set(numbers)]);\n\n// [2, 13, 4, 5, 6, 7, 32]\n
\n

Relation to strings

\n
\n

js

\n
const text = \"India\";\n\nconst mySet = new Set(text); // Set(5) {'I', 'n', 'd', 'i', 'a'}\nmySet.size; // 5\n\n// case sensitive & duplicate omission\nnew Set(\"Firefox\"); // Set(7) { \"F\", \"i\", \"r\", \"e\", \"f\", \"o\", \"x\" }\nnew Set(\"firefox\"); // Set(6) { \"f\", \"i\", \"r\", \"e\", \"o\", \"x\" }\n
\n

Use a set to ensure the uniqueness of a list of values

\n
\n

js

\n
const array = Array.from(document.querySelectorAll(\"[id]\")).map((e) => e.id);\n\nconst set = new Set(array);\nconsole.assert(set.size === array.length);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator431236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No309434336
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
3094.01.00.12.0
@@species511341No381051514141105.01.06.5.0
Set381213112583838142583.01.00.12.0
Set381213112583838142583.01.00.12.0
add381213
11Returns 'undefined' instead of the 'Set' object.
2583838142583.01.00.12.0
clear381219112583838192583.01.00.12.0
delete381213112583838142583.01.00.12.0
differenceNoNopreviewNoNo17NoNoNoNo17NoNoNo
entries381224No2583838242583.01.00.12.0
forEach381225112583838252583.01.00.12.0
has381213112583838142583.01.00.12.0
intersectionNoNopreviewNoNo17NoNoNoNo17NoNoNo
isDisjointFromNoNopreviewNoNo17NoNoNoNo17NoNoNo
isSubsetOfNoNopreviewNoNo17NoNoNoNo17NoNoNo
isSupersetOfNoNopreviewNoNo17NoNoNoNo17NoNoNo
key_equality_for_zeros381229No2593838292593.01.04.0.0
size3812
19From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
112583838
19From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
2583.01.00.12.0
symmetricDifferenceNoNopreviewNoNo17NoNoNoNo17NoNoNo
unionNoNopreviewNoNo17NoNoNoNo17NoNoNo
values383812122424No2525883838383824242525883.03.01.01.00.12.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\n

\n
\n", + "global_objects/weakmap": "

WeakMap

\n

A WeakMap is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a WeakMap does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any WeakMap become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a WeakMap key is symbol — more specifically, non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.

WeakMap allows associating data to objects in a way that doesn't prevent the key objects from being collected, even if the values reference the keys. However, a WeakMap doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration; if a WeakMap exposed any method to obtain a list of its keys, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map rather than a WeakMap.

You can learn more about WeakMap in the WeakMap object section of the Keyed collections guide.

\n
\n

Description

\n

Keys of WeakMaps must be garbage-collectable. Most primitive data types can be arbitrarily created and don't have a lifetime, so they cannot be used as keys. Objects and non-registered symbols can be used as keys because they are garbage-collectable.

Why WeakMap?

\n
\n

A map API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. As a result, the indices of the key and value would correspond to both arrays. Getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values.

Such an implementation would have two main inconveniences:

  1. The first one is an O(n) set and search (n being the number of keys in the map) since both operations must iterate through the list of keys to find a matching value.
  2. The second inconvenience is a memory leak because the arrays ensure that references to each key and each value are maintained indefinitely. These references prevent the keys from being garbage collected, even if there are no other references to the object. This would also prevent the corresponding values from being garbage collected.

By contrast, in a WeakMap, a key object refers strongly to its contents as long as the key is not garbage collected, but weakly from then on. As such, a WeakMap:

A WeakMap can be a particularly useful construct when mapping keys to information about the key that is valuable only if the key has not been garbage collected.

But because a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys. If there were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map.

\n

Constructor

\n
WeakMap()

Creates a new WeakMap object.

Instance properties

\n
\n

These properties are defined on WeakMap.prototype and shared by all WeakMap instances.

WeakMap.prototype.constructor

The constructor function that created the instance object. For WeakMap instances, the initial value is the WeakMap constructor.

WeakMap.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"WeakMap\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
WeakMap.prototype.delete()

Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.

WeakMap.prototype.get()

Returns the value associated to the key, or undefined if there is none.

WeakMap.prototype.has()

Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.

WeakMap.prototype.set()

Sets the value for the key in the WeakMap object. Returns the WeakMap object.

Examples

\n

Using WeakMap

\n
\n

js

\n
const wm1 = new WeakMap();\nconst wm2 = new WeakMap();\nconst wm3 = new WeakMap();\nconst o1 = {};\nconst o2 = function () {};\nconst o3 = window;\n\nwm1.set(o1, 37);\nwm1.set(o2, \"azerty\");\nwm2.set(o1, o2); // a value can be anything, including an object or a function\nwm2.set(o2, undefined);\nwm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!\n\nwm1.get(o2); // \"azerty\"\nwm2.get(o2); // undefined, because that is the set value\nwm2.get(o3); // undefined, because there is no key for o3 on wm2\n\nwm1.has(o2); // true\nwm2.has(o2); // true (even if the value itself is 'undefined')\nwm2.has(o3); // false\n\nwm3.set(o1, 37);\nwm3.get(o1); // 37\n\nwm1.has(o1); // true\nwm1.delete(o1);\nwm1.has(o1); // false\n
\n

Implementing a WeakMap-like class with a .clear() method

\n
\n

js

\n
class ClearableWeakMap {\n  #wm;\n  constructor(init) {\n    this.#wm = new WeakMap(init);\n  }\n  clear() {\n    this.#wm = new WeakMap();\n  }\n  delete(k) {\n    return this.#wm.delete(k);\n  }\n  get(k) {\n    return this.#wm.get(k);\n  }\n  has(k) {\n    return this.#wm.has(k);\n  }\n  set(k, v) {\n    this.#wm.set(k, v);\n    return this;\n  }\n}\n
\n

Emulating private members

\n
\n

Developers can use a WeakMap to associate private data to an object, with the following benefits:

\n

js

\n
let Thing;\n\n{\n  const privateScope = new WeakMap();\n  let counter = 0;\n\n  Thing = function () {\n    this.someProperty = \"foo\";\n\n    privateScope.set(this, {\n      hidden: ++counter,\n    });\n  };\n\n  Thing.prototype.showPublic = function () {\n    return this.someProperty;\n  };\n\n  Thing.prototype.showPrivate = function () {\n    return privateScope.get(this).hidden;\n  };\n}\n\nconsole.log(typeof privateScope);\n// \"undefined\"\n\nconst thing = new Thing();\n\nconsole.log(thing);\n// Thing {someProperty: \"foo\"}\n\nthing.showPublic();\n// \"foo\"\n\nthing.showPrivate();\n// 1\n
\n

This is roughly equivalent to the following, using private fields:

\n

js

\n
class Thing {\n  static #counter = 0;\n  #hidden;\n  constructor() {\n    this.someProperty = \"foo\";\n    this.#hidden = ++Thing.#counter;\n  }\n  showPublic() {\n    return this.someProperty;\n  }\n  showPrivate() {\n    return this.#hidden;\n  }\n}\n\nconsole.log(thing);\n// Thing {someProperty: \"foo\"}\n\nthing.showPublic();\n// \"foo\"\n\nthing.showPrivate();\n// 1\n
\n
\n

Associating metadata

\n
\n

A WeakMap can be used to associate metadata with an object, without affecting the lifetime of the object itself. This is very similar to the private members example, since private members are also modelled as external metadata that doesn't participate in prototypical inheritance.

This use case can be extended to already-created objects. For example, on the web, we may want to associate extra data with a DOM element, which the DOM element may access later. A common approach is to attach the data as a property:

\n

js

\n
const buttons = document.querySelectorAll(\".button\");\nbuttons.forEach((button) => {\n  button.clicked = false;\n  button.addEventListener(\"click\", () => {\n    button.clicked = true;\n    const currentButtons = [...document.querySelectorAll(\".button\")];\n    if (currentButtons.every((button) => button.clicked)) {\n      console.log(\"All buttons have been clicked!\");\n    }\n  });\n});\n
\n

This approach works, but it has a few pitfalls:

Using a WeakMap fixes these:

\n

js

\n
const buttons = document.querySelectorAll(\".button\");\nconst clicked = new WeakMap();\nbuttons.forEach((button) => {\n  clicked.set(button, false);\n  button.addEventListener(\"click\", () => {\n    clicked.set(button, true);\n    const currentButtons = [...document.querySelectorAll(\".button\")];\n    if (currentButtons.every((button) => clicked.get(button))) {\n      console.log(\"All buttons have been clicked!\");\n    }\n  });\n});\n
\n

Here, only code that has access to clicked knows the clicked state of each button, and external code can't modify the states. In addition, if any of the buttons gets removed from the DOM, the associated metadata will automatically get garbage-collected.

\n

Caching

\n
\n

You can associate objects passed to a function with the result of the function, so that if the same object is passed again, the cached result can be returned without re-executing the function. This is useful if the function is pure (i.e. it doesn't mutate any outside objects or cause other observable side effects).

\n

js

\n
const cache = new WeakMap();\nfunction handleObjectValues(obj) {\n  if (cache.has(obj)) {\n    return cache.get(obj);\n  }\n  const result = Object.values(obj).map(heavyComputation);\n  cache.set(obj, result);\n  return result;\n}\n
\n

This only works if your function's input is an object. Moreover, even if the input is never passed in again, the result still remains forever in the cache. A more effective way is to use a Map paired with WeakRef objects, which allows you to associate any type of input value with its respective (potentially large) computation result. See the WeakRefs and FinalizationRegistry example for more details.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakMap3612611238373662483.01.00.12.0
WeakMap3612611238373662483.01.00.12.0
delete3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
get3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
2483.01.00.12.0
has3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
set3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
11Returns 'undefined' instead of the 'Map' object.
2383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
symbol_as_keys108108NoNo9416.4108108No7316.421.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap\n

\n
\n", + "global_objects/weakset": "

WeakSet

A WeakSet is a collection of garbage-collectable values, including objects and non-registered symbols. A value in the WeakSet may only occur once. It is unique in the WeakSet's collection.

\n

Description

\n
\n

Values of WeakSets must be garbage-collectable. Most primitive data types can be arbitrarily created and don't have a lifetime, so they cannot be stored. Objects and non-registered symbols can be stored because they are garbage-collectable.

The main differences to the Set object are:

\n

Use case: Detecting circular references

\n
\n

Functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed.

WeakSets are ideal for this purpose:

\n

js

\n
// Execute a callback on everything stored inside an object\nfunction execRecursively(fn, subject, _refs = new WeakSet()) {\n  // Avoid infinite recursion\n  if (_refs.has(subject)) {\n    return;\n  }\n\n  fn(subject);\n  if (typeof subject === \"object\" && subject) {\n    _refs.add(subject);\n    for (const key in subject) {\n      execRecursively(fn, subject[key], _refs);\n    }\n    _refs.delete(subject);\n  }\n}\n\nconst foo = {\n  foo: \"Foo\",\n  bar: {\n    bar: \"Bar\",\n  },\n};\n\nfoo.bar.baz = foo; // Circular reference!\nexecRecursively((obj) => console.log(obj), foo);\n
\n

Here, a WeakSet is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter).

The number of objects or their traversal order is immaterial, so a WeakSet is more suitable (and performant) than a Set for tracking object references, especially if a very large number of objects is involved.

\n

Constructor

\n
WeakSet()

Creates a new WeakSet object.

Instance properties

\n
\n

These properties are defined on WeakSet.prototype and shared by all WeakSet instances.

WeakSet.prototype.constructor

The constructor function that created the instance object. For WeakSet instances, the initial value is the WeakSet constructor.

WeakSet.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"WeakSet\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
WeakSet.prototype.add()

Appends value to the WeakSet object.

WeakSet.prototype.delete()

Removes value from the WeakSet. WeakSet.prototype.has(value) will return false afterwards.

WeakSet.prototype.has()

Returns a boolean asserting whether value is present in the WeakSet object or not.

Examples

\n

Using the WeakSet object

\n
\n
\n

js

\n
const ws = new WeakSet();\nconst foo = {};\nconst bar = {};\n\nws.add(foo);\nws.add(bar);\n\nws.has(foo); // true\nws.has(bar); // true\n\nws.delete(foo); // removes foo from the set\nws.has(foo); // false, foo has been removed\nws.has(bar); // true, bar is retained\n
\n

Note that foo !== bar. While they are similar objects, they are not the same object. And so they are both added to the set.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakset-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakSet361234No2393736342493.01.00.12.0
WeakSet361234No2393736342493.01.00.12.0
add361234No2393736342493.01.00.12.0
delete361234No2393736342493.01.00.12.0
has361234No2393736342493.01.00.12.0
symbol_as_keys108108NoNo9416.4108108No7316.421.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet\n

\n
\n", + "global_objects/arraybuffer": "

ArrayBuffer

\n

The ArrayBuffer object is used to represent a generic raw binary data buffer.

It is an array of bytes, often referred to in other languages as a \"byte array\". You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

The ArrayBuffer() constructor creates a new ArrayBuffer of the given length in bytes. You can also get an array buffer from existing data, for example, from a Base64 string or from a local file.

ArrayBuffer is a transferable object.

\n
\n

Description

\n

Resizing ArrayBuffers

\n
\n

ArrayBuffer objects can be made resizable by including the maxByteLength option when calling the ArrayBuffer() constructor. You can query whether an ArrayBuffer is resizable and what its maximum size is by accessing its resizable and maxByteLength properties, respectively. You can assign a new size to a resizable ArrayBuffer with a resize() call. New bytes are initialized to 0.

These features make resizing ArrayBuffers more efficient — otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with WebAssembly.Memory.prototype.grow()).

\n

Transferring ArrayBuffers

\n
\n

ArrayBuffer objects can be transferred between different execution contexts, like Web Workers or Service Workers, using the structured clone algorithm. This is done by passing the ArrayBuffer as a transferable object in a call to Worker.postMessage() or ServiceWorker.postMessage(). In pure JavaScript, you can also transfer the ownership of memory from one ArrayBuffer to another using its transfer() or transferToFixedLength() method.

When an ArrayBuffer is transferred, its original copy becomes detached — this means it is no longer usable. At any moment, there will only be one copy of the ArrayBuffer that actually has access to the underlying memory. Detached buffers have the following behaviors:

You can check whether an ArrayBuffer is detached by its detached property.

\n

Constructor

\n
ArrayBuffer()

Creates a new ArrayBuffer object.

Static properties

\n
ArrayBuffer[@@species]

The constructor function that is used to create derived objects.

Static methods

\n
ArrayBuffer.isView()

Returns true if arg is one of the ArrayBuffer views, such as typed array objects or a DataView. Returns false otherwise.

Instance properties

\n
\n

These properties are defined on ArrayBuffer.prototype and shared by all ArrayBuffer instances.

ArrayBuffer.prototype.byteLength

The size, in bytes, of the ArrayBuffer. This is established when the array is constructed and can only be changed using the ArrayBuffer.prototype.resize() method if the ArrayBuffer is resizable.

ArrayBuffer.prototype.constructor

The constructor function that created the instance object. For ArrayBuffer instances, the initial value is the ArrayBuffer constructor.

\nArrayBuffer.prototype.detached Experimental \n

Read-only. Returns true if the ArrayBuffer has been detached (transferred), or false if not.

ArrayBuffer.prototype.maxByteLength

The read-only maximum length, in bytes, that the ArrayBuffer can be resized to. This is established when the array is constructed and cannot be changed.

ArrayBuffer.prototype.resizable

Read-only. Returns true if the ArrayBuffer can be resized, or false if not.

ArrayBuffer.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"ArrayBuffer\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
ArrayBuffer.prototype.resize()

Resizes the ArrayBuffer to the specified size, in bytes.

ArrayBuffer.prototype.slice()

Returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin (inclusive) up to end (exclusive). If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.

\nArrayBuffer.prototype.transfer() Experimental \n

Creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

\nArrayBuffer.prototype.transferToFixedLength() Experimental \n

Creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

Examples

\n

Creating an ArrayBuffer

\n
\n

In this example, we create a 8-byte buffer with a Int32Array view referring to the buffer:

\n

js

\n
const buffer = new ArrayBuffer(8);\nconst view = new Int32Array(buffer);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arraybuffer-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species511348No381051514841105.01.06.5.0
ArrayBuffer71241011.65.14184124.21.01.00.10.0
ArrayBuffer71241011.65.14184124.21.01.00.10.0
byteLength71241011.65.14184124.21.01.00.10.0
detached114114previewNo100No114114NoNoNoNoNoNo
isView321229111974.4.332291972.01.04.0.0
maxByteLength111111NoNo9716.4111111NoNo16.422.01.3320.0.0
resizable111111NoNo9716.4111111NoNo16.422.01.3320.0.0
resize111111NoNo9716.4111111NoNo16.422.01.3320.0.0
slice1712
12The non-standard ArrayBuffer.slice() method has been removed in Firefox 53 (but the standardized version ArrayBuffer.prototype.slice() is kept.
1112.15.14.418
14The non-standard ArrayBuffer.slice() method has been removed in Firefox 53 (but the standardized version ArrayBuffer.prototype.slice() is kept.
12.161.01.00.12.0
transfer114114previewNo100No114114NoNoNoNoNoNo
transferToFixedLength114114previewNo100No114114NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\n

\n
\n", + "global_objects/sharedarraybuffer": "

SharedArrayBuffer

The SharedArrayBuffer object is used to represent a generic raw binary data buffer, similar to the ArrayBuffer object, but in a way that they can be used to create views on shared memory. A SharedArrayBuffer is not a Transferable Object, unlike an ArrayBuffer which is transferable.

\n

Description

\n
\n

To share memory using SharedArrayBuffer objects from one agent in the cluster to another (an agent is either the web page's main program or one of its web workers), postMessage and structured cloning is used.

The structured clone algorithm accepts SharedArrayBuffer objects and typed arrays mapped onto SharedArrayBuffer objects. In both cases, the SharedArrayBuffer object is transmitted to the receiver resulting in a new, private SharedArrayBuffer object in the receiving agent (just as for ArrayBuffer). However, the shared data block referenced by the two SharedArrayBuffer objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent.

\n

js

\n
const sab = new SharedArrayBuffer(1024);\nworker.postMessage(sab);\n
\n

Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, atomic operations are needed.

SharedArrayBuffer objects are used by some web APIs, such as:

\n

Security requirements

\n
\n

Shared memory and high-resolution timers were effectively disabled at the start of 2018 in light of Spectre. In 2020, a new, secure approach has been standardized to re-enable shared memory.

As a baseline requirement, your document needs to be in a secure context.

For top-level documents, two headers need to be set to cross-origin isolate your site:

\n

http

\n
Cross-Origin-Opener-Policy: same-origin\nCross-Origin-Embedder-Policy: require-corp\n
\n

To check if cross origin isolation has been successful, you can test against the crossOriginIsolated property available to window and worker contexts:

\n

js

\n
const myWorker = new Worker(\"worker.js\");\n\nif (crossOriginIsolated) {\n  const buffer = new SharedArrayBuffer(16);\n  myWorker.postMessage(buffer);\n} else {\n  const buffer = new ArrayBuffer(16);\n  myWorker.postMessage(buffer);\n}\n
\n

With these two headers set, postMessage() no longer throws for SharedArrayBuffer objects and shared memory across threads is therefore available.

Nested documents and dedicated workers need to set the Cross-Origin-Embedder-Policy header as well, with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources need to set the Cross-Origin-Resource-Policy header with same-site as value. And their cross-origin (and cross-site) counterparts need to set the same header with cross-origin as value. Note that setting the Cross-Origin-Resource-Policy header to any other value than same-origin opens up the resource to potential attacks, such as Spectre.

Note that the Cross-Origin-Opener-Policy header limits your ability to retain a reference to popups. Direct access between two top-level window contexts essentially only work if they are same-origin and carry the same two headers with the same two values.

\n

API availability

\n
\n

Depending on whether the above security measures are taken, the various memory-sharing APIs have different availabilities:

\n

WebAssembly shared memory

\n
\n

WebAssembly.Memory objects can be created with the shared constructor flag. When this flag is set to true, the constructed Memory object can be shared between workers via postMessage(), just like SharedArrayBuffer, and the backing buffer of the Memory object is a SharedArrayBuffer. Therefore, the requirements listed above for sharing a SharedArrayBuffer between workers also apply to sharing a WebAssembly.Memory.

The WebAssembly Threads proposal also defines a new set of atomic instructions. Just as SharedArrayBuffer and its methods are unconditionally enabled (and only sharing between threads is gated on the new headers), the WebAssembly atomic instructions are also unconditionally allowed.

\n

Growing SharedArrayBuffers

\n
\n

SharedArrayBuffer objects can be made growable by including the maxByteLength option when calling the SharedArrayBuffer() constructor. You can query whether a SharedArrayBuffer is growable and what its maximum size is by accessing its growable and maxByteLength properties, respectively. You can assign a new size to a growable SharedArrayBuffer with a grow() call. New bytes are initialized to 0.

These features make growing SharedArrayBuffers more efficient — otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with WebAssembly.Memory.prototype.grow()).

For security reasons, SharedArrayBuffers cannot be reduced in size, only grown.

\n

Constructor

\n
SharedArrayBuffer()

Creates a new SharedArrayBuffer object.

Static properties

\n
SharedArrayBuffer[@@species]

Returns the constructor used to construct return values from SharedArrayBuffer methods.

Instance properties

\n
\n

These properties are defined on SharedArrayBuffer.prototype and shared by all SharedArrayBuffer instances.

SharedArrayBuffer.prototype.byteLength

The size, in bytes, of the array. This is established when the array is constructed and can only be changed using the SharedArrayBuffer.prototype.grow() method if the SharedArrayBuffer is growable.

SharedArrayBuffer.prototype.constructor

The constructor function that created the instance object. For SharedArrayBuffer instances, the initial value is the SharedArrayBuffer constructor.

SharedArrayBuffer.prototype.growable

Read-only. Returns true if the SharedArrayBuffer can be grown, or false if not.

SharedArrayBuffer.prototype.maxByteLength

The read-only maximum length, in bytes, that the SharedArrayBuffer can be grown to. This is established when the array is constructed and cannot be changed.

SharedArrayBuffer.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"SharedArrayBuffer\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
SharedArrayBuffer.prototype.grow()

Grows the SharedArrayBuffer to the specified size, in bytes.

SharedArrayBuffer.prototype.slice()

Returns a new SharedArrayBuffer whose contents are a copy of this SharedArrayBuffer's bytes from begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.

Examples

\n

Creating a new SharedArrayBuffer

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\n
\n

Slicing the SharedArrayBuffer

\n
\n

js

\n
sab.slice(); // SharedArrayBuffer { byteLength: 1024 }\nsab.slice(2); // SharedArrayBuffer { byteLength: 1022 }\nsab.slice(-2); // SharedArrayBuffer { byteLength: 2 }\nsab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 }\n
\n

Using it in a WebGL buffer

\n
\n

js

\n
const canvas = document.querySelector(\"canvas\");\nconst gl = canvas.getContext(\"webgl\");\nconst buffer = gl.createBuffer();\ngl.bindBuffer(gl.ARRAY_BUFFER, buffer);\ngl.bufferData(gl.ARRAY_BUFFER, sab, gl.STATIC_DRAW);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-sharedarraybuffer-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species687979No5515.2No89796315.215.01.08.10.0
SharedArrayBuffer687979No5515.2No89796315.215.01.08.10.0
SharedArrayBuffer687979No5515.2No89796315.215.01.08.10.0
byteLength687979No5515.2No89796315.215.01.08.10.0
grow111111NoNo9716.4No111NoNo16.422.01.3320.0.0
growable111111NoNo9716.4No111NoNo16.422.01.3320.0.0
maxByteLength111111NoNo9716.4No111NoNo16.422.01.3320.0.0
slice687979No5515.2No89796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer\n

\n
\n", + "global_objects/dataview": "

DataView

The DataView view provides a low-level interface for reading and writing multiple number types in a binary ArrayBuffer, without having to care about the platform's endianness.

\n

Description

\n

Endianness

\n
\n

Multi-byte number formats are represented in memory differently depending on machine architecture — see Endianness for an explanation. DataView accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness.

\n

js

\n
const littleEndian = (() => {\n  const buffer = new ArrayBuffer(2);\n  new DataView(buffer).setInt16(0, 256, true /* littleEndian */);\n  // Int16Array uses the platform's endianness.\n  return new Int16Array(buffer)[0] === 256;\n})();\nconsole.log(littleEndian); // true or false\n
\n
\n

64-bit Integer Values

\n
\n

Some browsers don't have support for DataView.prototype.setBigInt64() and DataView.prototype.setBigUint64(). So to enable 64-bit operations in your code that will work across browsers, you could implement your own getUint64() function, to obtain values with precision up to Number.MAX_SAFE_INTEGER — which could suffice for certain cases.

\n

js

\n
function getUint64(dataview, byteOffset, littleEndian) {\n  // split 64-bit number into two 32-bit (4-byte) parts\n  const left = dataview.getUint32(byteOffset, littleEndian);\n  const right = dataview.getUint32(byteOffset + 4, littleEndian);\n\n  // combine the two 32-bit values\n  const combined = littleEndian\n    ? left + 2 ** 32 * right\n    : 2 ** 32 * left + right;\n\n  if (!Number.isSafeInteger(combined))\n    console.warn(combined, \"exceeds MAX_SAFE_INTEGER. Precision may be lost\");\n\n  return combined;\n}\n
\n

Alternatively, if you need full 64-bit range, you can create a BigInt. Further, although native BigInts are much faster than user-land library equivalents, BigInts will always be much slower than 32-bit integers in JavaScript due to the nature of their variable size.

\n

js

\n
const BigInt = window.BigInt,\n  bigThirtyTwo = BigInt(32),\n  bigZero = BigInt(0);\nfunction getUint64BigInt(dataview, byteOffset, littleEndian) {\n  // split 64-bit number into two 32-bit (4-byte) parts\n  const left = BigInt(dataview.getUint32(byteOffset | 0, !!littleEndian) >>> 0);\n  const right = BigInt(\n    dataview.getUint32(((byteOffset | 0) + 4) | 0, !!littleEndian) >>> 0,\n  );\n\n  // combine the two 32-bit values and return\n  return littleEndian\n    ? (right << bigThirtyTwo) | left\n    : (left << bigThirtyTwo) | right;\n}\n
\n
\n

Constructor

\n
DataView()

Creates a new DataView object.

Instance properties

\n
\n

These properties are defined on DataView.prototype and shared by all DataView instances.

DataView.prototype.buffer

The ArrayBuffer referenced by this view. Fixed at construction time and thus read only.

DataView.prototype.byteLength

The length (in bytes) of this view. Fixed at construction time and thus read only.

DataView.prototype.byteOffset

The offset (in bytes) of this view from the start of its ArrayBuffer. Fixed at construction time and thus read only.

DataView.prototype.constructor

The constructor function that created the instance object. For DataView instances, the initial value is the DataView constructor.

DataView.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"DataView\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
DataView.prototype.getBigInt64()

Reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit signed integer.

DataView.prototype.getBigUint64()

Reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit unsigned integer.

DataView.prototype.getFloat32()

Reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit floating point number.

DataView.prototype.getFloat64()

Reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit floating point number.

DataView.prototype.getInt16()

Reads 2 bytes starting at the specified byte offset of this DataView and interprets them as a 16-bit signed integer.

DataView.prototype.getInt32()

Reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit signed integer.

DataView.prototype.getInt8()

Reads 1 byte at the specified byte offset of this DataView and interprets it as an 8-bit signed integer.

DataView.prototype.getUint16()

Reads 2 bytes starting at the specified byte offset of this DataView and interprets them as a 16-bit unsigned integer.

DataView.prototype.getUint32()

Reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit unsigned integer.

DataView.prototype.getUint8()

Reads 1 byte at the specified byte offset of this DataView and interprets it as an 8-bit unsigned integer.

DataView.prototype.setBigInt64()

Takes a BigInt and stores it as a 64-bit signed integer in the 8 bytes starting at the specified byte offset of this DataView.

DataView.prototype.setBigUint64()

Takes a BigInt and stores it as a 64-bit unsigned integer in the 8 bytes starting at the specified byte offset of this DataView.

DataView.prototype.setFloat32()

Takes a number and stores it as a 32-bit float in the 4 bytes starting at the specified byte offset of this DataView.

DataView.prototype.setFloat64()

Takes a number and stores it as a 64-bit float in the 8 bytes starting at the specified byte offset of this DataView.

DataView.prototype.setInt16()

Takes a number and stores it as a 16-bit signed integer in the 2 bytes at the specified byte offset of this DataView.

DataView.prototype.setInt32()

Takes a number and stores it as a 32-bit signed integer in the 4 bytes at the specified byte offset of this DataView.

DataView.prototype.setInt8()

Takes a number and stores it as an 8-bit signed integer in the byte at the specified byte offset of this DataView.

DataView.prototype.setUint16()

Takes a number and stores it as a 16-bit unsigned integer in the 2 bytes at the specified byte offset of this DataView.

DataView.prototype.setUint32()

Takes a number and stores it as a 32-bit unsigned integer in the 4 bytes at the specified byte offset of this DataView.

DataView.prototype.setUint8()

Takes a number and stores it as an 8-bit unsigned integer in the byte at the specified byte offset of this DataView.

Examples

\n

Using DataView

\n
\n

js

\n
const buffer = new ArrayBuffer(16);\nconst view = new DataView(buffer, 0);\n\nview.setInt16(1, 42);\nview.getInt16(1); // 42\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DataView912151012.15.14181512.151.01.00.10.0
DataView912151012.15.14181512.151.01.00.10.0
buffer912151012.15.14181512.151.01.00.10.0
byteLength912151012.15.14181512.151.01.00.10.0
byteOffset912151012.15.14181512.151.01.00.10.0
getBigInt64677968No541567676848159.01.010.4.0
getBigUint64677968No541567676848159.01.010.4.0
getFloat32912151012.15.14181512.151.01.00.10.0
getFloat64912151012.15.14181512.151.01.00.10.0
getInt16912151012.15.14181512.151.01.00.10.0
getInt32912151012.15.14181512.151.01.00.10.0
getInt8912151012.15.14181512.151.01.00.10.0
getUint16912151012.15.14181512.151.01.00.10.0
getUint32912151012.15.14181512.151.01.00.10.0
getUint8912151012.15.14181512.151.01.00.10.0
setBigInt64677968No541567676848159.01.010.4.0
setBigUint64677968No541567676848159.01.010.4.0
setFloat32912151012.15.14181512.151.01.00.10.0
setFloat64912151012.15.14181512.151.01.00.10.0
setInt16912151012.15.14181512.151.01.00.10.0
setInt32912151012.15.14181512.151.01.00.10.0
setInt8912151012.15.14181512.151.01.00.10.0
setUint16912151012.15.14181512.151.01.00.10.0
setUint32912151012.15.14181512.151.01.00.10.0
setUint8912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\n

\n
\n", + "global_objects/atomics": "

Atomics

The Atomics namespace object contains static methods for carrying out atomic operations. They are used with SharedArrayBuffer and ArrayBuffer objects.

\n

Description

\n

Unlike most global objects, Atomics is not a constructor. You cannot use it with the new operator or invoke the Atomics object as a function. All properties and methods of Atomics are static (just like the Math object).

Atomic operations

\n

When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted.

Wait and notify

\n

The wait() and notify() methods are modeled on Linux futexes (\"fast user-space mutex\") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs.

Static properties

\n
Atomics[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Atomics\". This property is used in Object.prototype.toString().

Static methods

\n
Atomics.add()

Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index.

Atomics.and()

Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index.

Atomics.compareExchange()

Stores a value at the specified index of the array, if it equals a value. Returns the old value.

Atomics.exchange()

Stores a value at the specified index of the array. Returns the old value.

Atomics.isLockFree()

An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns true if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only.

Atomics.load()

Returns the value at the specified index of the array.

Atomics.notify()

Notifies agents that are waiting on the specified index of the array. Returns the number of agents that were notified.

Atomics.or()

Computes a bitwise OR on the value at the specified index of the array with the provided value. Returns the old value at that index.

Atomics.store()

Stores a value at the specified index of the array. Returns the value.

Atomics.sub()

Subtracts a value at the specified index of the array. Returns the old value at that index.

Atomics.wait()

Verifies that the specified index of the array still contains a value and sleeps awaiting or times out. Returns either \"ok\", \"not-equal\", or \"timed-out\". If waiting is not allowed in the calling agent then it throws an exception. (Most browsers will not allow wait() on the browser's main thread.)

Atomics.waitAsync()

Waits asynchronously (i.e. without blocking, unlike Atomics.wait) on a shared memory location and returns a Promise.

Atomics.xor()

Computes a bitwise XOR on the value at the specified index of the array with the provided value. Returns the old value at that index.

Examples

\n

Using Atomics

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\n\nta[0]; // 0\nta[0] = 5; // 5\n\nAtomics.add(ta, 0, 12); // 5\nAtomics.load(ta, 0); // 17\n\nAtomics.and(ta, 0, 1); // 17\nAtomics.load(ta, 0); // 1\n\nAtomics.compareExchange(ta, 0, 5, 12); // 1\nAtomics.load(ta, 0); // 1\n\nAtomics.exchange(ta, 0, 12); // 1\nAtomics.load(ta, 0); // 12\n\nAtomics.isLockFree(1); // true\nAtomics.isLockFree(2); // true\nAtomics.isLockFree(3); // false\nAtomics.isLockFree(4); // true\n\nAtomics.or(ta, 0, 1); // 12\nAtomics.load(ta, 0); // 13\n\nAtomics.store(ta, 0, 12); // 12\n\nAtomics.sub(ta, 0, 2); // 12\nAtomics.load(ta, 0); // 10\n\nAtomics.xor(ta, 0, 1); // 10\nAtomics.load(ta, 0); // 11\n
\n

Waiting and notifying

\n
\n

Given a shared Int32Array:

\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst int32 = new Int32Array(sab);\n
\n

A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).

\n

js

\n
Atomics.wait(int32, 0, 0);\nconsole.log(int32[0]); // 123\n
\n

A writing thread stores a new value and notifies the waiting thread once it has written:

\n

js

\n
console.log(int32[0]); // 0;\nAtomics.store(int32, 0, 123);\nAtomics.notify(int32, 0, 1);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Atomic_operations_on_non_shared_buffersNoNo79NoNoNoNoNo79NoNoNoNoNo
Atomics687978No55
15.2Before Safari 16.4, Atomics is gated behind COOP/COEP. For more detail, read Making your website \"cross-origin isolated\" using COOP and COEP.
89897963
15.2Before Safari 16.4, Atomics is gated behind COOP/COEP. For more detail, read Making your website \"cross-origin isolated\" using COOP and COEP.
15.01.08.10.0
add687978No5515.28989796315.215.01.08.10.0
and687978No5515.28989796315.215.01.08.10.0
compareExchange687978No5515.28989796315.215.01.08.10.0
exchange687978No5515.28989796315.215.01.08.10.0
isLockFree687978No5515.28989796315.215.01.08.10.0
load687978No5515.28989796315.215.01.08.10.0
notify687978No5515.28989796315.215.01.08.10.0
or687978No5515.28989796315.215.01.08.10.0
store687978No5515.28989796315.215.01.08.10.0
sub687978No5515.28989796315.215.01.08.10.0
wait687978No5515.28989796315.215.01.08.10.0
waitAsync8787NoNo7516.48989No6316.415.01.416.0.0
xor687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics\n

\n
\n", + "global_objects/json": "

JSON

The JSON namespace object contains static methods for parsing values from and converting values to JavaScript Object Notation (JSON).

\n

Description

\n

Unlike most global objects, JSON is not a constructor. You cannot use it with the new operator or invoke the JSON object as a function. All properties and methods of JSON are static (just like the Math object).

JavaScript and JSON differences

\n
\n

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is not JSON. For example:

Objects and Arrays

Property names must be double-quoted strings; trailing commas are forbidden.

Numbers

Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported.

Any JSON text is a valid JavaScript expression, but only after the JSON superset revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a SyntaxError.

Other differences include allowing only double-quoted strings and no support for undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML.

The same text may represent different values in JavaScript object literals vs. JSON as well. For more information, see Object literal syntax vs. JSON.

\n

Full JSON grammar

\n
\n

Valid JSON syntax is formally defined by the following grammar, expressed in ABNF, and copied from IETF JSON standard (RFC):

JSON-text = object / array\nbegin-array     = ws %x5B ws  ; [ left square bracket\nbegin-object    = ws %x7B ws  ; { left curly bracket\nend-array       = ws %x5D ws  ; ] right square bracket\nend-object      = ws %x7D ws  ; } right curly bracket\nname-separator  = ws %x3A ws  ; : colon\nvalue-separator = ws %x2C ws  ; , comma\nws = *(\n     %x20 /              ; Space\n     %x09 /              ; Horizontal tab\n     %x0A /              ; Line feed or New line\n     %x0D                ; Carriage return\n     )\nvalue = false / null / true / object / array / number / string\nfalse = %x66.61.6c.73.65   ; false\nnull  = %x6e.75.6c.6c      ; null\ntrue  = %x74.72.75.65      ; true\nobject = begin-object [ member *( value-separator member ) ]\n         end-object\nmember = string name-separator value\narray = begin-array [ value *( value-separator value ) ] end-array\nnumber = [ minus ] int [ frac ] [ exp ]\ndecimal-point = %x2E       ; .\ndigit1-9 = %x31-39         ; 1-9\ne = %x65 / %x45            ; e E\nexp = e [ minus / plus ] 1*DIGIT\nfrac = decimal-point 1*DIGIT\nint = zero / ( digit1-9 *DIGIT )\nminus = %x2D               ; -\nplus = %x2B                ; +\nzero = %x30                ; 0\nstring = quotation-mark *char quotation-mark\nchar = unescaped /\n    escape (\n        %x22 /          ; \"    quotation mark  U+0022\n        %x5C /          ; \\    reverse solidus U+005C\n        %x2F /          ; /    solidus         U+002F\n        %x62 /          ; b    backspace       U+0008\n        %x66 /          ; f    form feed       U+000C\n        %x6E /          ; n    line feed       U+000A\n        %x72 /          ; r    carriage return U+000D\n        %x74 /          ; t    tab             U+0009\n        %x75 4HEXDIG )  ; uXXXX                U+XXXX\nescape = %x5C              ; \\\nquotation-mark = %x22      ; \"\nunescaped = %x20-21 / %x23-5B / %x5D-10FFFF\nHEXDIG = DIGIT / %x41-46 / %x61-66   ; 0-9, A-F, or a-f\n       ; HEXDIG equivalent to HEXDIG rule in [RFC5234]\nDIGIT = %x30-39            ; 0-9\n      ; DIGIT equivalent to DIGIT rule in [RFC5234]\n

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

\n

Static properties

\n
JSON[@@toStringTag]

The initial value of the @@toStringTag property is the string \"JSON\". This property is used in Object.prototype.toString().

Static methods

\n
JSON.parse()

Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.

JSON.stringify()

Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.

Examples

\n

Example JSON

\n
\n
\n

json

\n
{\n  \"browsers\": {\n    \"firefox\": {\n      \"name\": \"Firefox\",\n      \"pref_url\": \"about:config\",\n      \"releases\": {\n        \"1\": {\n          \"release_date\": \"2004-11-09\",\n          \"status\": \"retired\",\n          \"engine\": \"Gecko\",\n          \"engine_version\": \"1.7\"\n        }\n      }\n    }\n  }\n}\n
\n

You can use the JSON.parse() method to convert the above JSON string into a JavaScript object:

\n

js

\n
const jsonText = `{\n  \"browsers\": {\n    \"firefox\": {\n      \"name\": \"Firefox\",\n      \"pref_url\": \"about:config\",\n      \"releases\": {\n        \"1\": {\n          \"release_date\": \"2004-11-09\",\n          \"status\": \"retired\",\n          \"engine\": \"Gecko\",\n          \"engine_version\": \"1.7\"\n        }\n      }\n    }\n  }\n}`;\n\nconsole.log(JSON.parse(jsonText));\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-json-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
JSON3123.5810.54≤371841141.01.00.10.0
json_superset667962No531266666247129.01.010.0.0
parse3123.5810.54≤371841141.01.00.10.0
stringify3123.5810.54≤371841141.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON\n

\n
\n", + "global_objects/weakref": "

WeakRef

A WeakRef object lets you hold a weak reference to another object, without preventing that object from getting garbage-collected.

\n

Description

\n
\n

A WeakRef object contains a weak reference to an object, which is called its target or referent. A weak reference to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or strong) reference keeps an object in memory. When an object no longer has any strong references to it, the JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore.

Because non-registered symbols are also garbage collectable, they can also be used as the target of a WeakRef object. However, the use case of this is limited.

\n

Avoid where possible

\n
\n

Correct use of WeakRef takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.

Here are some specific points included by the authors in the proposal that introduced WeakRef:

Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:

  • One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
  • Garbage collection work can be split up over time using incremental and concurrent techniques.
  • Various runtime heuristics can be used to balance memory usage, responsiveness.
  • The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
  • Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
  • Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
\n

Notes on WeakRefs

\n

Constructor

\n
WeakRef()

Creates a new WeakRef object.

Instance properties

\n
\n

These properties are defined on WeakRef.prototype and shared by all WeakRef instances.

\nWeakRef.prototype.constructor Optional\n

The constructor function that created the instance object. For WeakRef instances, the initial value is the WeakRef constructor.

Note: This property is marked as \"normative optional\" in the specification, which means a conforming implementation may not expose the constructor property. This prevents arbitrary code from obtaining the WeakRef constructor and being able to observe garbage collection. However, all major engines do expose it by default.

WeakRef.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"WeakRef\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
WeakRef.prototype.deref()

Returns the WeakRef object's target object, or undefined if the target object has been reclaimed.

Examples

\n

Using a WeakRef object

\n
\n

This example starts a counter shown in a DOM element, stopping when the element doesn't exist anymore:

\n

js

\n
class Counter {\n  constructor(element) {\n    // Remember a weak reference to the DOM element\n    this.ref = new WeakRef(element);\n    this.start();\n  }\n\n  start() {\n    if (this.timer) {\n      return;\n    }\n\n    this.count = 0;\n\n    const tick = () => {\n      // Get the element from the weak reference, if it still exists\n      const element = this.ref.deref();\n      if (element) {\n        element.textContent = ++this.count;\n      } else {\n        // The element doesn't exist anymore\n        console.log(\"The element is gone.\");\n        this.stop();\n        this.ref = null;\n      }\n    };\n\n    tick();\n    this.timer = setInterval(tick, 1000);\n  }\n\n  stop() {\n    if (this.timer) {\n      clearInterval(this.timer);\n      this.timer = 0;\n    }\n  }\n}\n\nconst counter = new Counter(document.getElementById(\"counter\"));\nsetTimeout(() => {\n  document.getElementById(\"counter\").remove();\n}, 5000);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weak-ref-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakRef848479No7014.18484796014.514.01.014.6.0
WeakRef848479No7014.18484796014.514.01.014.6.0
deref848479No7014.18484796014.514.01.014.6.0
symbol_as_target108108NoNo9416.4108108No7316.421.0NoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef\n

\n
\n", + "global_objects/finalizationregistry": "

FinalizationRegistry

A FinalizationRegistry object lets you request a callback when a value is garbage-collected.

\n

Description

\n
\n

FinalizationRegistry provides a way to request that a cleanup callback get called at some point when a value registered with the registry has been reclaimed (garbage-collected). (Cleanup callbacks are sometimes called finalizers.)

Note: Cleanup callbacks should not be used for essential program logic. See Notes on cleanup callbacks for details.

You create the registry passing in the callback:

\n

js

\n
const registry = new FinalizationRegistry((heldValue) => {\n  // …\n});\n
\n

Then you register any value you want a cleanup callback for by calling the register method, passing in the value and a held value for it:

\n

js

\n
registry.register(target, \"some value\");\n
\n

The registry does not keep a strong reference to the value, as that would defeat the purpose (if the registry held it strongly, the value would never be reclaimed). In JavaScript, objects and non-registered symbols are garbage collectable, so they can be registered in a FinalizationRegistry object as the target or the token.

If target is reclaimed, your cleanup callback may be called at some point with the held value you provided for it (\"some value\" in the above). The held value can be any value you like: a primitive or an object, even undefined. If the held value is an object, the registry keeps a strong reference to it (so it can pass it to your cleanup callback later).

If you might want to unregister a registered target value later, you pass a third value, which is the unregistration token you'll use later when calling the registry's unregister function to unregister the value. The registry only keeps a weak reference to the unregister token.

It's common to use the target value itself as the unregister token, which is just fine:

\n

js

\n
registry.register(target, \"some value\", target);\n// …\n\n// some time later, if you don't care about `target` anymore, unregister it\nregistry.unregister(target);\n
\n

It doesn't have to be the same value, though; it can be a different one:

\n

js

\n
registry.register(target, \"some value\", token);\n// …\n\n// some time later\nregistry.unregister(token);\n
\n
\n

Avoid where possible

\n
\n

Correct use of FinalizationRegistry takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.

Here are some specific points included by the authors in the proposal that introduced FinalizationRegistry:

Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:

  • One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
  • Garbage collection work can be split up over time using incremental and concurrent techniques.
  • Various runtime heuristics can be used to balance memory usage, responsiveness.
  • The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
  • Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
  • Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
\n

Notes on cleanup callbacks

\n

Constructor

\n
FinalizationRegistry()

Creates a new FinalizationRegistry object.

Instance properties

\n
\n

These properties are defined on FinalizationRegistry.prototype and shared by all FinalizationRegistry instances.

FinalizationRegistry.prototype.constructor

The constructor function that created the instance object. For FinalizationRegistry instances, the initial value is the FinalizationRegistry constructor.

FinalizationRegistry.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"FinalizationRegistry\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
FinalizationRegistry.prototype.register()

Registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected.

FinalizationRegistry.prototype.unregister()

Unregisters an object from the registry.

Examples

\n

Creating a new registry

\n
\n

You create the registry passing in the callback:

\n

js

\n
const registry = new FinalizationRegistry((heldValue) => {\n  // …\n});\n
\n
\n

Registering objects for cleanup

\n
\n

Then you register any objects you want a cleanup callback for by calling the register method, passing in the object and a held value for it:

\n

js

\n
registry.register(theObject, \"some value\");\n
\n
\n

Callbacks never called synchronously

\n
\n

No matter how much pressure you put on the garbage collector, the cleanup callback will never be called synchronously. The object may be reclaimed synchronously, but the callback will always be called sometime after the current job finishes:

\n

js

\n
let counter = 0;\nconst registry = new FinalizationRegistry(() => {\n  console.log(`Array gets garbage collected at ${counter}`);\n});\n\nregistry.register([\"foo\"]);\n\n(function allocateMemory() {\n  // Allocate 50000 functions — a lot of memory!\n  Array.from({ length: 50000 }, () => () => {});\n  if (counter > 5000) return;\n  counter++;\n  allocateMemory();\n})();\n\nconsole.log(\"Main job ends\");\n// Logs:\n// Main job ends\n// Array gets garbage collected at 5001\n
\n

However, if you allow a little break between each allocation, the callback may be called sooner:

\n

js

\n
let arrayCollected = false;\nlet counter = 0;\nconst registry = new FinalizationRegistry(() => {\n  console.log(`Array gets garbage collected at ${counter}`);\n  arrayCollected = true;\n});\n\nregistry.register([\"foo\"]);\n\n(function allocateMemory() {\n  // Allocate 50000 functions — a lot of memory!\n  Array.from({ length: 50000 }, () => () => {});\n  if (counter > 5000 || arrayCollected) return;\n  counter++;\n  // Use setTimeout to make each allocateMemory a different job\n  setTimeout(allocateMemory);\n})();\n\nconsole.log(\"Main job ends\");\n
\n

There's no guarantee that the callback will be called sooner or if it will be called at all, but there's a possibility that the logged message has a counter value smaller than 5000.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-finalization-registry-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
FinalizationRegistry848479No7014.18484796014.514.01.014.6.0
FinalizationRegistry848479No7014.18484796014.514.01.014.6.0
register848479No7014.18484796014.514.01.014.6.0
symbol_as_target108108NoNo9416.4108108No7316.421.0NoNo
unregister848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n

\n
\n", + "global_objects/iterator": "

Iterator

An Iterator object is an object that conforms to the iterator protocol by providing a next() method that returns an iterator result object. All built-in iterators inherit from the Iterator class. The Iterator class provides a @@iterator method that returns the iterator object itself, making the iterator also iterable. It also provides some helper methods for working with iterators.

\n

Description

\n
\n

The following are all built-in JavaScript iterators:

Each of these iterators have a distinct prototype object, which defines the next() method used by the particular iterator. For example, all string iterator objects inherit from a hidden object StringIteratorPrototype, which has a next() method that iterates this string by code points. StringIteratorPrototype also has a @@toStringTag property whose initial value is the string \"String Iterator\". This property is used in Object.prototype.toString(). Similarly, other iterator prototypes also have their own @@toStringTag values, which are the same as the names given above.

All of these prototype objects inherit from Iterator.prototype, which provides a @@iterator method that returns the iterator object itself, making the iterator also iterable.

\n

Iterator helpers

\n
\n

Note: These methods are iterator helpers, not iterable helpers, because the only requirement for an object to be iterable is just the presence of a @@iterator method. There is no shared prototype to install these methods on.

The Iterator class itself provides some helper methods for working with iterators. For example, you may be tempted to do the following:

\n

js

\n
const nameToDeposit = new Map([\n  [\"Anne\", 1000],\n  [\"Bert\", 1500],\n  [\"Carl\", 2000],\n]);\n\nconst totalDeposit = [...nameToDeposit.values()].reduce((a, b) => a + b);\n
\n

This first converts the iterator returned by Map.prototype.values() to an array, then uses the Array.prototype.reduce() method to calculate the sum. However, this both creates an intermediate array and iterates the array twice. Instead, you can use the reduce() method of the iterator itself:

\n

js

\n
const totalDeposit = nameToDeposit.values().reduce((a, b) => a + b);\n
\n

This method is more efficient, because it only iterates the iterator once, without memorizing any intermediate values. Iterator helper methods are necessary to work with infinite iterators:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst seq = fibonacci();\nconst firstThreeDigitTerm = seq.find((n) => n >= 100);\n
\n

You cannot convert seq to an array, because it is infinite. Instead, you can use the find() method of the iterator itself, which only iterates seq as far as necessary to find the first value that satisfies the condition.

You will find many iterator methods analogous to array methods, such as:

Iterator.prototype.drop() and Iterator.prototype.take() combined are somewhat analogous to Array.prototype.slice().

Among these methods, filter(), flatMap(), map(), drop(), and take() return a new Iterator Helper object. The iterator helper is also an Iterator instance, making the helper methods chainable. All iterator helper objects inherit from a common prototype object, which implements the iterator protocol:

next()

Calls the next() method of the underlying iterator, applies the helper method to the result, and returns the result.

return()

Calls the return() method of the underlying iterator, and returns the result.

The iterator helper shares the same data source as the underlying iterator, so iterating the iterator helper causes the underlying iterator to be iterated as well. There is no way to \"fork\" an iterator to allow it to be iterated multiple times.

\n

js

\n
const it = [1, 2, 3].values();\nconst it2 = it.drop(0); // Essentially a copy\nconsole.log(it.next().value); // 1\nconsole.log(it2.next().value); // 2\nconsole.log(it.next().value); // 3\n
\n
\n

Proper iterators

\n
\n

There are two kinds of \"iterators\": objects that conform to the iterator protocol (which, at its minimum, only requires the presence of a next() method), and objects that inherit from the Iterator class, which enjoy the helper methods. They do not entail each other — objects that inherit from Iterator do not automatically become iterators, because the Iterator class does not define a next() method. Instead, the object needs to define a next() method itself. A proper iterator is one that both conforms to the iterator protocol and inherits from Iterator, and most code expect iterators to be proper iterators and iterables to return proper iterators. To create proper iterators, define a class that extends Iterator, or use the Iterator.from() method.

\n

js

\n
class MyIterator extends Iterator {\n  next() {\n    // …\n  }\n}\n\nconst myIterator = Iterator.from({\n  next() {\n    // …\n  },\n});\n
\n
\n

Constructor

\n
\nIterator() Experimental \n

Intended to be extended by other classes that create iterators. Throws an error when constructed by itself.

Static methods

\n
\nIterator.from() Experimental \n

Creates a new Iterator object from an iterator or iterable object.

Instance properties

\n
\n

These properties are defined on Iterator.prototype and shared by all Iterator instances.

Iterator.prototype.constructor

The constructor function that created the instance object. For Iterator instances, the initial value is the Iterator constructor.

Iterator.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Iterator\". This property is used in Object.prototype.toString().

Note: Unlike the @@toStringTag on most built-in classes, Iterator.prototype[@@toStringTag] is writable for web compatibility reasons.

\n

Instance methods

\n
\nIterator.prototype.drop() Experimental \n

Returns a new iterator helper that skips the given number of elements at the start of this iterator.

\nIterator.prototype.every() Experimental \n

Tests whether all elements produced by the iterator pass the test implemented by the provided function.

\nIterator.prototype.filter() Experimental \n

Returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns true.

\nIterator.prototype.find() Experimental \n

Returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

\nIterator.prototype.flatMap() Experimental \n

Returns a new iterator helper that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).

\nIterator.prototype.forEach() Experimental \n

Executes a provided function once for each element produced by the iterator.

\nIterator.prototype.map() Experimental \n

Returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function.

\nIterator.prototype.reduce() Experimental \n

Executes a user-supplied \"reducer\" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

\nIterator.prototype.some() Experimental \n

Tests whether at least one element in the iterator passes the test implemented by the provided function. It returns a boolean value.

\nIterator.prototype.take() Experimental \n

Returns a new iterator helper that yields the given number of elements in this iterator and then terminates.

\nIterator.prototype.toArray() Experimental \n

Creates a new Array instance populated with the elements yielded from the iterator.

Iterator.prototype[@@iterator]()

Returns the iterator object itself. This allows iterator objects to also be iterable.

Examples

\n

Using an iterator as an iterable

\n
\n

All built-in iterators are also iterable, so you can use them in a for...of loop:

\n

js

\n
const arrIterator = [1, 2, 3].values();\nfor (const value of arrIterator) {\n  console.log(value);\n}\n// Logs: 1, 2, 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%iteratorprototype%-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
Iterator117117NoNo103No117117NoNoNoNoNoNo
Iterator381217No251038381725103.01.00.12.0
drop117117NoNo103No117117NoNoNoNoNoNo
every117117NoNo103No117117NoNoNoNoNoNo
filter117117NoNo103No117117NoNoNoNoNoNo
find117117NoNo103No117117NoNoNoNoNoNo
flatMap117117NoNo103No117117NoNoNoNoNoNo
forEach117117NoNo103No117117NoNoNoNoNoNo
from117117NoNo103No117117NoNoNoNoNoNo
map117117NoNo103No117117NoNoNoNoNoNo
reduce117117NoNo103No117117NoNoNoNoNoNo
some117117NoNo103No117117NoNoNoNoNoNo
take117117NoNo103No117117NoNoNoNoNoNo
toArray117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator\n

\n
\n", + "global_objects/asynciterator": "

AsyncIterator

\n

An AsyncIterator object is an object that conforms to the async iterator protocol by providing a next() method that returns a promise fulfilling to an iterator result object. The AsyncIterator.prototype object is a hidden global object that all built-in async iterators inherit from. It provides an @@asyncIterator method that returns the async iterator object itself, making the async iterator also async iterable.

Note that AsyncIterator is not a global object, although it will be in the future with the async iterator helpers proposal. The AsyncIterator.prototype object shared by all built-in async iterators can be obtained with the following code:

\n

js

\n
const AsyncIteratorPrototype = Object.getPrototypeOf(\n  Object.getPrototypeOf(Object.getPrototypeOf((async function* () {})())),\n);\n
\n
\n
\n

Description

\n
\n

Currently, the only built-in JavaScript async iterator is the AsyncGenerator object returned by async generator functions. There are some other built-in async iterators in web API, such as the one of a ReadableStream.

Each of these async iterators have a distinct prototype object, which defines the next() method used by the particular async iterator. All of these prototype objects inherit from AsyncIterator.prototype, which provides am @@asyncIterator method that returns the async iterator object itself, making the async iterator also async iterable.

Note: AsyncIterator.prototype does not implement @@iterator, so async iterators are not sync iterable by default.

\n

Instance methods

\n
AsyncIterator.prototype[@@asyncIterator]()

Returns the async iterator object itself. This allows async iterator objects to also be async iterable.

Examples

\n

Using an async iterator as an async iterable

\n
\n

All built-in async iterators are also async iterable, so you can use them in a for await...of loop:

\n

js

\n
const asyncIterator = (async function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n})();\n(async () => {\n  for await (const value of asyncIterator) {\n    console.log(value);\n  }\n})();\n// Logs: 1, 2, 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asynciteratorprototype
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@asyncIterator637957No5011.16363574611.38.01.010.0.0
AsyncIterator637957No5011.16363574611.38.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator\n

\n
\n", + "global_objects/promise": "

Promise

\n

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

To learn about the way promises work and how you can use them, we advise you to read Using promises first.

\n
\n

Description

\n
\n

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A Promise is in one of these states:

The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.

A promise is said to be settled if it is either fulfilled or rejected, but not pending.

Flowchart showing how the Promise state transitions between pending, fulfilled, and rejected via then/catch handlers. A pending promise can become either fulfilled or rejected. If fulfilled, the \"on fulfillment\" handler, or first parameter of the then() method, is executed and carries out further asynchronous actions. If rejected, the error handler, either passed as the second parameter of the then() method or as the sole parameter of the catch() method, gets executed.

You will also hear the term resolved used with promises — this means that the promise is settled or \"locked-in\" to match the eventual state of another promise, and further resolving or rejecting it has no effect. The States and fates document from the original Promise proposal contains more details about promise terminology. Colloquially, \"resolved\" promises are often equivalent to \"fulfilled\" promises, but as illustrated in \"States and fates\", resolved promises can be pending or rejected as well. For example:

\n

js

\n
new Promise((resolveOuter) => {\n  resolveOuter(\n    new Promise((resolveInner) => {\n      setTimeout(resolveInner, 1000);\n    }),\n  );\n});\n
\n

This promise is already resolved at the time when it's created (because the resolveOuter is called synchronously), but it is resolved with another promise, and therefore won't be fulfilled until 1 second later, when the inner promise fulfills. In practice, the \"resolution\" is often done behind the scenes and not observable, and only its fulfillment or rejection are.

Note: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call \"promises\", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider using a function with no arguments e.g. f = () => expression to create the lazily-evaluated expression, and f() to evaluate the expression immediately.

\n

Chained Promises

\n
\n

The methods Promise.prototype.then(), Promise.prototype.catch(), and Promise.prototype.finally() are used to associate further action with a promise that becomes settled. As these methods return promises, they can be chained.

The .then() method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each .then() returns a newly generated promise object, which can optionally be used for chaining; for example:

\n

js

\n
const myPromise = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve(\"foo\");\n  }, 300);\n});\n\nmyPromise\n  .then(handleFulfilledA, handleRejectedA)\n  .then(handleFulfilledB, handleRejectedB)\n  .then(handleFulfilledC, handleRejectedC);\n
\n

Processing continues to the next link of the chain even when a .then() lacks a callback function. Therefore, a chain can safely omit every rejection callback function until the final .catch().

Handling a rejected promise in each .then() has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. In such cases we must throw an error of some type to maintain error state down the chain. On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement. A .catch() is really just a .then() without a slot for a callback function for the case when the promise is fulfilled.

\n

js

\n
myPromise\n  .then(handleFulfilledA)\n  .then(handleFulfilledB)\n  .then(handleFulfilledC)\n  .catch(handleRejectedAny);\n
\n

Using arrow functions for the callback functions, implementation of the promise chain might look something like this:

\n

js

\n
myPromise\n  .then((value) => `${value} and bar`)\n  .then((value) => `${value} and bar again`)\n  .then((value) => `${value} and again`)\n  .then((value) => `${value} and again`)\n  .then((value) => {\n    console.log(value);\n  })\n  .catch((err) => {\n    console.error(err);\n  });\n
\n

Note: For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence.

The termination condition of a promise determines the \"settled\" state of the next promise in the chain. A \"fulfilled\" state indicates a successful completion of the promise, while a \"rejected\" state indicates a lack of success. The return value of each fulfilled promise in the chain is passed along to the next .then(), while the reason for rejection is passed along to the next rejection-handler function in the chain.

The promises of a chain are nested in one another, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop.

(promise D, (promise C, (promise B, (promise A) ) ) )\n

When a nextValue is a promise, the effect is a dynamic replacement. The return causes a promise to be popped, but the nextValue promise is pushed into its place. For the nesting shown above, suppose the .then() associated with \"promise B\" returns a nextValue of \"promise X\". The resulting nesting would look like this:

(promise D, (promise C, (promise X) ) )\n

A promise can participate in more than one nesting. For the following code, the transition of promiseA into a \"settled\" state will cause both instances of .then() to be invoked.

\n

js

\n
const promiseA = new Promise(myExecutorFunc);\nconst promiseB = promiseA.then(handleFulfilled1, handleRejected1);\nconst promiseC = promiseA.then(handleFulfilled2, handleRejected2);\n
\n

An action can be assigned to an already \"settled\" promise. In that case, the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed to be asynchronous. Therefore, an action for an already \"settled\" promise will occur only after the stack has cleared and a clock-tick has passed. The effect is much like that of setTimeout(action, 0).

\n

js

\n
const promiseA = new Promise((resolve, reject) => {\n  resolve(777);\n});\n// At this point, \"promiseA\" is already settled.\npromiseA.then((val) => console.log(\"asynchronous logging has val:\", val));\nconsole.log(\"immediate logging\");\n\n// produces output in this order:\n// immediate logging\n// asynchronous logging has val: 777\n
\n
\n

Thenables

\n
\n

The JavaScript ecosystem had made multiple Promise implementations long before it became part of the language. Despite being represented differently internally, at the minimum, all Promise-like objects implement the Thenable interface. A thenable implements the .then() method, which is called with two callbacks: one for when the promise is fulfilled, one for when it's rejected. Promises are thenables as well.

To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example, Promise.resolve will not only resolve promises, but also trace thenables.

\n

js

\n
const aThenable = {\n  then(onFulfilled, onRejected) {\n    onFulfilled({\n      // The thenable is fulfilled with another thenable\n      then(onFulfilled, onRejected) {\n        onFulfilled(42);\n      },\n    });\n  },\n};\n\nPromise.resolve(aThenable); // A promise fulfilled with 42\n
\n
\n

Promise concurrency

\n
\n

The Promise class offers four static methods to facilitate async task concurrency:

Promise.all()

Fulfills when all of the promises fulfill; rejects when any of the promises rejects.

Promise.allSettled()

Fulfills when all promises settle.

Promise.any()

Fulfills when any of the promises fulfills; rejects when all of the promises reject.

Promise.race()

Settles when any of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.

All these methods take an iterable of promises (thenables, to be exact) and return a new promise. They all support subclassing, which means they can be called on subclasses of Promise, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the Promise() constructor — accepting a single executor function that can be called with the resolve and reject callbacks as parameters. The subclass must also have a resolve static method that can be called like Promise.resolve() to resolve values to promises.

Note that JavaScript is single-threaded by nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent. Parallel execution in JavaScript can only be achieved through worker threads.

\n

Constructor

\n
Promise()

Creates a new Promise object. The constructor is primarily used to wrap functions that do not already support promises.

Static properties

\n
Promise[@@species]

Returns the constructor used to construct return values from promise methods.

Static methods

\n
Promise.all()

Takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises reject, with this first rejection reason.

Promise.allSettled()

Takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Promise.any()

Takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when any of the input's promises fulfill, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an AggregateError containing an array of rejection reasons.

Promise.race()

Takes an iterable of promises as input and returns a single Promise. This returned promise settles with the eventual state of the first promise that settles.

Promise.reject()

Returns a new Promise object that is rejected with the given reason.

Promise.resolve()

Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will \"follow\" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

Instance properties

\n
\n

These properties are defined on Promise.prototype and shared by all Promise instances.

Promise.prototype.constructor

The constructor function that created the instance object. For Promise instances, the initial value is the Promise constructor.

Promise.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Promise\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Promise.prototype.catch()

Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.

Promise.prototype.finally()

Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.

Promise.prototype.then()

Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler onFulfilled or onRejected is not a function).

Examples

\n

Basic Example

\n
\n

js

\n
const myFirstPromise = new Promise((resolve, reject) => {\n  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.\n  // In this example, we use setTimeout(...) to simulate async code.\n  // In reality, you will probably be using something like XHR or an HTML API.\n  setTimeout(() => {\n    resolve(\"Success!\"); // Yay! Everything went well!\n  }, 250);\n});\n\nmyFirstPromise.then((successMessage) => {\n  // successMessage is whatever we passed in the resolve(...) function above.\n  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.\n  console.log(`Yay! ${successMessage}`);\n});\n
\n

Example with diverse situations

\n
\n

This example shows diverse techniques for using Promise capabilities and diverse situations that can occur. To understand this, start by scrolling to the bottom of the code block, and examine the promise chain. Upon provision of an initial promise, a chain of promises can follow. The chain is composed of .then() calls, and typically (but not necessarily) has a single .catch() at the end, optionally followed by .finally(). In this example, the promise chain is initiated by a custom-written new Promise() construct; but in actual practice, promise chains more typically start with an API function (written by someone else) that returns a promise.

The example function tetheredGetNumber() shows that a promise generator will utilize reject() while setting up an asynchronous call, or within the call-back, or both. The function promiseGetWord() illustrates how an API function might generate and return a promise in a self-contained manner.

Note that the function troubleWithGetNumber() ends with a throw. That is forced because a promise chain goes through all the .then() promises, even after an error, and without the throw, the error would seem \"fixed\". This is a hassle, and for this reason, it is common to omit onRejected throughout the chain of .then() promises, and just have a single onRejected in the final catch().

This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the threshold values.

\n

js

\n
// To experiment with error handling, \"threshold\" values cause errors randomly\nconst THRESHOLD_A = 8; // can use zero 0 to guarantee error\n\nfunction tetheredGetNumber(resolve, reject) {\n  setTimeout(() => {\n    const randomInt = Date.now();\n    const value = randomInt % 10;\n    if (value < THRESHOLD_A) {\n      resolve(value);\n    } else {\n      reject(`Too large: ${value}`);\n    }\n  }, 500);\n}\n\nfunction determineParity(value) {\n  const isOdd = value % 2 === 1;\n  return { value, isOdd };\n}\n\nfunction troubleWithGetNumber(reason) {\n  const err = new Error(\"Trouble getting number\", { cause: reason });\n  console.error(err);\n  throw err;\n}\n\nfunction promiseGetWord(parityInfo) {\n  return new Promise((resolve, reject) => {\n    const { value, isOdd } = parityInfo;\n    if (value >= THRESHOLD_A - 1) {\n      reject(`Still too large: ${value}`);\n    } else {\n      parityInfo.wordEvenOdd = isOdd ? \"odd\" : \"even\";\n      resolve(parityInfo);\n    }\n  });\n}\n\nnew Promise(tetheredGetNumber)\n  .then(determineParity, troubleWithGetNumber)\n  .then(promiseGetWord)\n  .then((info) => {\n    console.log(`Got: ${info.value}, ${info.wordEvenOdd}`);\n    return info;\n  })\n  .catch((reason) => {\n    if (reason.cause) {\n      console.error(\"Had previously handled error\");\n    } else {\n      console.error(`Trouble with promiseGetWord(): ${reason}`);\n    }\n  })\n  .finally((info) => console.log(\"All done\"));\n
\n
\n

Advanced Example

\n
\n

This small example shows the mechanism of a Promise. The testPromise() method is called each time the <button> is clicked. It creates a promise that will be fulfilled, using setTimeout(), to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

The fulfillment of the promise is logged, via a fulfill callback set using p1.then(). A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.

By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.

HTML

\n

html

\n
<button id=\"make-promise\">Make a promise!</button>\n<div id=\"log\"></div>\n
\n

JavaScript

\n

js

\n
\"use strict\";\n\nlet promiseCount = 0;\n\nfunction testPromise() {\n  const thisPromiseCount = ++promiseCount;\n  const log = document.getElementById(\"log\");\n  // begin\n  log.insertAdjacentHTML(\"beforeend\", `${thisPromiseCount}) Started<br>`);\n  // We make a new promise: we promise a numeric count of this promise,\n  // starting from 1 (after waiting 3s)\n  const p1 = new Promise((resolve, reject) => {\n    // The executor function is called with the ability\n    // to resolve or reject the promise\n    log.insertAdjacentHTML(\n      \"beforeend\",\n      `${thisPromiseCount}) Promise constructor<br>`,\n    );\n    // This is only an example to create asynchronism\n    setTimeout(\n      () => {\n        // We fulfill the promise\n        resolve(thisPromiseCount);\n      },\n      Math.random() * 2000 + 1000,\n    );\n  });\n\n  // We define what to do when the promise is resolved with the then() call,\n  // and what to do when the promise is rejected with the catch() call\n  p1.then((val) => {\n    // Log the fulfillment value\n    log.insertAdjacentHTML(\"beforeend\", `${val}) Promise fulfilled<br>`);\n  }).catch((reason) => {\n    // Log the rejection reason\n    console.log(`Handle rejected promise (${reason}) here.`);\n  });\n  // end\n  log.insertAdjacentHTML(\"beforeend\", `${thisPromiseCount}) Promise made<br>`);\n}\n\nconst btn = document.getElementById(\"make-promise\");\nbtn.addEventListener(\"click\", testPromise);\n
\n

Result

\n
\n\n\n
\n

Loading an image with XHR

\n

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented on and allows you to follow the Promise and XHR architecture closely.

Incumbent settings object tracking

\n
\n

A settings object is an environment that provides additional information when JavaScript code is running. This includes the realm and module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one to use for a given piece of user code.

To better picture this, we can take a closer look at how the realm might be an issue. A realm can be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects like Array and Error. Each settings object has its own \"copy\" of these and they are not shared. That can cause some unexpected behavior in relation to promises. In order to get around this, we track something called the incumbent settings object. This represents information specific to the context of the user code responsible for a certain function call.

To illustrate this a bit further we can take a look at how an <iframe> embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers:

\n

html

\n
<!doctype html> <iframe></iframe>\n<!-- we have a realm here -->\n<script>\n  // we have a realm here as well\n  const bound = frames[0].postMessage.bind(frames[0], \"some data\", \"*\");\n  // bound is a built-in function — there is no user\n  // code on the stack, so which realm do we use?\n  setTimeout(bound);\n  // this still works, because we use the youngest\n  // realm (the incumbent) on the stack\n</script>\n
\n

The same concept applies to promises. If we modify the above example a little bit, we get this:

\n

html

\n
<!doctype html> <iframe></iframe>\n<!-- we have a realm here -->\n<script>\n  // we have a realm here as well\n  const bound = frames[0].postMessage.bind(frames[0], \"some data\", \"*\");\n  // bound is a built in function — there is no user\n  // code on the stack — which realm do we use?\n  Promise.resolve(undefined).then(bound);\n  // this still works, because we use the youngest\n  // realm (the incumbent) on the stack\n</script>\n
\n

If we change this so that the <iframe> in the document is listening to post messages, we can observe the effect of the incumbent settings object:

\n

html

\n
<!-- y.html -->\n<!doctype html>\n<iframe src=\"x.html\"></iframe>\n<script>\n  const bound = frames[0].postMessage.bind(frames[0], \"some data\", \"*\");\n  Promise.resolve(undefined).then(bound);\n</script>\n
\n
\n

html

\n
<!-- x.html -->\n<!doctype html>\n<script>\n  window.addEventListener(\n    \"message\",\n    (event) => {\n      document.querySelector(\"#text\").textContent = \"hello\";\n      // this code will only run in browsers that track the incumbent settings object\n      console.log(event);\n    },\n    false,\n  );\n</script>\n
\n

In the above example, the inner text of the <iframe> will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message.

Note: Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species517948No381051514841105.01.06.5.0
Promise3212
29Constructor requires a new operator since version 37.
No19
8Constructor requires a new operator since version 10.
4.4.332
29Constructor requires a new operator since version 37.
19
8Constructor requires a new operator since version 10.
2.01.0
0.12.0Constructor requires a new operator since version 4.
Promise321229No1984.4.332291982.01.00.12.0
all321229No1984.4.332291982.01.00.12.0
allSettled767971No6313767679541312.01.012.9.0
any858579No7114858579601414.01.215.0.0
catch321229No1984.4.332291982.01.00.12.0
finally631858No5011.16363584611.38.01.010.0.0
incumbent_settings_object_trackingNoNo50NoNoNoNoNo50NoNoNoNoNo
race321229No1984.4.332291982.01.00.12.0
reject321229No1984.4.332291982.01.00.12.0
resolve321229No1984.4.332291982.01.00.12.0
then321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\n

\n
\n", + "global_objects/generatorfunction": "

GeneratorFunction

\n

The GeneratorFunction object provides methods for generator functions. In JavaScript, every generator function is actually a GeneratorFunction object.

Note that GeneratorFunction is not a global object. It can be obtained with the following code:

\n

js

\n
const GeneratorFunction = function* () {}.constructor;\n
\n

GeneratorFunction is a subclass of Function.

\n
\n

Try it

\n

Constructor

\n
GeneratorFunction()

Creates a new GeneratorFunction object.

Instance properties

\n
\n

Also inherits instance properties from its parent Function.

These properties are defined on GeneratorFunction.prototype and shared by all GeneratorFunction instances.

GeneratorFunction.prototype.constructor

The constructor function that created the instance object. For GeneratorFunction instances, the initial value is the GeneratorFunction constructor.

GeneratorFunction.prototype.prototype

All generator functions share the same prototype property, which is Generator.prototype. Each generator function instance also has its own prototype property. When the generator function is called, the returned generator object inherits from the generator function's prototype property, which in turn inherits from GeneratorFunction.prototype.prototype.

GeneratorFunction.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"GeneratorFunction\". This property is used in Object.prototype.toString().

\n

Instance methods

\n

Inherits instance methods from its parent Function.

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generatorfunction-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
GeneratorFunction391326No261039392626104.01.04.0.0
GeneratorFunction391326No261039392626104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction\n

\n
\n", + "global_objects/asyncgeneratorfunction": "

AsyncGeneratorFunction

\n

The AsyncGeneratorFunction object provides methods for async generator functions. In JavaScript, every async generator function is actually an AsyncGeneratorFunction object.

Note that AsyncGeneratorFunction is not a global object. It can be obtained with the following code:

\n

js

\n
const AsyncGeneratorFunction = async function* () {}.constructor;\n
\n

AsyncGeneratorFunction is a subclass of Function.

\n
\n

Try it

\n

Constructor

\n
AsyncGeneratorFunction()

Creates a new AsyncGeneratorFunction object.

Instance properties

\n
\n

Also inherits instance properties from its parent Function.

These properties are defined on AsyncGeneratorFunction.prototype and shared by all AsyncGeneratorFunction instances.

AsyncGeneratorFunction.prototype.constructor

The constructor function that created the instance object. For AsyncGeneratorFunction instances, the initial value is the AsyncGeneratorFunction constructor.

AsyncGeneratorFunction.prototype.prototype

All async generator functions share the same prototype property, which is AsyncGenerator.prototype. Each async generator function instance also has its own prototype property. When the async generator function is called, the returned async generator object inherits from the async generator function's prototype property, which in turn inherits from AsyncGeneratorFunction.prototype.prototype.

AsyncGeneratorFunction.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"AsyncGeneratorFunction\". This property is used in Object.prototype.toString().

\n

Instance methods

\n

Inherits instance methods from its parent Function.

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgeneratorfunction-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AsyncGeneratorFunction637955No501263635546128.01.010.0.0
AsyncGeneratorFunction637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction\n

\n
\n", + "global_objects/generator": "

Generator

\n

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Generator is a subclass of the hidden Iterator class.

\n
\n

Try it

\n

Constructor

\n
\n

The Generator constructor is not available globally. Instances of Generator must be returned from generator functions:

\n

js

\n
function* generator() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst gen = generator(); // \"Generator { }\"\n\nconsole.log(gen.next().value); // 1\nconsole.log(gen.next().value); // 2\nconsole.log(gen.next().value); // 3\n
\n

In fact, there's no JavaScript entity that corresponds to the Generator constructor. There's only a hidden object which is the prototype object shared by all objects created by generator functions. This object is often stylized as Generator.prototype to make it look like a class, but it should be more appropriately called GeneratorFunction.prototype.prototype, because GeneratorFunction is an actual JavaScript entity.

\n

Instance properties

\n
\n

These properties are defined on Generator.prototype and shared by all Generator instances.

Generator.prototype.constructor

The constructor function that created the instance object. For Generator instances, the initial value is GeneratorFunction.prototype.

Note: Generator objects do not store a reference to the generator function that created them.

Generator.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Generator\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
\n

Also inherits instance methods from its parent Iterator.

Generator.prototype.next()

Returns a value yielded by the yield expression.

Generator.prototype.return()

Acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.

Generator.prototype.throw()

Acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

\n

Examples

\n

An infinite iterator

\n
\n

With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.

\n

js

\n
function* infinite() {\n  let index = 0;\n\n  while (true) {\n    yield index++;\n  }\n}\n\nconst generator = infinite(); // \"Generator { }\"\n\nconsole.log(generator.next().value); // 0\nconsole.log(generator.next().value); // 1\nconsole.log(generator.next().value); // 2\n// …\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Generator391326No261039392626104.01.04.0.0
next391326No261039392626104.01.04.0.0
return501338No371050503837105.01.06.0.0
throw391326No261039392626104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator\n

\n
\n", + "global_objects/asyncgenerator": "

AsyncGenerator

\n

The AsyncGenerator object is returned by an async generator function and it conforms to both the async iterable protocol and the async iterator protocol.

Async generator methods always yield Promise objects.

AsyncGenerator is a subclass of the hidden AsyncIterator class.

\n
\n

Try it

\n

Constructor

\n
\n

The AsyncGenerator constructor is not available globally. Instances of AsyncGenerator must be returned from async generator functions

\n

js

\n
async function* createAsyncGenerator() {\n  yield await Promise.resolve(1);\n  yield await Promise.resolve(2);\n  yield await Promise.resolve(3);\n}\nconst asyncGen = createAsyncGenerator();\nasyncGen.next().then((res) => console.log(res.value)); // 1\nasyncGen.next().then((res) => console.log(res.value)); // 2\nasyncGen.next().then((res) => console.log(res.value)); // 3\n
\n

In fact, there's no JavaScript entity that corresponds to the AsyncGenerator constructor. There's only a hidden object which is the prototype object shared by all objects created by async generator functions. This object is often stylized as AsyncGenerator.prototype to make it look like a class, but it should be more appropriately called AsyncGeneratorFunction.prototype.prototype, because AsyncGeneratorFunction is an actual JavaScript entity.

\n

Instance properties

\n
\n

These properties are defined on AsyncGenerator.prototype and shared by all AsyncGenerator instances.

AsyncGenerator.prototype.constructor

The constructor function that created the instance object. For AsyncGenerator instances, the initial value is AsyncGeneratorFunction.prototype.

Note: AsyncGenerator objects do not store a reference to the async generator function that created them.

AsyncGenerator.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"AsyncGenerator\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
\n

Also inherits instance methods from its parent AsyncIterator.

AsyncGenerator.prototype.next()

Returns a Promise which will be resolved with the given value yielded by the yield expression.

AsyncGenerator.prototype.return()

Acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.

AsyncGenerator.prototype.throw()

Acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

\n

Examples

\n

Async generator iteration

\n
\n

The following example iterates over an async generator, logging values 1–6 to the console at decreasing time intervals. Notice how each time a Promise is yielded, but it's automatically resolved within the for await...of loop.

\n

js

\n
// An async task. Pretend it's doing something more useful\n// in practice.\nfunction delayedValue(time, value) {\n  return new Promise((resolve /*, reject*/) => {\n    setTimeout(() => resolve(value), time);\n  });\n}\n\nasync function* generate() {\n  yield delayedValue(2000, 1);\n  yield delayedValue(100, 2);\n  yield delayedValue(500, 3);\n  yield delayedValue(250, 4);\n  yield delayedValue(125, 5);\n  yield delayedValue(50, 6);\n  console.log(\"All done!\");\n}\n\nasync function main() {\n  for await (const value of generate()) {\n    console.log(\"value\", value);\n  }\n}\n\nmain().catch((e) => console.error(e));\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgenerator-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AsyncGenerator637955No501263635546128.01.010.0.0
next637955No501263635546128.01.010.0.0
return637955No501263635546128.01.010.0.0
throw637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator\n

\n
\n", + "global_objects/asyncfunction": "

AsyncFunction

\n

The AsyncFunction object provides methods for async functions. In JavaScript, every async function is actually an AsyncFunction object.

Note that AsyncFunction is not a global object. It can be obtained with the following code:

\n

js

\n
const AsyncFunction = async function () {}.constructor;\n
\n

AsyncFunction is a subclass of Function.

\n
\n

Constructor

\n
AsyncFunction()

Creates a new AsyncFunction object.

Instance properties

\n
\n

Also inherits instance properties from its parent Function.

These properties are defined on AsyncFunction.prototype and shared by all AsyncFunction instances.

AsyncFunction.prototype.constructor

The constructor function that created the instance object. For AsyncFunction instances, the initial value is the AsyncFunction constructor.

AsyncFunction.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"AsyncFunction\". This property is used in Object.prototype.toString().

Note: AsyncFunction instances do not have the prototype property.

\n

Instance methods

\n

Inherits instance methods from its parent Function.

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-function-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AsyncFunction551552No4210.15555524210.36.01.07.6.0
AsyncFunction551552No4210.15555524210.36.01.07.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction\n

\n
\n", + "global_objects/reflect": "

Reflect

The Reflect namespace object contains static methods for invoking interceptable JavaScript object internal methods. The methods are the same as those of proxy handlers.

\n

Description

\n
\n

Unlike most global objects, Reflect is not a constructor. You cannot use it with the new operator or invoke the Reflect object as a function. All properties and methods of Reflect are static (just like the Math object).

The Reflect object provides a collection of static functions which have the same names as the proxy handler methods.

The major use case of Reflect is to provide default forwarding behavior in Proxy handler traps. A trap is used to intercept an operation on an object — it provides a custom implementation for an object internal method. The Reflect API is used to invoke the corresponding internal method. For example, the code below creates a proxy p with a deleteProperty trap that intercepts the [[Delete]] internal method. Reflect.deleteProperty() is used to invoke the default [[Delete]] behavior on targetObject directly. You can replace it with delete, but using Reflect saves you from having to remember the syntax that each internal method corresponds to.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    deleteProperty(targetObject, property) {\n      // Custom functionality: log the deletion\n      console.log(\"Deleting property:\", property);\n\n      // Execute the default introspection behavior\n      return Reflect.deleteProperty(targetObject, property);\n    },\n  },\n);\n
\n

The Reflect methods also allow finer control of how the internal method is invoked. For example, Reflect.construct() is the only way to construct a target function with a specific new.target value. If you use the new operator to invoke a function, the new.target value is always the function itself. This has important effects with subclassing. For another example, Reflect.get() allows you to run a getter with a custom this value, while property accessors always use the current object as the this value.

Nearly every Reflect method's behavior can be done with some other syntax or method. Some of these methods have corresponding static methods of the same name on Object, although they do have some subtle differences. For the exact differences, see the description for each Reflect method.

\n

Static properties

\n
Reflect[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Reflect\". This property is used in Object.prototype.toString().

Static methods

\n
Reflect.apply()

Calls a target function with arguments as specified by the argumentsList parameter. See also Function.prototype.apply().

Reflect.construct()

The new operator as a function. Equivalent to calling new target(...argumentsList). Also provides the option to specify a different prototype.

Reflect.defineProperty()

Similar to Object.defineProperty(). Returns a boolean that is true if the property was successfully defined.

Reflect.deleteProperty()

The delete operator as a function. Equivalent to calling delete target[propertyKey].

Reflect.get()

Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function.

Reflect.getOwnPropertyDescriptor()

Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object, undefined otherwise.

Reflect.getPrototypeOf()

Same as Object.getPrototypeOf().

Reflect.has()

Returns a boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function.

Reflect.isExtensible()

Same as Object.isExtensible(). Returns a boolean that is true if the target is extensible.

Reflect.ownKeys()

Returns an array of the target object's own (not inherited) property keys.

Reflect.preventExtensions()

Similar to Object.preventExtensions(). Returns a boolean that is true if the update was successful.

Reflect.set()

A function that assigns values to properties. Returns a boolean that is true if the update was successful.

Reflect.setPrototypeOf()

A function that sets the prototype of an object. Returns a boolean that is true if the update was successful.

Examples

\n

Detecting whether an object contains certain properties

\n
\n

js

\n
const duck = {\n  name: \"Maurice\",\n  color: \"white\",\n  greeting() {\n    console.log(`Quaaaack! My name is ${this.name}`);\n  },\n};\n\nReflect.has(duck, \"color\");\n// true\nReflect.has(duck, \"haircut\");\n// false\n
\n

Returning the object's own keys

\n
\n

js

\n
Reflect.ownKeys(duck);\n// [ \"name\", \"color\", \"greeting\" ]\n
\n

Adding a new property to the object

\n
\n

js

\n
Reflect.set(duck, \"eyes\", \"black\");\n// returns \"true\" if successful\n// \"duck\" now contains the property \"eyes: 'black'\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Reflect491242No361049494236105.01.06.0.0
apply491242No361049494236105.01.06.0.0
construct491242No361049494236105.01.06.0.0
defineProperty491242No361049494236105.01.06.0.0
deleteProperty491242No361049494236105.01.06.0.0
get491242No361049494236105.01.06.0.0
getOwnPropertyDescriptor491242No361049494236105.01.06.0.0
getPrototypeOf491242No361049494236105.01.06.0.0
has491242No361049494236105.01.06.0.0
isExtensible491242No361049494236105.01.06.0.0
ownKeys491242No361049494236105.01.06.0.0
preventExtensions491242No361049494236105.01.06.0.0
set491242No361049494236105.01.06.0.0
setPrototypeOf491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect\n

\n
\n", + "global_objects/proxy": "

Proxy

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

\n

Description

\n
\n

The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.

You create a Proxy with two parameters:

For example, this code creates a proxy for the target object.

\n

js

\n
const target = {\n  message1: \"hello\",\n  message2: \"everyone\",\n};\n\nconst handler1 = {};\n\nconst proxy1 = new Proxy(target, handler1);\n
\n

Because the handler is empty, this proxy behaves just like the original target:

\n

js

\n
console.log(proxy1.message1); // hello\nconsole.log(proxy1.message2); // everyone\n
\n

To customize the proxy, we define functions on the handler object:

\n

js

\n
const target = {\n  message1: \"hello\",\n  message2: \"everyone\",\n};\n\nconst handler2 = {\n  get(target, prop, receiver) {\n    return \"world\";\n  },\n};\n\nconst proxy2 = new Proxy(target, handler2);\n
\n

Here we've provided an implementation of the get() handler, which intercepts attempts to access properties in the target.

Handler functions are sometimes called traps, presumably because they trap calls to the target object. The very simple trap in handler2 above redefines all property accessors:

\n

js

\n
console.log(proxy2.message1); // world\nconsole.log(proxy2.message2); // world\n
\n

Proxies are often used with the Reflect object, which provides some methods with the same names as the Proxy traps. The Reflect methods provide the reflective semantics for invoking the corresponding object internal methods. For example, we can call Reflect.get if we don't wish to redefine the object's behavior:

\n

js

\n
const target = {\n  message1: \"hello\",\n  message2: \"everyone\",\n};\n\nconst handler3 = {\n  get(target, prop, receiver) {\n    if (prop === \"message2\") {\n      return \"world\";\n    }\n    return Reflect.get(...arguments);\n  },\n};\n\nconst proxy3 = new Proxy(target, handler3);\n\nconsole.log(proxy3.message1); // hello\nconsole.log(proxy3.message2); // world\n
\n

The Reflect method still interacts with the object through object internal methods — it doesn't \"de-proxify\" the proxy if it's invoked on a proxy. If you use Reflect methods within a proxy trap, and the Reflect method call gets intercepted by the trap again, there may be infinite recursion.

\n

Terminology

\n
\n

The following terms are used when talking about the functionality of proxies.

handler

The object passed as the second argument to the Proxy constructor. It contains the traps which define the behavior of the proxy.

trap

The function that define the behavior for the corresponding object internal method. (This is analogous to the concept of traps in operating systems.)

target

Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.

invariants

Semantics that remain unchanged when implementing custom operations. If your trap implementation violates the invariants of a handler, a TypeError will be thrown.

\n

Object internal methods

\n
\n

Objects are collections of properties. However, the language doesn't provide any machinery to directly manipulate data stored in the object — rather, the object defines some internal methods specifying how it can be interacted with. For example, when you read obj.x, you may expect the following to happen:

There isn't anything special about this process in the language — it's just because ordinary objects, by default, have a [[Get]] internal method that is defined with this behavior. The obj.x property access syntax simply invokes the [[Get]] method on the object, and the object uses its own internal method implementation to determine what to return.

As another example, arrays differ from normal objects, because they have a magic length property that, when modified, automatically allocates empty slots or removes elements from the array. Similarly, adding array elements automatically changes the length property. This is because arrays have a [[DefineOwnProperty]] internal method that knows to update length when an integer index is written to, or update the array contents when length is written to. Such objects whose internal methods have different implementations from ordinary objects are called exotic objects. Proxy enable developers to define their own exotic objects with full capacity.

All objects have the following internal methods:

Internal method Corresponding trap
[[GetPrototypeOf]] getPrototypeOf()
[[SetPrototypeOf]] setPrototypeOf()
[[IsExtensible]] isExtensible()
[[PreventExtensions]] preventExtensions()
[[GetOwnProperty]] getOwnPropertyDescriptor()
[[DefineOwnProperty]] defineProperty()
[[HasProperty]] has()
[[Get]] get()
[[Set]] set()
[[Delete]] deleteProperty()
[[OwnPropertyKeys]] ownKeys()

Function objects also have the following internal methods:

Internal method Corresponding trap
[[Call]] apply()
[[Construct]] construct()

It's important to realize that all interactions with an object eventually boils down to the invocation of one of these internal methods, and that they are all customizable through proxies. This means almost no behavior (except certain critical invariants) is guaranteed in the language — everything is defined by the object itself. When you run delete obj.x, there's no guarantee that \"x\" in obj returns false afterwards — it depends on the object's implementations of [[Delete]] and [[HasProperty]]. A delete obj.x may log things to the console, modify some global state, or even define a new property instead of deleting the existing one, although these semantics should be avoided in your own code.

All internal methods are called by the language itself, and are not directly accessible in JavaScript code. The Reflect namespace offers methods that do little more than call the internal methods, besides some input normalization/validation. In each trap's page, we list several typical situations when the trap is invoked, but these internal methods are called in a lot of places. For example, array methods read and write to array through these internal methods, so methods like push() would also invoke get() and set() traps.

Most of the internal methods are straightforward in what they do. The only two that may be confusable are [[Set]] and [[DefineOwnProperty]]. For normal objects, the former invokes setters; the latter doesn't. (And [[Set]] calls [[DefineOwnProperty]] internally if there's no existing property or the property is a data property.) While you may know that the obj.x = 1 syntax uses [[Set]], and Object.defineProperty() uses [[DefineOwnProperty]], it's not immediately apparent what semantics other built-in methods and syntaxes use. For example, class fields use the [[DefineOwnProperty]] semantic, which is why setters defined in the superclass are not invoked when a field is declared on the derived class.

\n

Constructor

\n
\n
Proxy()

Creates a new Proxy object.

Note: There's no Proxy.prototype property, so Proxy instances do not have any special properties or methods.

\n

Static methods

\n
Proxy.revocable()

Creates a revocable Proxy object.

Examples

\n

Basic example

\n
\n

In this simple example, the number 37 gets returned as the default value when the property name is not in the object. It is using the get() handler.

\n

js

\n
const handler = {\n  get(obj, prop) {\n    return prop in obj ? obj[prop] : 37;\n  },\n};\n\nconst p = new Proxy({}, handler);\np.a = 1;\np.b = undefined;\n\nconsole.log(p.a, p.b); // 1, undefined\n\nconsole.log(\"c\" in p, p.c); // false, 37\n
\n
\n

No-op forwarding proxy

\n
\n

In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.

\n

js

\n
const target = {};\nconst p = new Proxy(target, {});\n\np.a = 37; // Operation forwarded to the target\n\nconsole.log(target.a); // 37 (The operation has been properly forwarded!)\n
\n

Note that while this \"no-op\" works for plain JavaScript objects, it does not work for native objects, such as DOM elements, Map objects, or anything that has internal slots. See no private property forwarding for more information.

\n

No private property forwarding

\n
\n

A proxy is still another object with a different identity — it's a proxy that operates between the wrapped object and the outside. As such, the proxy does not have direct access to the original object's private properties.

\n

js

\n
class Secret {\n  #secret;\n  constructor(secret) {\n    this.#secret = secret;\n  }\n  get secret() {\n    return this.#secret.replace(/\\d+/, \"[REDACTED]\");\n  }\n}\n\nconst aSecret = new Secret(\"123456\");\nconsole.log(aSecret.secret); // [REDACTED]\n// Looks like a no-op forwarding...\nconst proxy = new Proxy(aSecret, {});\nconsole.log(proxy.secret); // TypeError: Cannot read private member #secret from an object whose class did not declare it\n
\n

This is because when the proxy's get trap is invoked, the this value is the proxy instead of the original secret, so #secret is not accessible. To fix this, use the original secret as this:

\n

js

\n
const proxy = new Proxy(aSecret, {\n  get(target, prop, receiver) {\n    // By default, it looks like Reflect.get(target, prop, receiver)\n    // which has a different value of `this`\n    return target[prop];\n  },\n});\nconsole.log(proxy.secret);\n
\n

For methods, this means you have to redirect the method's this value to the original object as well:

\n

js

\n
class Secret {\n  #x = 1;\n  x() {\n    return this.#x;\n  }\n}\n\nconst aSecret = new Secret();\nconst proxy = new Proxy(aSecret, {\n  get(target, prop, receiver) {\n    const value = target[prop];\n    if (value instanceof Function) {\n      return function (...args) {\n        return value.apply(this === receiver ? target : this, args);\n      };\n    }\n    return value;\n  },\n});\nconsole.log(proxy.x());\n
\n

Some native JavaScript objects have properties called internal slots, which are not accessible from JavaScript code. For example, Map objects have an internal slot called [[MapData]], which stores the key-value pairs of the map. As such, you cannot trivially create a forwarding proxy for a map:

\n

js

\n
const proxy = new Proxy(new Map(), {});\nconsole.log(proxy.size); // TypeError: get size method called on incompatible Proxy\n
\n

You have to use the \"this-recovering\" proxy illustrated above to work around this.

\n

Validation

\n
\n

With a Proxy, you can easily validate the passed value for an object. This example uses the set() handler.

\n

js

\n
const validator = {\n  set(obj, prop, value) {\n    if (prop === \"age\") {\n      if (!Number.isInteger(value)) {\n        throw new TypeError(\"The age is not an integer\");\n      }\n      if (value > 200) {\n        throw new RangeError(\"The age seems invalid\");\n      }\n    }\n\n    // The default behavior to store the value\n    obj[prop] = value;\n\n    // Indicate success\n    return true;\n  },\n};\n\nconst person = new Proxy({}, validator);\n\nperson.age = 100;\nconsole.log(person.age); // 100\nperson.age = \"young\"; // Throws an exception\nperson.age = 300; // Throws an exception\n
\n
\n

Manipulating DOM nodes

\n
\n

In this example we use Proxy to toggle an attribute of two different elements: so when we set the attribute on one element, the attribute is unset on the other one.

We create a view object which is a proxy for an object with a selected property. The proxy handler defines the set() handler.

When we assign an HTML element to view.selected, the element's 'aria-selected' attribute is set to true. If we then assign a different element to view.selected, this element's 'aria-selected' attribute is set to true and the previous element's 'aria-selected' attribute is automatically set to false.

\n

js

\n
const view = new Proxy(\n  {\n    selected: null,\n  },\n  {\n    set(obj, prop, newval) {\n      const oldval = obj[prop];\n\n      if (prop === \"selected\") {\n        if (oldval) {\n          oldval.setAttribute(\"aria-selected\", \"false\");\n        }\n        if (newval) {\n          newval.setAttribute(\"aria-selected\", \"true\");\n        }\n      }\n\n      // The default behavior to store the value\n      obj[prop] = newval;\n\n      // Indicate success\n      return true;\n    },\n  },\n);\n\nconst item1 = document.getElementById(\"item-1\");\nconst item2 = document.getElementById(\"item-2\");\n\n// select item1:\nview.selected = item1;\n\nconsole.log(`item1: ${item1.getAttribute(\"aria-selected\")}`);\n// item1: true\n\n// selecting item2 de-selects item1:\nview.selected = item2;\n\nconsole.log(`item1: ${item1.getAttribute(\"aria-selected\")}`);\n// item1: false\n\nconsole.log(`item2: ${item2.getAttribute(\"aria-selected\")}`);\n// item2: true\n
\n
\n

Value correction and an extra property

\n
\n

The products proxy object evaluates the passed value and converts it to an array if needed. The object also supports an extra property called latestBrowser both as a getter and a setter.

\n

js

\n
const products = new Proxy(\n  {\n    browsers: [\"Firefox\", \"Chrome\"],\n  },\n  {\n    get(obj, prop) {\n      // An extra property\n      if (prop === \"latestBrowser\") {\n        return obj.browsers[obj.browsers.length - 1];\n      }\n\n      // The default behavior to return the value\n      return obj[prop];\n    },\n    set(obj, prop, value) {\n      // An extra property\n      if (prop === \"latestBrowser\") {\n        obj.browsers.push(value);\n        return true;\n      }\n\n      // Convert the value if it is not an array\n      if (typeof value === \"string\") {\n        value = [value];\n      }\n\n      // The default behavior to store the value\n      obj[prop] = value;\n\n      // Indicate success\n      return true;\n    },\n  },\n);\n\nconsole.log(products.browsers);\n//  ['Firefox', 'Chrome']\n\nproducts.browsers = \"Safari\";\n//  pass a string (by mistake)\n\nconsole.log(products.browsers);\n//  ['Safari'] <- no problem, the value is an array\n\nproducts.latestBrowser = \"Edge\";\n\nconsole.log(products.browsers);\n//  ['Safari', 'Edge']\n\nconsole.log(products.latestBrowser);\n//  'Edge'\n
\n
\n

A complete traps list example

\n
\n

Now in order to create a complete sample traps list, for didactic purposes, we will try to proxify a non-native object that is particularly suited to this type of operation: the docCookies global object created by a simple cookie framework.

\n

js

\n
/*\n  const docCookies = ... get the \"docCookies\" object here:\n  https://reference.codeproject.com/dom/document/cookie/simple_document.cookie_framework\n*/\n\nconst docCookies = new Proxy(docCookies, {\n  get(target, key) {\n    return target[key] ?? target.getItem(key) ?? undefined;\n  },\n  set(target, key, value) {\n    if (key in target) {\n      return false;\n    }\n    return target.setItem(key, value);\n  },\n  deleteProperty(target, key) {\n    if (!(key in target)) {\n      return false;\n    }\n    return target.removeItem(key);\n  },\n  ownKeys(target) {\n    return target.keys();\n  },\n  has(target, key) {\n    return key in target || target.hasItem(key);\n  },\n  defineProperty(target, key, descriptor) {\n    if (descriptor && \"value\" in descriptor) {\n      target.setItem(key, descriptor.value);\n    }\n    return target;\n  },\n  getOwnPropertyDescriptor(target, key) {\n    const value = target.getItem(key);\n    return value\n      ? {\n          value,\n          writable: true,\n          enumerable: true,\n          configurable: false,\n        }\n      : undefined;\n  },\n});\n\n/* Cookies test */\n\nconsole.log((docCookies.myCookie1 = \"First value\"));\nconsole.log(docCookies.getItem(\"myCookie1\"));\n\ndocCookies.setItem(\"myCookie1\", \"Changed value\");\nconsole.log(docCookies.myCookie1);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Proxy491218No361049491836105.01.06.0.0
Proxy491218No361049491836105.01.06.0.0
revocable631234No501063633446108.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\n

\n
\n", + "global_objects/intl": "

Intl

The Intl namespace object contains several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Collectively, they comprise the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, date and time formatting, and more.

\n

Description

\n
\n

Unlike most global objects, Intl is not a constructor. You cannot use it with the new operator or invoke the Intl object as a function. All properties and methods of Intl are static (just like the Math object).

The internationalization constructors as well as several language sensitive methods of other constructors (listed under See also) use a common pattern for identifying locales and determining the one they will actually use: they all accept locales and options arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the options.localeMatcher property.

\n

locales argument

\n
\n

The locales argument is used to determine the locale used in a given operation. The JavaScript implementation examines locales, and then computes a locale it understands that comes closest to satisfying the expressed preference. locales may be:

In the latter two cases, the actual locale used is the best-supported locale determined by locale negotiation. If a locale identifier is not a string or an object, a TypeError is thrown. If a locale identifier is a string that's syntactically invalid, a RangeError is thrown. If a locale identifier is well-formed but the implementation doesn't recognize it, it is ignored and the next locale in the list is considered, eventually falling back to the system's locale. However, you shouldn't rely on a particular locale name being ignored, because the implementation may add data for any locale in the future. For example, new Intl.DateTimeFormat(\"default\") uses the implementation's default locale only because \"default\" is syntactically valid but not recognized as any locale.

A locale identifier is a string that consists of:

  1. A language subtag with 2–3 or 5–8 letters
  2. A script subtag with 4 letters Optional\n
  3. A region subtag with either 2 letters or 3 digits Optional\n
  4. One or more variant subtags (all of which must be unique), each with either 5–8 alphanumerals or a digit followed by 3 alphanumerals Optional\n
  5. One or more BCP 47 extension sequences Optional\n
  6. A private-use extension sequence Optional\n

Each subtag and sequence are separated by hyphens. Locale identifiers are case-insensitive ASCII. However, it's conventional to use title case (the first letter is capitalized, successive letters are lower case) for script subtags, upper case for region subtags, and lower case for everything else. For example:

Subtags identifying languages, scripts, regions (including countries), and (rarely used) variants are registered in the IANA Language Subtag Registry. This registry is periodically updated over time, and implementations may not always be up to date, so don't rely too much on subtags being universally supported.

BCP 47 extension sequences consist of a single digit or letter (other than \"x\") and one or more two- to eight-letter or digit subtags separated by hyphens. Only one sequence is permitted for each digit or letter: \"de-a-foo-a-foo\" is invalid. BCP 47 extension subtags are defined in the Unicode CLDR Project. Currently only two extensions have defined semantics:

Finally, a private-use extension sequence using the letter \"x\" may appear, followed by one or more one- to eight-letter or digit subtags separated by hyphens. This allows applications to encode information for their own private use, that will be ignored by all Intl operations.

\n

options argument

\n
\n

The options argument must be an object with properties that vary between constructors and functions. If the options argument is not provided or is undefined, default values are used for all properties.

One property is supported by all language sensitive constructors and functions: The localeMatcher property, whose value must be a string \"lookup\" or \"best fit\" and which selects one of the locale matching algorithms described below.

\n

Locale identification and negotiation

\n
\n

The list of locales specified by the locales argument, after Unicode extensions have been removed from them, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the \"lookup\" matcher follows the Lookup algorithm specified in BCP 47; the \"best fit\" matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a locales argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the options argument (see below).

If the selected locale identifier had a Unicode extension sequence, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the locale identifier. For example, the \"co\" key (collation) is only supported by Intl.Collator, and its \"phonebk\" value is only supported for German.

\n

Static properties

\n
Intl.Collator

Constructor for collators, which are objects that enable language-sensitive string comparison.

Intl.DateTimeFormat

Constructor for objects that enable language-sensitive date and time formatting.

Intl.DisplayNames

Constructor for objects that enable the consistent translation of language, region and script display names.

\nIntl.DurationFormat Experimental \n

Constructor for objects that enable locale-sensitive duration formatting.

Intl.ListFormat

Constructor for objects that enable language-sensitive list formatting.

Intl.Locale

Constructor for objects that represents a Unicode locale identifier.

Intl.NumberFormat

Constructor for objects that enable language-sensitive number formatting.

Intl.PluralRules

Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals.

Intl.RelativeTimeFormat

Constructor for objects that enable language-sensitive relative time formatting.

Intl.Segmenter

Constructor for objects that enable locale-sensitive text segmentation.

Intl[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl\". This property is used in Object.prototype.toString().

Static methods

\n
Intl.getCanonicalLocales()

Returns canonical locale names.

Intl.supportedValuesOf()

Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.

Examples

\n

Formatting dates and numbers

\n
\n

You can use Intl to format dates and numbers in a form that's conventional for a specific language and region:

\n

js

\n
const count = 26254.39;\nconst date = new Date(\"2012-05-24\");\n\nfunction log(locale) {\n  console.log(\n    `${new Intl.DateTimeFormat(locale).format(date)}${new Intl.NumberFormat(\n      locale,\n    ).format(count)}`,\n  );\n}\n\nlog(\"en-US\"); // 5/24/2012 26,254.39\n\nlog(\"de-DE\"); // 24.5.2012 26.254,39\n
\n
\n

Using the browser's preferred language

\n
\n

Instead of passing a hardcoded locale name to the Intl methods, you can use the user's preferred language provided by navigator.language:

\n

js

\n
const date = new Date(\"2012-05-24\");\n\nconst formattedDate = new Intl.DateTimeFormat(navigator.language).format(date);\n
\n

Alternatively, the navigator.languages property provides a sorted list of the user's preferred languages. This list can be passed directly to the Intl constructors to implement preference-based fallback selection of locales. The locale negotiation process is used to pick the most appropriate locale available:

\n

js

\n
const count = 26254.39;\n\nconst formattedCount = new Intl.NumberFormat(navigator.languages).format(count);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# intl-object
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@toStringTag868683No7214868683611414.01.815.0.0
Collator2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
DateTimeFormat2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
DisplayNames818186No6814.18181865814.513.01.814.0.0
DurationFormatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
ListFormat727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
Locale747975No6214747479531411.01.812.0.0
NumberFormat2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
PluralRules631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
RelativeTimeFormat717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
Segmenter8787NoNo7314.18787No6214.514.01.816.0.0
Segments8787NoNo7314.18787No6214.514.01.816.0.0
Intl2412291115104.4255614101.51.80.12.0
getCanonicalLocales541648No4110.15454564110.36.01.87.0.0
supportedValuesOf999993No8515.49999936815.418.01.1918.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl\n

\n
\n", + "global_objects/intl/collator": "

Intl.Collator

The Intl.Collator object enables language-sensitive string comparison.

\n

Try it

\n

Constructor

\n
Intl.Collator()

Creates a new Collator object.

Static methods

\n
Intl.Collator.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.Collator.prototype and shared by all Intl.Collator instances.

Intl.Collator.prototype.constructor

The constructor function that created the instance object. For Intl.Collator instances, the initial value is the Intl.Collator constructor.

Intl.Collator.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.Collator\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.Collator.prototype.compare()

Getter function that compares two strings according to the sort order of this Intl.Collator object.

Intl.Collator.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

Examples

\n

Using Collator

\n
\n

The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:

\n

js

\n
console.log(new Intl.Collator().compare(\"a\", \"c\")); // -1, or some other negative value\nconsole.log(new Intl.Collator().compare(\"c\", \"a\")); // 1, or some other positive value\nconsole.log(new Intl.Collator().compare(\"a\", \"a\")); // 0\n
\n

Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.

\n

Using locales

\n
\n

The results provided by Intl.Collator.prototype.compare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
// in German, ä sorts with a\nconsole.log(new Intl.Collator(\"de\").compare(\"ä\", \"z\"));\n// -1, or some other negative value\n\n// in Swedish, ä sorts after z\nconsole.log(new Intl.Collator(\"sv\").compare(\"ä\", \"z\"));\n// 1, or some other positive value\n
\n
\n

Using options

\n
\n

The results provided by Intl.Collator.prototype.compare() can be customized using the options argument:

\n

js

\n
// in German, ä has a as the base letter\nconsole.log(new Intl.Collator(\"de\", { sensitivity: \"base\" }).compare(\"ä\", \"a\"));\n// 0\n\n// in Swedish, ä and a are separate base letters\nconsole.log(new Intl.Collator(\"sv\", { sensitivity: \"base\" }).compare(\"ä\", \"a\"));\n// 1, or some other positive value\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# collator-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Collator2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the Collator instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
Collator2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
compare2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator\n

\n
\n", + "global_objects/intl/datetimeformat": "

Intl.DateTimeFormat

The Intl.DateTimeFormat object enables language-sensitive date and time formatting.

\n

Try it

\n

Constructor

\n
Intl.DateTimeFormat()

Creates a new Intl.DateTimeFormat object.

Static methods

\n
Intl.DateTimeFormat.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.DateTimeFormat.prototype and shared by all Intl.DateTimeFormat instances.

Intl.DateTimeFormat.prototype.constructor

The constructor function that created the instance object. For Intl.DateTimeFormat instances, the initial value is the Intl.DateTimeFormat constructor.

Intl.DateTimeFormat.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.DateTimeFormat\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.DateTimeFormat.prototype.format()

Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object.

Intl.DateTimeFormat.prototype.formatRange()

This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating DateTimeFormat.

Intl.DateTimeFormat.prototype.formatRangeToParts()

This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.

Intl.DateTimeFormat.prototype.formatToParts()

Returns an Array of objects representing the date string in parts that can be used for custom locale-aware formatting.

Intl.DateTimeFormat.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples

\n

Using DateTimeFormat

\n
\n

In basic use without specifying a locale, DateTimeFormat uses the default locale and default options.

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// toLocaleString without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(new Intl.DateTimeFormat().format(date));\n// \"12/19/2012\" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)\n\n// US English uses month-day-year order\nconsole.log(new Intl.DateTimeFormat(\"en-US\").format(date));\n// \"12/19/2012\"\n\n// British English uses day-month-year order\nconsole.log(new Intl.DateTimeFormat(\"en-GB\").format(date));\n// \"19/12/2012\"\n\n// Korean uses year-month-day order\nconsole.log(new Intl.DateTimeFormat(\"ko-KR\").format(date));\n// \"2012. 12. 19.\"\n\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(new Intl.DateTimeFormat(\"ar-EG\").format(date));\n// \"١٩‏/١٢‏/٢٠١٢\"\n\n// for Japanese, applications may want to use the Japanese calendar,\n// where 2012 was the year 24 of the Heisei era\nconsole.log(new Intl.DateTimeFormat(\"ja-JP-u-ca-japanese\").format(date));\n// \"24/12/19\"\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(new Intl.DateTimeFormat([\"ban\", \"id\"]).format(date));\n// \"19/12/2012\"\n
\n
\n

Using options

\n
\n

The date and time formats can be customized using the options argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));\n\n// request a weekday along with a long date\nlet options = {\n  weekday: \"long\",\n  year: \"numeric\",\n  month: \"long\",\n  day: \"numeric\",\n};\nconsole.log(new Intl.DateTimeFormat(\"de-DE\", options).format(date));\n// \"Donnerstag, 20. Dezember 2012\"\n\n// an application may want to use UTC and make that visible\noptions.timeZone = \"UTC\";\noptions.timeZoneName = \"short\";\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// \"Thursday, December 20, 2012, GMT\"\n\n// sometimes you want to be more precise\noptions = {\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n  timeZone: \"Australia/Sydney\",\n  timeZoneName: \"short\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-AU\", options).format(date));\n// \"2:00:00 pm AEDT\"\n\n// sometimes you want to be very precise\noptions.fractionalSecondDigits = 3; //number digits for fraction-of-seconds\nconsole.log(new Intl.DateTimeFormat(\"en-AU\", options).format(date));\n// \"2:00:00.200 pm AEDT\"\n\n// sometimes even the US needs 24-hour time\noptions = {\n  year: \"numeric\",\n  month: \"numeric\",\n  day: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n  hour12: false,\n  timeZone: \"America/Los_Angeles\",\n};\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// \"12/19/2012, 19:00:00\"\n\n// to specify options but use the browser's default locale, use undefined\nconsole.log(new Intl.DateTimeFormat(undefined, options).format(date));\n// \"12/19/2012, 19:00:00\"\n\n// sometimes it's helpful to include the period of the day\noptions = { hour: \"numeric\", dayPeriod: \"short\" };\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(date));\n// 10 at night\n
\n

The used calendar and numbering formats can also be set independently via options arguments:

\n

js

\n
const options = { calendar: \"chinese\", numberingSystem: \"arab\" };\nconst dateFormat = new Intl.DateTimeFormat(undefined, options);\nconst usedOptions = dateFormat.resolvedOptions();\n\nconsole.log(usedOptions.calendar);\n// \"chinese\"\n\nconsole.log(usedOptions.numberingSystem);\n// \"arab\"\n\nconsole.log(usedOptions.timeZone);\n// \"America/New_York\" (the users default timezone)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# datetimeformat-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DateTimeFormat2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the DateTimeFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
DateTimeFormat2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
format2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
formatRange767991No6314.17676915414.512.01.8
12.9.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
formatRangeToParts767991No6314.17676915414.512.01.8
12.9.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
formatToParts
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
1851No
44Before version 58, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 58 and later use the specification defined dayPeriod. See Chromium bug 865351.
11
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
56
43Before version 50, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 50 and later use the specification defined dayPeriod. See Chromium bug 865351.
11
7.0Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
1.8
8.0.0[\"Before version 12.0.0, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 12.0.0 and later use the specification defined dayPeriod. See Chromium bug 865351.\", \"Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.\"]
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat\n

\n
\n", + "global_objects/intl/displaynames": "

Intl.DisplayNames

The Intl.DisplayNames object enables the consistent translation of language, region and script display names.

\n

Try it

\n

Constructor

\n
Intl.DisplayNames()

Creates a new Intl.DisplayNames object.

Static methods

\n
Intl.DisplayNames.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.DisplayNames.prototype and shared by all Intl.DisplayNames instances.

Intl.DisplayNames.prototype.constructor

The constructor function that created the instance object. For Intl.DisplayNames instances, the initial value is the Intl.DisplayNames constructor.

Intl.DisplayNames.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.DisplayNames\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.DisplayNames.prototype.of()

This method receives a code and returns a string based on the locale and options provided when instantiating Intl.DisplayNames.

Intl.DisplayNames.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples

\n

Region Code Display Names

\n
\n

To create an Intl.DisplayNames for a locale and get the display name for a region code.

\n

js

\n
// Get display names of region in English\nlet regionNames = new Intl.DisplayNames([\"en\"], { type: \"region\" });\nregionNames.of(\"419\"); // \"Latin America\"\nregionNames.of(\"BZ\"); // \"Belize\"\nregionNames.of(\"US\"); // \"United States\"\nregionNames.of(\"BA\"); // \"Bosnia & Herzegovina\"\nregionNames.of(\"MM\"); // \"Myanmar (Burma)\"\n\n// Get display names of region in Traditional Chinese\nregionNames = new Intl.DisplayNames([\"zh-Hant\"], { type: \"region\" });\nregionNames.of(\"419\"); // \"拉丁美洲\"\nregionNames.of(\"BZ\"); // \"貝里斯\"\nregionNames.of(\"US\"); // \"美國\"\nregionNames.of(\"BA\"); // \"波士尼亞與赫塞哥維納\"\nregionNames.of(\"MM\"); // \"緬甸\"\n
\n
\n

Language Display Names

\n
\n

To create an Intl.DisplayNames for a locale and get the display name for a language-script-region sequence.

\n

js

\n
// Get display names of language in English\nlet languageNames = new Intl.DisplayNames([\"en\"], { type: \"language\" });\nlanguageNames.of(\"fr\"); // \"French\"\nlanguageNames.of(\"de\"); // \"German\"\nlanguageNames.of(\"fr-CA\"); // \"Canadian French\"\nlanguageNames.of(\"zh-Hant\"); // \"Traditional Chinese\"\nlanguageNames.of(\"en-US\"); // \"American English\"\nlanguageNames.of(\"zh-TW\"); // \"Chinese (Taiwan)\"]\n\n// Get display names of language in Traditional Chinese\nlanguageNames = new Intl.DisplayNames([\"zh-Hant\"], { type: \"language\" });\nlanguageNames.of(\"fr\"); // \"法文\"\nlanguageNames.of(\"zh\"); // \"中文\"\nlanguageNames.of(\"de\"); // \"德文\"\n
\n
\n

Script Code Display Names

\n
\n

To create an Intl.DisplayNames for a locale and get the display name for a script code.

\n

js

\n
// Get display names of script in English\nlet scriptNames = new Intl.DisplayNames([\"en\"], { type: \"script\" });\n// Get script names\nscriptNames.of(\"Latn\"); // \"Latin\"\nscriptNames.of(\"Arab\"); // \"Arabic\"\nscriptNames.of(\"Kana\"); // \"Katakana\"\n\n// Get display names of script in Traditional Chinese\nscriptNames = new Intl.DisplayNames([\"zh-Hant\"], { type: \"script\" });\nscriptNames.of(\"Latn\"); // \"拉丁文\"\nscriptNames.of(\"Arab\"); // \"阿拉伯文\"\nscriptNames.of(\"Kana\"); // \"片假名\"\n
\n
\n

Currency Code Display Names

\n
\n

To create an Intl.DisplayNames for a locale and get the display name for currency code.

\n

js

\n
// Get display names of currency code in English\nlet currencyNames = new Intl.DisplayNames([\"en\"], { type: \"currency\" });\n// Get currency names\ncurrencyNames.of(\"USD\"); // \"US Dollar\"\ncurrencyNames.of(\"EUR\"); // \"Euro\"\ncurrencyNames.of(\"TWD\"); // \"New Taiwan Dollar\"\ncurrencyNames.of(\"CNY\"); // \"Chinese Yuan\"\n\n// Get display names of currency code in Traditional Chinese\ncurrencyNames = new Intl.DisplayNames([\"zh-Hant\"], { type: \"currency\" });\ncurrencyNames.of(\"USD\"); // \"美元\"\ncurrencyNames.of(\"EUR\"); // \"歐元\"\ncurrencyNames.of(\"TWD\"); // \"新台幣\"\ncurrencyNames.of(\"CNY\"); // \"人民幣\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# intl-displaynames-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DisplayNames818186No6814.18181865814.513.01.814.0.0
DisplayNames818186No6814.18181865814.513.01.814.0.0
of818186No6814.18181865814.513.01.814.0.0
resolvedOptions818186No6814.18181865814.513.01.814.0.0
supportedLocalesOf818186No6814.18181865814.513.01.814.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames\n

\n
\n", + "global_objects/intl/durationformat": "

Intl.DurationFormat

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Intl.DurationFormat object enables language-sensitive duration formatting.

\n
\n

Constructor

\n
\nIntl.DurationFormat() Experimental \n

Creates a new Intl.DurationFormat object.

Static methods

\n
\nIntl.DurationFormat.supportedLocalesOf() Experimental \n

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.DurationFormat.prototype and shared by all Intl.DurationFormat instances.

Intl.DurationFormat.prototype.constructor

The constructor function that created the instance object. For Intl.DurationFormat instances, the initial value is the Intl.DurationFormat constructor.

Intl.DurationFormat.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.DurationFormat\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
\nIntl.DurationFormat.prototype.format() Experimental \n

Getter function that formats a duration according to the locale and formatting options of this DurationFormat object.

\nIntl.DurationFormat.prototype.formatToParts() Experimental \n

Returns an Array of objects representing the formatted duration in parts.

\nIntl.DurationFormat.prototype.resolvedOptions() Experimental \n

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples

\n

Using Intl.DurationFormat

\n
\n

The examples below show how to use the Intl.DurationFormat object to format a duration object with various locales and styles.

\n

js

\n
const duration = {\n  hours: 1,\n  minutes: 46,\n  seconds: 40,\n};\n\n// With style set to \"long\" and locale \"fr-FR\"\nnew Intl.DurationFormat(\"fr-FR\", { style: \"long\" }).format(duration);\n// \"1 heure, 46 minutes et 40 secondes\"\n\n// With style set to \"short\" and locale \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"short\" }).format(duration);\n// \"1 hr, 46 min and 40 sec\"\n\n// With style set to \"short\" and locale \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1h 46min 40s\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# durationformat-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DurationFormatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
DurationFormatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
formatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
formatToPartsNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
resolvedOptionsNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
supportedLocalesOfNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat\n

\n
\n", + "global_objects/intl/listformat": "

Intl.ListFormat

The Intl.ListFormat object enables language-sensitive list formatting.

\n

Try it

\n

Constructor

\n
Intl.ListFormat()

Creates a new Intl.ListFormat object.

Static methods

\n
Intl.ListFormat.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.ListFormat.prototype and shared by all Intl.ListFormat instances.

Intl.ListFormat.prototype.constructor

The constructor function that created the instance object. For Intl.ListFormat instances, the initial value is the Intl.ListFormat constructor.

Intl.ListFormat.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.ListFormat\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.ListFormat.prototype.format()

Returns a language-specific formatted string representing the elements of the list.

Intl.ListFormat.prototype.formatToParts()

Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.

Intl.ListFormat.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current Intl.ListFormat object.

Examples

\n

Using format

\n
\n

The following example shows how to create a List formatter using the English language.

\n

js

\n
const list = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\n
\n
\n

Using formatToParts

\n
\n

The following example shows how to create a List formatter returning formatted parts

\n

js

\n
const list = [\"Motorcycle\", \"Bus\", \"Car\"];\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", {\n    style: \"long\",\n    type: \"conjunction\",\n  }).formatToParts(list),\n);\n\n// [ { \"type\": \"element\", \"value\": \"Motorcycle\" },\n//   { \"type\": \"literal\", \"value\": \", \" },\n//   { \"type\": \"element\", \"value\": \"Bus\" },\n//   { \"type\": \"literal\", \"value\": \", and \" },\n//   { \"type\": \"element\", \"value\": \"Car\" } ];\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# listformat-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ListFormat727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the ListFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
ListFormat727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
format727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
formatToParts727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
resolvedOptions727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
supportedLocalesOf727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat\n

\n
\n", + "global_objects/intl/locale": "

Intl.Locale

The Intl.Locale object is a standard built-in property of the Intl object that represents a Unicode locale identifier.

\n

Try it

\n

Description

\n
\n

The Intl.Locale object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a locale identifier. The locale identifier consists of a language identifier and extension tags. Language identifiers are the core of the locale, consisting of language, script, and region subtags. Additional information about the locale is stored in the optional extension tags. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.

Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. The following properties of Intl.Locale correspond to Unicode locale identifier subtags:

Property Corresponding subtag
language \nlanguage (first part)
script \nscript (second part)
region \nregion (second/third part)
calendar \nca (extension)
caseFirst \nkf (extension)
collation \nco (extension)
hourCycle \nhc (extension)
numberingSystem \nnu (extension)
numeric \nkn (extension)

The information above is exactly provided as-is when the Locale object is constructed, without consulting any external database. The Intl.Locale object additionally provides some methods that return information about the locale's real-world information, such as available calendars, collations, and numbering systems.

\n

Constructor

\n
Intl.Locale()

Creates a new Locale object.

Instance properties

\n
\n

These properties are defined on Intl.Locale.prototype and shared by all Intl.Locale instances.

Intl.Locale.prototype.baseName

Returns basic, core information about the Locale in the form of a substring of the complete data string.

Intl.Locale.prototype.calendar

Returns the part of the Locale that indicates the Locale's calendar era.

Intl.Locale.prototype.caseFirst

Returns whether case is taken into account for the locale's collation rules.

Intl.Locale.prototype.collation

Returns the collation type for the Locale, which is used to order strings according to the locale's rules.

Intl.Locale.prototype.constructor

The constructor function that created the instance object. For Intl.Locale instances, the initial value is the Intl.Locale constructor.

Intl.Locale.prototype.hourCycle

Returns the time keeping format convention used by the locale.

Intl.Locale.prototype.language

Returns the language associated with the locale.

Intl.Locale.prototype.numberingSystem

Returns the numeral system used by the locale.

Intl.Locale.prototype.numeric

Returns whether the locale has special collation handling for numeric characters.

Intl.Locale.prototype.region

Returns the region of the world (usually a country) associated with the locale.

Intl.Locale.prototype.script

Returns the script used for writing the particular language used in the locale.

Intl.Locale.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.Locale\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.Locale.prototype.getCalendars()

Returns an Array of available calendar identifiers, according to the locale's rules.

Intl.Locale.prototype.getCollations()

Returns an Array of the collation types for the Locale.

Intl.Locale.prototype.getHourCycles()

Returns an Array of hour cycle identifiers, indicating either the 12-hour clock (\"h12\"), the Japanese 12-hour clock (\"h11\"), the 24-hour clock (\"h23\"), or the unused format \"h24\".

Intl.Locale.prototype.getNumberingSystems()

Returns an Array of numbering system identifiers available according to the locale's rules.

Intl.Locale.prototype.getTextInfo()

Returns the part indicating the ordering of characters ltr (left-to-right) or rtl (right-to-left).

Intl.Locale.prototype.getTimeZones()

Returns an Array of time zone identifiers, associated with the Locale.

Intl.Locale.prototype.getWeekInfo()

Returns UTS 35's Week Elements according to the locale rules.

Intl.Locale.prototype.maximize()

Gets the most likely values for the language, script, and region of the locale based on existing values.

Intl.Locale.prototype.minimize()

Attempts to remove information about the locale that would be added by calling maximize().

Intl.Locale.prototype.toString()

Returns the Locale's full locale identifier string.

Examples

\n

Basic usage

\n
\n

At its very simplest, the Intl.Locale() constructor takes a locale identifier string as its argument:

\n

js

\n
const us = new Intl.Locale(\"en-US\");\n
\n
\n

Using the Locale constructor with an options object

\n
\n

The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the hourCycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor:

\n

js

\n
const us12hour = new Intl.Locale(\"en-US\", { hourCycle: \"h12\" });\nconsole.log(us12hour.hourCycle); // Prints \"h12\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# locale-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Locale747975No6214747479531411.01.812.0.0
Locale747975No6214747479531411.01.812.0.0
baseName747975No6214747479531411.01.812.0.0
calendar747975No6214747479531411.01.812.0.0
caseFirst747975No6214747479531411.01.812.0.0
collation747975No6214747479531411.01.812.0.0
getCalendars
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getCollations
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getHourCycles
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getNumberingSystems
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getTextInfo
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getTimeZones
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
getWeekInfo
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
hourCycle747975No6214747479531411.01.812.0.0
language747975No6214747479531411.01.812.0.0
maximize747975No6214747479531411.01.812.0.0
minimize747975No6214747479531411.01.812.0.0
numberingSystem747975No6214747479531411.01.812.0.0
numeric747975No6214747479531411.01.812.0.0
region747975No6214747479531411.01.812.0.0
script747975No6214747479531411.01.812.0.0
toString747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale\n

\n
\n", + "global_objects/intl/numberformat": "

Intl.NumberFormat

The Intl.NumberFormat object enables language-sensitive number formatting.

\n

Try it

\n

Constructor

\n
Intl.NumberFormat()

Creates a new NumberFormat object.

Static methods

\n
Intl.NumberFormat.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.NumberFormat.prototype and shared by all Intl.NumberFormat instances.

Intl.NumberFormat.prototype.constructor

The constructor function that created the instance object. For Intl.NumberFormat instances, the initial value is the Intl.NumberFormat constructor.

Intl.NumberFormat.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.NumberFormat\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.NumberFormat.prototype.format()

Getter function that formats a number according to the locale and formatting options of this Intl.NumberFormat object.

Intl.NumberFormat.prototype.formatRange()

Getter function that formats a range of numbers according to the locale and formatting options of the Intl.NumberFormat object from which the method is called.

Intl.NumberFormat.prototype.formatRangeToParts()

Returns an Array of objects representing the range of number strings in parts that can be used for custom locale-aware formatting.

Intl.NumberFormat.prototype.formatToParts()

Returns an Array of objects representing the number string in parts that can be used for custom locale-aware formatting.

Intl.NumberFormat.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

Examples

\n

Basic usage

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const number = 3500;\n\nconsole.log(new Intl.NumberFormat().format(number));\n// '3,500' if in US English locale\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const number = 123456.789;\n\n// German uses comma as decimal separator and period for thousands\nconsole.log(new Intl.NumberFormat(\"de-DE\").format(number));\n// 123.456,789\n\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(new Intl.NumberFormat(\"ar-EG\").format(number));\n// ١٢٣٤٥٦٫٧٨٩\n\n// India uses thousands/lakh/crore separators\nconsole.log(new Intl.NumberFormat(\"en-IN\").format(number));\n// 1,23,456.789\n\n// the nu extension key requests a numbering system, e.g. Chinese decimal\nconsole.log(new Intl.NumberFormat(\"zh-Hans-CN-u-nu-hanidec\").format(number));\n// 一二三,四五六.七八九\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(new Intl.NumberFormat([\"ban\", \"id\"]).format(number));\n// 123.456,789\n
\n
\n

Using options

\n
\n

The results can be customized using the options argument:

\n

js

\n
const number = 123456.789;\n\n// request a currency format\nconsole.log(\n  new Intl.NumberFormat(\"de-DE\", { style: \"currency\", currency: \"EUR\" }).format(\n    number,\n  ),\n);\n// 123.456,79 €\n\n// the Japanese yen doesn't use a minor unit\nconsole.log(\n  new Intl.NumberFormat(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }).format(\n    number,\n  ),\n);\n// ¥123,457\n\n// limit to three significant digits\nconsole.log(\n  new Intl.NumberFormat(\"en-IN\", { maximumSignificantDigits: 3 }).format(\n    number,\n  ),\n);\n// 1,23,000\n\n// Formatting with units\nconsole.log(\n  new Intl.NumberFormat(\"pt-PT\", {\n    style: \"unit\",\n    unit: \"kilometer-per-hour\",\n  }).format(50),\n);\n// 50 km/h\n\nconsole.log(\n  (16).toLocaleString(\"en-GB\", {\n    style: \"unit\",\n    unit: \"liter\",\n    unitDisplay: \"long\",\n  }),\n);\n// 16 litres\n
\n

For an exhaustive list of options, see the Intl.NumberFormat() constructor page.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# numberformat-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
NumberFormat2412291115104.4255614101.51.80.12.0
NumberFormat2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
format24
12Before Edge 18, numbers are rounded to 15 decimal digits. For example, new Intl.NumberFormat('en-US').format(1000000000000005) returns \"1,000,000,000,000,010\".
29
11In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, new Intl.NumberFormat('en-US').format(1000000000000005) returns \"1,000,000,000,000,010\".
15104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
formatRange106106116No9215.41061061167215.420.0No19.0.0
formatRangeToParts106106116No9215.41061061167215.420.0No19.0.0
formatToParts641258No511364645847139.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat\n

\n
\n", + "global_objects/intl/pluralrules": "

Intl.PluralRules

The Intl.PluralRules object enables plural-sensitive formatting and plural-related language rules.

\n

Description

\n
\n

Languages use different patterns for expressing both plural numbers of items (cardinal numbers) and for expressing the order of items (ordinal numbers). English has two forms for expressing cardinal numbers: one for the singular \"item\" (1 hour, 1 dog, 1 fish) and the other for zero or any other number of \"items\" (0 hours, 2 lemmings, 100000.5 fish), while Chinese has only one form, and Arabic has six! Similarly, English has four forms for expressing ordinal numbers: \"th\", \"st\", \"nd\", \"rd\", giving the sequence: 0th, 1st, 2nd, 3rd, 4th, 5th, ..., 21st, 22nd, 23rd, 24th, 25th, and so on, while both Chinese and Arabic only have one form for ordinal numbers.

Given a particular language and set of formatting options, the methods Intl.PluralRules.prototype.select() and Intl.PluralRules.prototype.selectRange() return a tag that represents the plural form of a single or a range of numbers, cardinal or ordinal. Code can use the returned tags to represent numbers appropriately for the given language. The full set of tags that might be returned are: zero, one, two, few, many, and other (the \"general\" plural form, also used if the language only has one form).

As English only has two forms for cardinal numbers, the select() method returns only two tags: \"one\" for the singular case, and \"other\" for all other cardinal numbers. This allows construction of sentences that make sense in English for each case, such as: \"1 dog is happy; do you want to play with it?\" and \"10 dogs are happy; do you want to play with them?\".

Creating appropriate sentences for each form depends on the language, and even in English may not be as simple as just adding \"s\" to a noun to make the plural form. Using the example above, we see that the form may affect:

Other languages have more forms, and choosing appropriate sentences can be even more complex.

select() can return any of four tags for ordinal numbers in English, representing each of the allowed forms: one for \"st\" numbers (1, 21, 31, ...), two for \"nd\" numbers (2, 22, 32, ...), few for \"rd\" numbers (3, 33, 43, ...), and other for \"th\" numbers (0, 4-20, etc.). Again, the returned tags allow appropriate formatting of strings describing an ordinal number.

For more information about the rules and how they are used, see Plural Rules. For a list of the rules and how they apply for different languages, see the LDML Language Plural Rules.

\n

Constructor

\n
Intl.PluralRules()

Creates a new Intl.PluralRules object.

Static methods

\n
Intl.PluralRules.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.PluralRules.prototype and shared by all Intl.PluralRules instances.

Intl.PluralRules.prototype.constructor

The constructor function that created the instance object. For Intl.PluralRules instances, the initial value is the Intl.PluralRules constructor.

Intl.PluralRules.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.PluralRules\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.PluralRules.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

Intl.PluralRules.prototype.select()

Returns a string indicating which plural rule to use for locale-aware formatting.

Intl.PluralRules.prototype.selectRange()

This method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.

Examples

\n

Using locales

\n
\n

This example shows some of the variations in localized plural rules for cardinal numbers.

In order to get the format for the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the constructor locales argument:

\n

js

\n
// US English\nconst enCardinalRules = new Intl.PluralRules(\"en-US\");\nconsole.log(enCardinalRules.select(0)); // \"other\"\nconsole.log(enCardinalRules.select(1)); // \"one\"\nconsole.log(enCardinalRules.select(2)); // \"other\"\nconsole.log(enCardinalRules.select(3)); // \"other\"\n\n// Arabic\nconst arCardinalRules = new Intl.PluralRules(\"ar-EG\");\nconsole.log(arCardinalRules.select(0)); // \"zero\"\nconsole.log(arCardinalRules.select(1)); // \"one\"\nconsole.log(arCardinalRules.select(2)); // \"two\"\nconsole.log(arCardinalRules.select(6)); // \"few\"\nconsole.log(arCardinalRules.select(18)); // \"many\"\n
\n
\n

Using options

\n
\n

The plural form of the specified number may also depend on constructor options, such as how the number is rounded, and whether it is cardinal or ordinal.

This example shows how you can set the type of rules to \"ordinal\", and how this affects the form for some numbers in US English.

\n

js

\n
// US English - ordinal\nconst enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\nconsole.log(enOrdinalRules.select(0)); // \"other\" (0th)\nconsole.log(enOrdinalRules.select(1)); // \"one\"   (1st)\nconsole.log(enOrdinalRules.select(2)); // \"two\"   (2nd)\nconsole.log(enOrdinalRules.select(3)); // \"few\"   (3rd)\nconsole.log(enOrdinalRules.select(4)); // \"other\" (4th)\nconsole.log(enOrdinalRules.select(21)); // \"one\"  (21st)\n
\n
\n

Formatting text using the returned tag

\n
\n

The code below extends the previous example, showing how you might use the returned tag for an ordinal number to format text in English.

\n

js

\n
const enOrdinalRules = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\n\nconst suffixes = new Map([\n  [\"one\", \"st\"],\n  [\"two\", \"nd\"],\n  [\"few\", \"rd\"],\n  [\"other\", \"th\"],\n]);\nconst formatOrdinals = (n) => {\n  const rule = enOrdinalRules.select(n);\n  const suffix = suffixes.get(rule);\n  return `${n}${suffix}`;\n};\n\nformatOrdinals(0); // '0th'\nformatOrdinals(1); // '1st'\nformatOrdinals(2); // '2nd'\nformatOrdinals(3); // '3rd'\nformatOrdinals(4); // '4th'\nformatOrdinals(11); // '11th'\nformatOrdinals(21); // '21st'\nformatOrdinals(42); // '42nd'\nformatOrdinals(103); // '103rd'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# pluralrules-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
PluralRules631858No501363635846138.01.813.0.0
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the PluralRules instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
PluralRules631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
resolvedOptions631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
select631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
selectRange106106116No9215.41061061167215.420.0No19.0.0
supportedLocalesOf631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules\n

\n
\n", + "global_objects/intl/relativetimeformat": "

Intl.RelativeTimeFormat

The Intl.RelativeTimeFormat object enables language-sensitive relative time formatting.

\n

Try it

\n

Constructor

\n
Intl.RelativeTimeFormat()

Creates a new Intl.RelativeTimeFormat object.

Static methods

\n
Intl.RelativeTimeFormat.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.RelativeTimeFormat.prototype and shared by all Intl.RelativeTimeFormat instances.

Intl.RelativeTimeFormat.prototype.constructor

The constructor function that created the instance object. For Intl.RelativeTimeFormat instances, the initial value is the Intl.RelativeTimeFormat constructor.

Intl.RelativeTimeFormat.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.RelativeTimeFormat\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.RelativeTimeFormat.prototype.format()

Formats a value and a unit according to the locale and formatting options of the given Intl.RelativeTimeFormat object.

Intl.RelativeTimeFormat.prototype.formatToParts()

Returns an Array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.

Intl.RelativeTimeFormat.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples

\n

Basic format usage

\n
\n

The following example shows how to use a relative time formatter for the English language.

\n

js

\n
// Create a relative time formatter in your locale\n// with default values explicitly passed in.\nconst rtf = new Intl.RelativeTimeFormat(\"en\", {\n  localeMatcher: \"best fit\", // other values: \"lookup\"\n  numeric: \"always\", // other values: \"auto\"\n  style: \"long\", // other values: \"short\" or \"narrow\"\n});\n\n// Format relative time using negative value (-1).\nrtf.format(-1, \"day\"); // \"1 day ago\"\n\n// Format relative time using positive value (1).\nrtf.format(1, \"day\"); // \"in 1 day\"\n
\n
\n

Using formatToParts

\n
\n

The following example shows how to create a relative time formatter returning formatted parts.

\n

js

\n
const rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n\n// Format relative time using the day unit.\nrtf.formatToParts(-1, \"day\");\n// [{ type: \"literal\", value: \"yesterday\"}]\n\nrtf.formatToParts(100, \"day\");\n// [\n//   { type: \"literal\", value: \"in \" },\n//   { type: \"integer\", value: \"100\", unit: \"day\" },\n//   { type: \"literal\", value: \" days\" }\n// ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# relativetimeformat-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
RelativeTimeFormat717965No5814717165501410.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the RelativeTimeFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
RelativeTimeFormat717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
format717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
formatToParts717970No5814717179501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
resolvedOptions717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
supportedLocalesOf717965No5814717165501410.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat\n

\n
\n", + "global_objects/intl/segmenter": "

Intl.Segmenter

The Intl.Segmenter object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.

\n

Try it

\n

Constructor

\n
Intl.Segmenter()

Creates a new Intl.Segmenter object.

Static methods

\n
Intl.Segmenter.supportedLocalesOf()

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties

\n
\n

These properties are defined on Intl.Segmenter.prototype and shared by all Intl.Segmenter instances.

Intl.Segmenter.prototype.constructor

The constructor function that created the instance object. For Intl.Segmenter instances, the initial value is the Intl.Segmenter constructor.

Intl.Segmenter.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string \"Intl.Segmenter\". This property is used in Object.prototype.toString().

\n

Instance methods

\n
Intl.Segmenter.prototype.resolvedOptions()

Returns a new object with properties reflecting the locale and granularity options computed during initialization of this Intl.Segmenter object.

Intl.Segmenter.prototype.segment()

Returns a new iterable Segments instance representing the segments of a string according to the locale and granularity of this Intl.Segmenter instance.

Examples

\n

Basic usage and difference from String.prototype.split()

\n
\n

If we were to use String.prototype.split(\" \") to segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).

\n

js

\n
const str = \"吾輩は猫である。名前はたぬき。\";\nconsole.table(str.split(\" \"));\n// ['吾輩は猫である。名前はたぬき。']\n// The two sentences are not correctly segmented.\n
\n
\n

js

\n
const str = \"吾輩は猫である。名前はたぬき。\";\nconst segmenterJa = new Intl.Segmenter(\"ja-JP\", { granularity: \"word\" });\n\nconst segments = segmenterJa.segment(str);\nconsole.table(Array.from(segments));\n// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},\n// etc.\n// ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# segmenter-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Segmenter8787NoNo7314.18787No6214.514.01.816.0.0
Segmenter8787NoNo7314.18787No6214.514.01.816.0.0
resolvedOptions8787NoNo7314.18787No6214.514.01.816.0.0
segment8787NoNo7314.18787No6214.514.01.816.0.0
supportedLocalesOf8787NoNo7314.18787No6214.514.01.816.0.0
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter\n

\n
\n", + "statements/return": "

return

The return statement ends function execution and specifies a value to be returned to the function caller.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
return;\nreturn expression;\n
\n
\nexpression Optional\n

The expression whose value is to be returned. If omitted, undefined is returned.

\n

Description

\n
\n

The return statement can only be used within function bodies. When a return statement is used in a function body, the execution of the function is stopped. The return statement has different effects when placed in different functions:

If a return statement is executed within a try block, its finally block, if present, is first executed, before the value is actually returned.

\n

Automatic semicolon insertion

\n
\n

The syntax forbids line terminators between the return keyword and the expression to be returned.

\n

js

\n
return\na + b;\n
\n

The code above is transformed by automatic semicolon insertion (ASI) into:

\n

js

\n
return;\na + b;\n
\n

This makes the function return undefined and the a + b expression is never evaluated. This may generate a warning in the console.

To avoid this problem (to prevent ASI), you could use parentheses:

\n

js

\n
return (\n  a + b\n);\n
\n
\n

Examples

\n

Interrupt a function

\n
\n

A function immediately stops at the point where return is called.

\n

js

\n
function counter() {\n  // Infinite loop\n  for (let count = 1; ; count++) {\n    console.log(`${count}A`); // Until 5\n    if (count === 5) {\n      return;\n    }\n    console.log(`${count}B`); // Until 4\n  }\n  console.log(`${count}C`); // Never appears\n}\n\ncounter();\n\n// Logs:\n// 1A\n// 1B\n// 2A\n// 2B\n// 3A\n// 3B\n// 4A\n// 4B\n// 5A\n
\n
\n

Returning a function

\n
\n

See also the article about Closures.

\n

js

\n
function magic() {\n  return function calc(x) {\n    return x * 42;\n  };\n}\n\nconst answer = magic();\nanswer(1337); // 56154\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-return-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
return11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return\n

\n
\n", + "statements/break": "

break

The break statement terminates the current loop or switch statement and transfers program control to the statement following the terminated statement. It can also be used to jump past a labeled statement when used within that labeled statement.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
break;\nbreak label;\n
\n
\nlabel Optional\n

Identifier associated with the label of the statement to break to. If the break statement is not nested within a loop or switch, then the label identifier is required.

\n

Description

\n
\n

When break; is encountered, the program breaks out of the innermost switch or looping statement and continues executing the next statement after that.

When break label; is encountered, the program breaks out of the statement labeled with label and continues executing the next statement after that. The break statement needs to be nested within the referenced label. The labeled statement can be any statement (commonly a block statement); it does not have to be another loop statement.

A break statement, with or without a following label, cannot be used at the top level of a script, module, function's body, or static initialization block, even when the function or class is further contained within a loop.

\n

Examples

\n

break in while loop

\n
\n

The following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.

\n

js

\n
function testBreak(x) {\n  let i = 0;\n\n  while (i < 6) {\n    if (i === 3) {\n      break;\n    }\n    i += 1;\n  }\n\n  return i * x;\n}\n
\n
\n

break in switch statements

\n
\n

The following code has a break statement that terminates the switch statement when a case is matched and the corresponding code has run.

\n

js

\n
const food = \"sushi\";\n\nswitch (food) {\n  case \"sushi\":\n    console.log(\"Sushi is originally from Japan.\");\n    break;\n  case \"pizza\":\n    console.log(\"Pizza is originally from Italy.\");\n    break;\n  default:\n    console.log(\"I have never heard of that dish.\");\n    break;\n}\n
\n
\n

break in labeled blocks

\n
\n

The following code uses break statements with labeled blocks. By using break outerBlock, control is transferred to the end of the block statement marked as outerBlock.

\n

js

\n
outerBlock: {\n  innerBlock: {\n    console.log(\"1\");\n    break outerBlock; // breaks out of both innerBlock and outerBlock\n    console.log(\":-(\"); // skipped\n  }\n  console.log(\"2\"); // skipped\n}\n
\n
\n

Unsyntactic break statements

\n
\n

A break statement must be nested within any label it references. The following code also uses break statements with labeled blocks, but generates a syntax error because its break statement references block2 but it's not nested within block2.

\n

js

\n
block1: {\n  console.log(\"1\");\n  break block2; // SyntaxError: label not found\n}\n\nblock2: {\n  console.log(\"2\");\n}\n
\n

Syntax errors are also generated in the following code examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of.

\n

js

\n
function testBreak(x) {\n  let i = 0;\n\n  while (i < 6) {\n    if (i === 3) {\n      (() => {\n        break;\n      })();\n    }\n    i += 1;\n  }\n\n  return i * x;\n}\n\ntestBreak(1); // SyntaxError: Illegal break statement\n
\n
\n

js

\n
block1: {\n  console.log(\"1\");\n  (() => {\n    break block1; // SyntaxError: Undefined label 'block1'\n  })();\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-break-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
break11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break\n

\n
\n", + "statements/continue": "

continue

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
continue;\ncontinue label;\n
\n
\nlabel Optional\n

Identifier associated with the label of the statement.

\n

Description

\n
\n

In contrast to the break statement, continue does not terminate the execution of the loop entirely, but instead:

The continue statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the innermost loop. In this case, the continue statement needs to be nested within this labeled statement.

A continue statement, with or without a following label, cannot be used at the top level of a script, module, function's body, or static initialization block, even when the function or class is further contained within a loop.

\n

Examples

\n

Using continue with while

\n
\n

The following example shows a while loop that has a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

\n

js

\n
let i = 0;\nlet n = 0;\n\nwhile (i < 5) {\n  i++;\n\n  if (i === 3) {\n    continue;\n  }\n\n  n += i;\n}\n
\n
\n

Using continue with a label

\n
\n

In the following example, a statement labeled checkIAndJ contains a statement labeled checkJ. If continue is encountered, the program continues at the top of the checkJ statement. Each time continue is encountered, checkJ reiterates until its condition returns false. When false is returned, the remainder of the checkIAndJ statement is completed.

If continue had a label of checkIAndJ, the program would continue at the top of the checkIAndJ statement.

\n

js

\n
let i = 0;\nlet j = 8;\n\ncheckIAndJ: while (i < 4) {\n  console.log(`i: ${i}`);\n  i += 1;\n\n  checkJ: while (j > 4) {\n    console.log(`j: ${j}`);\n    j -= 1;\n\n    if (j % 2 === 0) continue checkJ;\n    console.log(`${j} is odd.`);\n  }\n  console.log(`i = ${i}`);\n  console.log(`j = ${j}`);\n}\n
\n

Output:

i: 0\n\n// start checkj\nj: 8\n7 is odd.\nj: 7\nj: 6\n5 is odd.\nj: 5\n// end checkj\n\ni = 1\nj = 4\n\ni: 1\ni = 2\nj = 4\n\ni: 2\ni = 3\nj = 4\n\ni: 3\ni = 4\nj = 4\n
\n

Unsyntactic continue statements

\n
\n

continue cannot be used within loops across function boundaries.

\n

js

\n
for (let i = 0; i < 10; i++) {\n  (() => {\n    continue; // SyntaxError: Illegal continue statement: no surrounding iteration statement\n  })();\n}\n
\n

When referencing a label, the labeled statement must contain the continue statement.

\n

js

\n
label: for (let i = 0; i < 10; i++) {\n  console.log(i);\n}\n\nfor (let i = 0; i < 10; i++) {\n  continue label; // SyntaxError: Undefined label 'label'\n}\n
\n

The labeled statement must be a loop.

\n

js

\n
label: {\n  for (let i = 0; i < 10; i++) {\n    continue label; // SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-continue-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
continue11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue\n

\n
\n", + "statements/throw": "

throw

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
throw expression;\n
\n
expression

The expression to throw.

\n

Description

\n
\n

The throw statement is valid in all contexts where statements can be used. Its execution generates an exception that penetrates through the call stack. For more information on error bubbling and handling, see Control flow and error handling.

The throw keyword can be followed by any kind of expression, for example:

\n

js

\n
throw error; // Throws a previously defined value (e.g. within a catch block)\nthrow new Error(\"Required\"); // Throws a new Error object\n
\n

In practice, the exception you throw should always be an Error object or an instance of an Error subclass, such as RangeError. This is because code that catches the error may expect certain properties, such as message, to be present on the caught value. For example, web APIs typically throw DOMException instances, which inherit from Error.prototype.

\n

Automatic semicolon insertion

\n
\n

The syntax forbids line terminators between the throw keyword and the expression to be thrown.

\n

js

\n
throw\nnew Error();\n
\n

The code above is transformed by automatic semicolon insertion (ASI) into:

\n

js

\n
throw;\nnew Error();\n
\n

This is invalid code, because unlike return, throw must be followed by an expression.

To avoid this problem (to prevent ASI), you could use parentheses:

\n

js

\n
throw (\n  new Error()\n);\n
\n
\n

Examples

\n

Throwing a user-defined error

\n
\n

This example defines a function that throws a TypeError if the input is not of the expected type.

\n

js

\n
function isNumeric(x) {\n  return [\"number\", \"bigint\"].includes(typeof x);\n}\n\nfunction sum(...values) {\n  if (!values.every(isNumeric)) {\n    throw new TypeError(\"Can only add numbers\");\n  }\n  return values.reduce((a, b) => a + b);\n}\n\nconsole.log(sum(1, 2, 3)); // 6\ntry {\n  sum(\"1\", \"2\");\n} catch (e) {\n  console.error(e); // TypeError: Can only add numbers\n}\n
\n
\n

Throwing an existing object

\n
\n

This example calls a callback-based async function, and throws an error if the callback receives an error.

\n

js

\n
readFile(\"foo.txt\", (err, data) => {\n  if (err) {\n    throw err;\n  }\n  console.log(data);\n});\n
\n

Errors thrown this way are not catchable by the caller and will cause the program to crash unless (a) the readFile function itself catches the error, or (b) the program is running in a context that catches top-level errors. You can handle errors more naturally by using the Promise() constructor.

\n

js

\n
function readFilePromise(path) {\n  return new Promise((resolve, reject) => {\n    readFile(path, (err, data) => {\n      if (err) {\n        reject(err);\n      }\n      resolve(data);\n    });\n  });\n}\n\ntry {\n  const data = await readFilePromise(\"foo.txt\");\n  console.log(data);\n} catch (err) {\n  console.error(err);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-throw-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
throw11215414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw\n

\n
\n", + "statements/if...else": "

if...else

The if...else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
if (condition)\n  statement1\n\n// With an else clause\nif (condition)\n  statement1\nelse\n  statement2\n
\n
condition

An expression that is considered to be either truthy or falsy.

statement1

Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ({ /* ... */ }) to group those statements. To execute no statements, use an empty statement.

statement2

Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements.

\n

Description

\n
\n

Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.

\n

js

\n
if (condition1)\n  statement1\nelse if (condition2)\n  statement2\nelse if (condition3)\n  statement3\n// …\nelse\n  statementN\n
\n

To see how this works, this is how it would look if the nesting were properly indented:

\n

js

\n
if (condition1)\n  statement1\nelse\n  if (condition2)\n    statement2\n  else\n    if (condition3)\n      statement3\n// …\n
\n

To execute multiple statements within a clause, use a block statement ({ /* ... */ }) to group those statements.

\n

js

\n
if (condition) {\n  statements1\n} else {\n  statements2\n}\n
\n

Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:

\n

js

\n
function checkValue(a, b) {\n  if (a === 1)\n    if (b === 2)\n      console.log(\"a is 1 and b is 2\");\n  else\n    console.log(\"a is not 1\");\n}\n
\n

This code looks innocent — however, executing checkValue(1, 3) will log \"a is not 1\". This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like:

\n

js

\n
function checkValue(a, b) {\n  if (a === 1)\n    if (b === 2)\n      console.log(\"a is 1 and b is 2\");\n    else\n      console.log(\"a is not 1\");\n}\n
\n

In general, it is a good practice to always use block statements, especially in code involving nested if statements.

\n

js

\n
function checkValue(a, b) {\n  if (a === 1) {\n    if (b === 2) {\n      console.log(\"a is 1 and b is 2\");\n    }\n  } else {\n    console.log(\"a is not 1\");\n  }\n}\n
\n

Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false, undefined, null, 0, -0, NaN, or the empty string (\"\"), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:

\n

js

\n
const b = new Boolean(false);\nif (b) {\n  console.log(\"b is truthy\"); // \"b is truthy\"\n}\n
\n
\n

Examples

\n

Using if...else

\n
\n

js

\n
if (cipherChar === fromChar) {\n  result += toChar;\n  x++;\n} else {\n  result += clearChar;\n}\n
\n

Using else if

\n
\n

Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if:

\n

js

\n
if (x > 50) {\n  /* do something */\n} else if (x > 5) {\n  /* do something */\n} else {\n  /* do something */\n}\n
\n
\n

Using an assignment as a condition

\n
\n

You should almost never have an if...else with an assignment like x = y as a condition:

\n

js

\n
if ((x = y)) {\n  // …\n}\n
\n

Because unlike while loops, the condition is only evaluated once, so the assignment is only performed once. The code above is equivalent to:

\n

js

\n
x = y;\nif (x) {\n  // …\n}\n
\n

Which is much clearer. However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with our recommendations.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-if-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
if...else11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else\n

\n
\n", + "statements/switch": "

switch

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
switch (expression) {\n  case value1:\n    statements\n  case value2:\n    statements\n  // …\n  case valueN:\n    statements\n  default:\n    statements\n}\n
\n
expression

An expression whose result is matched against each case clause.

\ncase valueN Optional\n

A case clause used to match against expression. If the expression matches the specified valueN (which can be any expression), execution starts from the first statement after that case clause until either the end of the switch statement or the first encountered break.

\ndefault Optional\n

A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses. A switch statement can only have one default clause.

\n

Description

\n
\n

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict equality comparison) and transfers control to that clause, executing all statements following that clause.

The clause values are only evaluated when necessary — if a match is already found, subsequent case clause values will not be evaluated, even when they will be visited by fall-through.

\n

js

\n
switch (undefined) {\n  case console.log(1):\n  case console.log(2):\n}\n// Only logs 1\n
\n

If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing statements following that clause. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so. A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError.

\n

Breaking and fall-through

\n
\n

You can use the break statement within a switch statement's body to break out early, often when all statements between two case clauses have been executed. Execution will continue at the first statement following switch.

If break is omitted, execution will proceed to the next case clause, even to the default clause, regardless of whether the value of that clause matches. This behavior is called \"fall-through\".

\n

js

\n
const foo = 0;\nswitch (foo) {\n  case -1:\n    console.log(\"negative 1\");\n    break;\n  case 0: // Value of foo matches this criteria; execution starts from here\n    console.log(0);\n  // Forgotten break! Execution falls through\n  case 1: // no break statement in 'case 0:' so this case will run as well\n    console.log(1);\n    break; // Break encountered; will not continue into 'case 2:'\n  case 2:\n    console.log(2);\n    break;\n  default:\n    console.log(\"default\");\n}\n// Logs 0 and 1\n
\n

In the appropriate context, other control-flow statements also have the effect of breaking out of the switch statement. For example, if the switch statement is contained in a function, then a return statement terminates the execution of the function body and therefore the switch statement. If the switch statement is contained in a loop, then a continue statement stops the switch statement and jumps to the next iteration of the loop.

\n

Lexical scoping

\n
\n

The case and default clauses are like labels: they indicate possible places that control flow may jump to. However, they don't create lexical scopes themselves (neither do they automatically break out — as demonstrated above). For example:

\n

js

\n
const action = \"say_hello\";\nswitch (action) {\n  case \"say_hello\":\n    const message = \"hello\";\n    console.log(message);\n    break;\n  case \"say_hi\":\n    const message = \"hi\";\n    console.log(message);\n    break;\n  default:\n    console.log(\"Empty action received.\");\n}\n
\n

This example will output the error \"Uncaught SyntaxError: Identifier 'message' has already been declared\", because the first const message = 'hello'; conflicts with the second const message = 'hi'; declaration, even when they're within their own separate case clauses. Ultimately, this is due to both const declarations being within the same block scope created by the switch body.

To fix this, whenever you need to use let or const declarations in a case clause, wrap it in a block.

\n

js

\n
const action = \"say_hello\";\nswitch (action) {\n  case \"say_hello\": {\n    const message = \"hello\";\n    console.log(message);\n    break;\n  }\n  case \"say_hi\": {\n    const message = \"hi\";\n    console.log(message);\n    break;\n  }\n  default: {\n    console.log(\"Empty action received.\");\n  }\n}\n
\n

This code will now output hello in the console as it should, without any errors.

\n

Examples

\n

Using switch

\n
\n

In the following example, if expr evaluates to Bananas, the program matches the value with case case 'Bananas' and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for the case 'Cherries' would also be executed.

\n

js

\n
switch (expr) {\n  case \"Oranges\":\n    console.log(\"Oranges are $0.59 a pound.\");\n    break;\n  case \"Apples\":\n    console.log(\"Apples are $0.32 a pound.\");\n    break;\n  case \"Bananas\":\n    console.log(\"Bananas are $0.48 a pound.\");\n    break;\n  case \"Cherries\":\n    console.log(\"Cherries are $3.00 a pound.\");\n    break;\n  case \"Mangoes\":\n  case \"Papayas\":\n    console.log(\"Mangoes and papayas are $2.79 a pound.\");\n    break;\n  default:\n    console.log(`Sorry, we are out of ${expr}.`);\n}\n\nconsole.log(\"Is there anything else you'd like?\");\n
\n
\n

Putting the default clause between two case clauses

\n
\n

If no match is found, execution will start from the default clause, and execute all statements after that.

\n

js

\n
const foo = 5;\nswitch (foo) {\n  case 2:\n    console.log(2);\n    break; // it encounters this break so will not continue into 'default:'\n  default:\n    console.log(\"default\");\n  // fall-through\n  case 1:\n    console.log(\"1\");\n}\n
\n

It also works when you put default before all other case clauses.

\n

Taking advantage of fall-through

\n
\n

This method takes advantage of the fact that if there is no break below a case clause, execution will continue to the next case clause regardless if that case meets the criteria.

The following is an example of a single operation sequential case statement, where four different values perform exactly the same.

\n

js

\n
const Animal = \"Giraffe\";\nswitch (Animal) {\n  case \"Cow\":\n  case \"Giraffe\":\n  case \"Dog\":\n  case \"Pig\":\n    console.log(\"This animal is not extinct.\");\n    break;\n  case \"Dinosaur\":\n  default:\n    console.log(\"This animal is extinct.\");\n}\n
\n

The following is an example of a multiple-operation sequential case clause, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case clauses, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.

\n

js

\n
const foo = 1;\nlet output = \"Output: \";\nswitch (foo) {\n  case 0:\n    output += \"So \";\n  case 1:\n    output += \"What \";\n    output += \"Is \";\n  case 2:\n    output += \"Your \";\n  case 3:\n    output += \"Name\";\n  case 4:\n    output += \"?\";\n    console.log(output);\n    break;\n  case 5:\n    output += \"!\";\n    console.log(output);\n    break;\n  default:\n    console.log(\"Please pick a number from 0 to 5!\");\n}\n
\n

The output from this example:

Value Log text
\nfoo is NaN or not 1, 2, 3, 4, 5, or 0\n Please pick a number from 0 to 5!
0 Output: So What Is Your Name?
1 Output: What Is Your Name?
2 Output: Your Name?
3 Output: Name?
4 Output: ?
5 Output: !
\n

An alternative to if...else chains

\n
\n

You may often find yourself doing a series of if...else matches.

\n

js

\n
if (\"fetch\" in globalThis) {\n  // Fetch a resource with fetch\n} else if (\"XMLHttpRequest\" in globalThis) {\n  // Fetch a resource with XMLHttpRequest\n} else {\n  // Fetch a resource with some custom AJAX logic\n}\n
\n

This pattern is not doing a sequence of === comparisons, but you can still convert it to a switch construct.

\n

js

\n
switch (true) {\n  case \"fetch\" in globalThis:\n    // Fetch a resource with fetch\n    break;\n  case \"XMLHttpRequest\" in globalThis:\n    // Fetch a resource with XMLHttpRequest\n    break;\n  default:\n    // Fetch a resource with some custom AJAX logic\n    break;\n}\n
\n

The switch (true) pattern as an alternative to if...else is especially useful if you want to utilize the fall-through behavior.

\n

js

\n
switch (true) {\n  case isSquare(shape):\n    console.log(\"This shape is a square.\");\n  // Fall-through, since a square is a rectangle as well!\n  case isRectangle(shape):\n    console.log(\"This shape is a rectangle.\");\n  case isQuadrilateral(shape):\n    console.log(\"This shape is a quadrilateral.\");\n    break;\n  case isCircle(shape):\n    console.log(\"This shape is a circle.\");\n    break;\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-switch-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
switch11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch\n

\n
\n", + "statements/try...catch": "

try...catch

The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
try {\n  tryStatements\n} catch (exceptionVar) {\n  catchStatements\n} finally {\n  finallyStatements\n}\n
\n
tryStatements

The statements to be executed.

catchStatements

Statement that is executed if an exception is thrown in the try block.

\nexceptionVar Optional\n

An optional identifier or pattern to hold the caught exception for the associated catch block. If the catch block does not use the exception's value, you can omit the exceptionVar and its surrounding parentheses.

finallyStatements

Statements that are executed before control flow exits the try...catch...finally construct. These statements execute regardless of whether an exception was thrown or caught.

\n

Description

\n
\n

The try statement always starts with a try block. Then, a catch block or a finally block must be present. It's also possible to have both catch and finally blocks. This gives us three forms for the try statement:

Unlike other constructs such as if or for, the try, catch, and finally blocks must be blocks, instead of single statements.

\n

js

\n
try doSomething(); // SyntaxError\ncatch (e) console.log(e);\n
\n

A catch block contains statements that specify what to do if an exception is thrown in the try block. If any statement within the try block (or in a function called from within the try block) throws an exception, control is immediately shifted to the catch block. If no exception is thrown in the try block, the catch block is skipped.

The finally block will always execute before control flow exits the try...catch...finally construct. It always executes, regardless of whether an exception was thrown or caught.

You can nest one or more try statements. If an inner try statement does not have a catch block, the enclosing try statement's catch block is used instead.

You can also use the try statement to handle JavaScript exceptions. See the JavaScript Guide for more information on JavaScript exceptions.

\n

Catch binding

\n
\n

When an exception is thrown in the try block, exceptionVar (i.e., the e in catch (e)) holds the exception value. You can use this binding to get information about the exception that was thrown. This binding is only available in the catch block's scope.

It needs not be a single identifier. You can use a destructuring pattern to assign multiple identifiers at once.

\n

js

\n
try {\n  throw new TypeError(\"oops\");\n} catch ({ name, message }) {\n  console.log(name); // \"TypeError\"\n  console.log(message); // \"oops\"\n}\n
\n

The bindings created by the catch clause live in the same scope as the catch block, so any variables declared in the catch block cannot have the same name as the bindings created by the catch clause. (There's one exception to this rule, but it's a deprecated syntax.)

\n

js

\n
try {\n  throw new TypeError(\"oops\");\n} catch ({ name, message }) {\n  var name; // SyntaxError: Identifier 'name' has already been declared\n  let message; // SyntaxError: Identifier 'message' has already been declared\n}\n
\n

The exception binding is writable. For example, you may want to normalize the exception value to make sure it's an Error object.

\n

js

\n
try {\n  throw \"Oops; this is not an Error object\";\n} catch (e) {\n  if (!(e instanceof Error)) {\n    e = new Error(e);\n  }\n  console.error(e.message);\n}\n
\n

If you don't need the exception value, you can omit it along with the enclosing parentheses.

\n

js

\n
function isValidJSON(text) {\n  try {\n    JSON.parse(text);\n    return true;\n  } catch {\n    return false;\n  }\n}\n
\n
\n

The finally block

\n
\n

The finally block contains statements to execute after the try block and catch block(s) execute, but before the statements following the try...catch...finally block. Control flow will always enter the finally block, which can proceed in one of the following ways:

If an exception is thrown from the try block, even when there's no catch block to handle the exception, the finally block still executes, in which case the exception is still thrown immediately after the finally block finishes executing.

The following example shows one use case for the finally block. The code opens a file and then executes statements that use the file; the finally block makes sure the file always closes after it is used even if an exception was thrown.

\n

js

\n
openMyFile();\ntry {\n  // tie up a resource\n  writeMyFile(theData);\n} finally {\n  closeMyFile(); // always close the resource\n}\n
\n

Control flow statements (return, throw, break, continue) in the finally block will \"mask\" any completion value of the try block or catch block. In this example, the try block tries to return 1, but before returning, the control flow is yielded to the finally block first, so the finally block's return value is returned instead.

\n

js

\n
function doIt() {\n  try {\n    return 1;\n  } finally {\n    return 2;\n  }\n}\n\ndoIt(); // returns 2\n
\n

It is generally a bad idea to have control flow statements in the finally block. Only use it for cleanup code.

\n

Examples

\n

Unconditional catch block

\n
\n

When a catch block is used, the catch block is executed when any exception is thrown from within the try block. For example, when the exception occurs in the following code, control transfers to the catch block.

\n

js

\n
try {\n  throw \"myException\"; // generates an exception\n} catch (e) {\n  // statements to handle any exceptions\n  logMyErrors(e); // pass exception object to error handler\n}\n
\n

The catch block specifies an identifier (e in the example above) that holds the value of the exception; this value is only available in the scope of the catch block.

\n

Conditional catch blocks

\n
\n

You can create \"Conditional catch blocks\" by combining try...catch blocks with if...else if...else structures, like this:

\n

js

\n
try {\n  myroutine(); // may throw three types of exceptions\n} catch (e) {\n  if (e instanceof TypeError) {\n    // statements to handle TypeError exceptions\n  } else if (e instanceof RangeError) {\n    // statements to handle RangeError exceptions\n  } else if (e instanceof EvalError) {\n    // statements to handle EvalError exceptions\n  } else {\n    // statements to handle any unspecified exceptions\n    logMyErrors(e); // pass exception object to error handler\n  }\n}\n
\n

A common use case for this is to only catch (and silence) a small subset of expected errors, and then re-throw the error in other cases:

\n

js

\n
try {\n  myRoutine();\n} catch (e) {\n  if (e instanceof RangeError) {\n    // statements to handle this very common expected error\n  } else {\n    throw e; // re-throw the error unchanged\n  }\n}\n
\n

This may mimic the syntax from other languages, like Java:

\n

java

\n
try {\n  myRoutine();\n} catch (RangeError e) {\n  // statements to handle this very common expected error\n}\n// Other errors are implicitly re-thrown\n
\n
\n

Nested try blocks

\n
\n

First, let's see what happens with this:

\n

js

\n
try {\n  try {\n    throw new Error(\"oops\");\n  } finally {\n    console.log(\"finally\");\n  }\n} catch (ex) {\n  console.error(\"outer\", ex.message);\n}\n\n// Logs:\n// \"finally\"\n// \"outer\" \"oops\"\n
\n

Now, if we already caught the exception in the inner try block by adding a catch block:

\n

js

\n
try {\n  try {\n    throw new Error(\"oops\");\n  } catch (ex) {\n    console.error(\"inner\", ex.message);\n  } finally {\n    console.log(\"finally\");\n  }\n} catch (ex) {\n  console.error(\"outer\", ex.message);\n}\n\n// Logs:\n// \"inner\" \"oops\"\n// \"finally\"\n
\n

And now, let's rethrow the error.

\n

js

\n
try {\n  try {\n    throw new Error(\"oops\");\n  } catch (ex) {\n    console.error(\"inner\", ex.message);\n    throw ex;\n  } finally {\n    console.log(\"finally\");\n  }\n} catch (ex) {\n  console.error(\"outer\", ex.message);\n}\n\n// Logs:\n// \"inner\" \"oops\"\n// \"finally\"\n// \"outer\" \"oops\"\n
\n

Any given exception will be caught only once by the nearest enclosing catch block unless it is rethrown. Of course, any new exceptions raised in the \"inner\" block (because the code in catch block may do something that throws), will be caught by the \"outer\" block.

\n

Returning from a finally block

\n
\n

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch blocks. This includes exceptions thrown inside of the catch block:

\n

js

\n
(() => {\n  try {\n    try {\n      throw new Error(\"oops\");\n    } catch (ex) {\n      console.error(\"inner\", ex.message);\n      throw ex;\n    } finally {\n      console.log(\"finally\");\n      return;\n    }\n  } catch (ex) {\n    console.error(\"outer\", ex.message);\n  }\n})();\n\n// Logs:\n// \"inner\" \"oops\"\n// \"finally\"\n
\n

The outer \"oops\" is not thrown because of the return in the finally block. The same would apply to any value returned from the catch block.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-try-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
try...catch11215414.418410.111.01.00.10.0
optional_catch_binding667958No5311.16666584711.39.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch\n

\n
\n", + "statements/var": "

var

The var statement declares function-scoped or globally-scoped variables, optionally initializing each to a value.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
var name1;\nvar name1 = value1;\nvar name1 = value1, name2 = value2;\nvar name1, name2 = value2;\nvar name1 = value1, name2, /* …, */ nameN = valueN;\n
\n
nameN

The name of the variable to declare. Each must be a legal JavaScript identifier or a destructuring binding pattern.

\nvalueN Optional\n

Initial value of the variable. It can be any legal expression. Default value is undefined.

\n

Description

\n
\n

The scope of a variable declared with var is one of the following curly-brace-enclosed syntaxes that most closely contains the var statement:

Or if none of the above applies:

\n

js

\n
function foo() {\n  var x = 1;\n  function bar() {\n    var y = 2;\n    console.log(x); // 1 (function `bar` closes over `x`)\n    console.log(y); // 2 (`y` is in scope)\n  }\n  bar();\n  console.log(x); // 1 (`x` is in scope)\n  console.log(y); // ReferenceError, `y` is scoped to `bar`\n}\n\nfoo();\n
\n

Importantly, other block constructs, including block statements, try...catch, switch, headers of one of the for statements, do not create scopes for var, and variables declared with var inside such a block can continue to be referenced outside the block.

\n

js

\n
for (var a of [1, 2, 3]);\nconsole.log(a); // 3\n
\n

In a script, a variable declared using var is added as a non-configurable property of the global object. This means its property descriptor cannot be changed and it cannot be deleted using delete. JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable.

\n

js

\n
\"use strict\";\nvar x = 1;\nObject.hasOwn(globalThis, \"x\"); // true\ndelete globalThis.x; // TypeError in strict mode. Fails silently otherwise.\ndelete x; // SyntaxError in strict mode. Fails silently otherwise.\n
\n

In both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not added as properties to the global object.

The list that follows the var keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list and get the initialized value.

\n

Hoisting

\n
\n

var declarations, wherever they occur in a script, are processed before any code within the script is executed. Declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called hoisting, as it appears that the variable declaration is moved to the top of the function, static initialization block, or script source in which it occurs.

Note: var declarations are only hoisted to the top of the current script. If you have two <script> elements within one HTML, the first script cannot access variables declared by the second before the second script has been processed and executed.

\n

js

\n
bla = 2;\nvar bla;\n
\n

This is implicitly understood as:

\n

js

\n
var bla;\nbla = 2;\n
\n

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are scoped to the current function.

Only a variable's declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached. Until then the variable remains undefined (but declared):

\n

js

\n
function doSomething() {\n  console.log(bar); // undefined\n  var bar = 111;\n  console.log(bar); // 111\n}\n
\n

This is implicitly understood as:

\n

js

\n
function doSomething() {\n  var bar;\n  console.log(bar); // undefined\n  bar = 111;\n  console.log(bar); // 111\n}\n
\n
\n

Redeclarations

\n
\n

Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless the declaration has an initializer.

\n

js

\n
var a = 1;\nvar a = 2;\nconsole.log(a); // 2\nvar a;\nconsole.log(a); // 2; not undefined\n
\n

var declarations can also be in the same scope as a function declaration. In this case, the var declaration's initializer always overrides the function's value, regardless of their relative position. This is because function declarations are hoisted before any initializer gets evaluated, so the initializer comes later and overrides the value.

\n

js

\n
var a = 1;\nfunction a() {}\nconsole.log(a); // 1\n
\n

var declarations cannot be in the same scope as a let, const, class, or import declaration.

\n

js

\n
var a = 1;\nlet a = 2; // SyntaxError: Identifier 'a' has already been declared\n
\n

Because var declarations are not scoped to blocks, this also applies to the following case:

\n

js

\n
let a = 1;\n{\n  var a = 1; // SyntaxError: Identifier 'a' has already been declared\n}\n
\n

It does not apply to the following case, where let is in a child scope of var, not the same scope:

\n

js

\n
var a = 1;\n{\n  let a = 2;\n}\n
\n

A var declaration within a function's body can have the same name as a parameter.

\n

js

\n
function foo(a) {\n  var a = 1;\n  console.log(a);\n}\n\nfoo(2); // Logs 1\n
\n

A var declaration within a catch block can have the same name as the catch-bound identifier, but only if the catch binding is a simple identifier, not a destructuring pattern. This is a deprecated syntax and you should not rely on it. In this case, the declaration is hoisted to outside the catch block, but any value assigned within the catch block is not visible outside.

\n

js

\n
try {\n  throw 1;\n} catch (e) {\n  var e = 2; // Works\n}\nconsole.log(e); // undefined\n
\n
\n

Examples

\n

Declaring and initializing two variables

\n
\n

js

\n
var a = 0,\n  b = 0;\n
\n

Assigning two variables with single string value

\n
\n
\n

js

\n
var a = \"A\";\nvar b = a;\n
\n

This is equivalent to:

\n

js

\n
var a, b = a = \"A\";\n
\n

Be mindful of the order:

\n

js

\n
var x = y,\n  y = \"A\";\nconsole.log(x, y); // undefined A\n
\n

Here, x and y are declared before any code is executed, but the assignments occur later. At the time x = y is evaluated, y exists so no ReferenceError is thrown and its value is undefined. So, x is assigned the undefined value. Then, y is assigned the value \"A\".

\n

Initialization of several variables

\n
\n

Be careful of the var x = y = 1 syntax — y is not actually declared as a variable, so y = 1 is an unqualified identifier assignment, which creates a global variable in non-strict mode.

\n

js

\n
var x = 0;\nfunction f() {\n  var x = y = 1; // Declares x locally; declares y globally.\n}\nf();\n\nconsole.log(x, y); // 0 1\n\n// In non-strict mode:\n// x is the global one as expected;\n// y is leaked outside of the function, though!\n
\n

The same example as above but with a strict mode:

\n

js

\n
\"use strict\";\n\nvar x = 0;\nfunction f() {\n  var x = y = 1; // ReferenceError: y is not defined\n}\nf();\n\nconsole.log(x, y);\n
\n
\n

Implicit globals and outer function scope

\n
\n

Variables that appear to be implicit globals may be references to variables in an outer function scope:

\n

js

\n
var x = 0; // Declares x within file scope, then assigns it a value of 0.\n\nconsole.log(typeof z); // \"undefined\", since z doesn't exist yet\n\nfunction a() {\n  var y = 2; // Declares y within scope of function a, then assigns it a value of 2.\n\n  console.log(x, y); // 0 2\n\n  function b() {\n    x = 3; // Assigns 3 to existing file scoped x.\n    y = 4; // Assigns 4 to existing outer y.\n    z = 5; // Creates a new global variable z, and assigns it a value of 5.\n    // (Throws a ReferenceError in strict mode.)\n  }\n\n  b(); // Creates z as a global variable.\n  console.log(x, y, z); // 3 4 5\n}\n\na(); // Also calls b.\nconsole.log(x, z); // 3 5\nconsole.log(typeof y); // \"undefined\", as y is local to function a\n
\n
\n

Declaration with destructuring

\n
\n

The left-hand side of each = can also be a binding pattern. This allows creating multiple variables at once.

\n

js

\n
const result = /(a+)(b+)(c+)/.exec(\"aaabcc\");\nvar [, a, b, c] = result;\nconsole.log(a, b, c); // \"aaa\" \"b\" \"cc\"\n
\n

For more information, see Destructuring assignment.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-variable-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
var11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\n

\n
\n", + "statements/let": "

let

The let declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value.

\n

Try it

\n

Syntax

\n
\n

js

\n
let name1;\nlet name1 = value1;\nlet name1 = value1, name2 = value2;\nlet name1, name2 = value2;\nlet name1 = value1, name2, /* …, */ nameN = valueN;\n
\n

Parameters

\n
nameN

The name of the variable to declare. Each must be a legal JavaScript identifier or a destructuring binding pattern.

\nvalueN Optional\n

Initial value of the variable. It can be any legal expression. Default value is undefined.

Description

\n
\n

The scope of a variable declared with let is one of the following curly-brace-enclosed syntaxes that most closely contains the let declaration:

Or the current module or script, if it's contained in none of these.

Compared with var, let declarations have the following differences:

Note that let is allowed as an identifier name when declared with var or function in non-strict mode, but you should avoid using let as an identifier name to prevent unexpected syntax ambiguities.

Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer let for non-primitives that are mutated.

The list that follows the let keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list.

\n

Temporal dead zone (TDZ)

\n
\n

A variable declared with let, const, or class is said to be in a \"temporal dead zone\" (TDZ) from the start of the block until code execution reaches the place where the variable is declared and initialized.

While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError. The variable is initialized with a value when execution reaches the place in the code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of undefined.

This differs from var variables, which will return a value of undefined if they are accessed before they are declared. The code below demonstrates the different result when let and var are accessed in code before the place where they are declared.

\n

js

\n
{\n  // TDZ starts at beginning of scope\n  console.log(bar); // \"undefined\"\n  console.log(foo); // ReferenceError: Cannot access 'foo' before initialization\n  var bar = 1;\n  let foo = 2; // End of TDZ (for foo)\n}\n
\n

The term \"temporal\" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position). For example, the code below works because, even though the function that uses the let variable appears before the variable is declared, the function is called outside the TDZ.

\n

js

\n
{\n  // TDZ starts at beginning of scope\n  const func = () => console.log(letVar); // OK\n\n  // Within the TDZ letVar access throws `ReferenceError`\n\n  let letVar = 3; // End of TDZ (for letVar)\n  func(); // Called outside TDZ!\n}\n
\n

Using the typeof operator for a let variable in its TDZ will throw a ReferenceError:

\n

js

\n
typeof i; // ReferenceError: Cannot access 'i' before initialization\nlet i = 10;\n
\n

This differs from using typeof for undeclared variables, and variables that hold a value of undefined:

\n

js

\n
console.log(typeof undeclaredVariable); // \"undefined\"\n
\n
\n

Redeclarations

\n
\n

let declarations cannot be in the same scope as any other declaration, including let, const, class, function, var, and import declaration.

\n

js

\n
{\n  let foo;\n  let foo; // SyntaxError: Identifier 'foo' has already been declared\n}\n
\n

A let declaration within a function's body cannot have the same name as a parameter. A let declaration within a catch block cannot have the same name as the catch-bound identifier.

\n

js

\n
function foo(a) {\n  let a = 1; // SyntaxError: Identifier 'a' has already been declared\n}\ntry {\n} catch (e) {\n  let e; // SyntaxError: Identifier 'e' has already been declared\n}\n
\n

If you're experimenting in a REPL, such as the Firefox web console (Tools > Web Developer > Web Console), and you run two let declarations with the same name in two separate inputs, you may get the same re-declaration error. See further discussion of this issue in Firefox bug 1580891. The Chrome console allows let re-declarations between different REPL inputs.

You may encounter errors in switch statements because there is only one block.

\n

js

\n
let x = 1;\n\nswitch (x) {\n  case 0:\n    let foo;\n    break;\n  case 1:\n    let foo; // SyntaxError: Identifier 'foo' has already been declared\n    break;\n}\n
\n

To avoid the error, wrap each case in a new block statement.

\n

js

\n
let x = 1;\n\nswitch (x) {\n  case 0: {\n    let foo;\n    break;\n  }\n  case 1: {\n    let foo;\n    break;\n  }\n}\n
\n
\n

Examples

\n

Scoping rules

\n
\n

Variables declared by let have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

\n

js

\n
function varTest() {\n  var x = 1;\n  {\n    var x = 2; // same variable!\n    console.log(x); // 2\n  }\n  console.log(x); // 2\n}\n\nfunction letTest() {\n  let x = 1;\n  {\n    let x = 2; // different variable\n    console.log(x); // 2\n  }\n  console.log(x); // 1\n}\n
\n

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

\n

js

\n
var x = \"global\";\nlet y = \"global\";\nconsole.log(this.x); // \"global\"\nconsole.log(this.y); // undefined\n
\n
\n

TDZ combined with lexical scoping

\n
\n

The following code results in a ReferenceError at the line shown:

\n

js

\n
function test() {\n  var foo = 33;\n  if (foo) {\n    let foo = foo + 55; // ReferenceError\n  }\n}\ntest();\n
\n

The if block is evaluated because the outer var foo has a value. However due to lexical scoping this value is not available inside the block: the identifier foo inside the if block is the let foo. The expression foo + 55 throws a ReferenceError because initialization of let foo has not completed — it is still in the temporal dead zone.

This phenomenon can be confusing in a situation like the following. The instruction let n of n.a is already inside the scope of the for...of loop's block. So, the identifier n.a is resolved to the property a of the n object located in the first part of the instruction itself (let n). This is still in the temporal dead zone as its declaration statement has not been reached and terminated.

\n

js

\n
function go(n) {\n  // n here is defined!\n  console.log(n); // { a: [1, 2, 3] }\n\n  for (let n of n.a) {\n    //          ^ ReferenceError\n    console.log(n);\n  }\n}\n\ngo({ a: [1, 2, 3] });\n
\n
\n

Other situations

\n
\n

When used inside a block, let limits the variable's scope to that block. Note the difference between var, whose scope is inside the function where it is declared.

\n

js

\n
var a = 1;\nvar b = 2;\n\n{\n  var a = 11; // the scope is global\n  let b = 22; // the scope is inside the block\n\n  console.log(a); // 11\n  console.log(b); // 22\n}\n\nconsole.log(a); // 11\nconsole.log(b); // 2\n
\n

However, this combination of var and let declarations below is a SyntaxError because var not being block-scoped, leading to them being in the same scope. This results in an implicit re-declaration of the variable.

\n

js

\n
let x = 1;\n\n{\n  var x = 2; // SyntaxError for re-declaration\n}\n
\n
\n

Declaration with destructuring

\n
\n

The left-hand side of each = can also be a binding pattern. This allows creating multiple variables at once.

\n

js

\n
const result = /(a+)(b+)(c+)/.exec(\"aaabcc\");\nlet [, a, b, c] = result;\nconsole.log(a, b, c); // \"aaa\" \"b\" \"cc\"\n
\n

For more information, see Destructuring assignment.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-let-and-const-declarations
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
let49
41–49Strict mode is required.
\n
14
12–14In Edge 12 and 13, let within a for loop initializer does not create a separate variable for each loop iteration as defined by ES2015. Instead, it behaves as though the loop were wrapped in a scoping block with the let immediately before the loop.
\n
44[\"Before Firefox 44, let is only available to code blocks in HTML wrapped in a <script type=\\\"application/javascript;version=1.7\\\"> block (or higher version) and has different semantics (e.g. no temporal dead zone).\", \"Before Firefox 46, a TypeError is thrown on redeclaration instead of a SyntaxError.\", \"Firefox 54 adds support of let in workers.\"]
11In Internet Explorer, let within a for loop initializer does not create a separate variable for each loop iteration as defined by ES2015. Instead, it behaves as though the loop were wrapped in a scoping block with the let immediately before the loop.
171049
41–49Strict mode is required.
\n
49
41–49Strict mode is required.
\n
44[\"Before Firefox 44, let is only available to code blocks in HTML wrapped in a <script type=\\\"application/javascript;version=1.7\\\"> block (or higher version) and has different semantics (e.g. no temporal dead zone).\", \"Before Firefox 46, a TypeError is thrown on redeclaration instead of a SyntaxError.\", \"Firefox 54 adds support of let in workers.\"]
18105.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\n

\n
\n", + "statements/const": "

const

The const declaration declares block-scoped local variables. The value of a constant can't be changed through reassignment using the assignment operator, but if a constant is an object, its properties can be added, updated, or removed.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
const name1 = value1;\nconst name1 = value1, name2 = value2;\nconst name1 = value1, name2 = value2, /* …, */ nameN = valueN;\n
\n
nameN

The name of the variable to declare. Each must be a legal JavaScript identifier or a destructuring binding pattern.

valueN

Initial value of the variable. It can be any legal expression.

\n

Description

\n
\n

The const declaration is very similar to let:

An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)

\n

js

\n
const FOO; // SyntaxError: Missing initializer in const declaration\n
\n

The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. You should understand const declarations as \"create a variable whose identity remains constant\", not \"whose value remains constant\" — or, \"create immutable bindings\", not \"immutable values\".

Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer let for non-primitives that are mutated.

The list that follows the const keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list.

\n

Examples

\n

Basic const usage

\n
\n

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters, especially for primitives because they are truly immutable.

\n

js

\n
// define MY_FAV as a constant and give it the value 7\nconst MY_FAV = 7;\n\nconsole.log(\"my favorite number is: \" + MY_FAV);\n
\n
\n

js

\n
// Re-assigning to a constant variable throws an error\nMY_FAV = 20; // TypeError: Assignment to constant variable\n\n// Redeclaring a constant throws an error\nconst MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared\nvar MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared\nlet MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared\n
\n
\n

Block scoping

\n
\n

It's important to note the nature of block scoping.

\n

js

\n
const MY_FAV = 7;\n\nif (MY_FAV === 7) {\n  // This is fine because it's in a new block scope\n  const MY_FAV = 20;\n  console.log(MY_FAV); // 20\n\n  // var declarations are not scoped to blocks so this throws an error\n  var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared\n}\n\nconsole.log(MY_FAV); // 7\n
\n
\n

const in objects and arrays

\n
\n

const also works on objects and arrays. Attempting to overwrite the object throws an error \"Assignment to constant variable\".

\n

js

\n
const MY_OBJECT = { key: \"value\" };\nMY_OBJECT = { OTHER_KEY: \"value\" };\n
\n

However, object keys are not protected, so the following statement is executed without problem.

\n

js

\n
MY_OBJECT.key = \"otherValue\";\n
\n

You would need to use Object.freeze() to make an object immutable.

The same applies to arrays. Assigning a new array to the variable throws an error \"Assignment to constant variable\".

\n

js

\n
const MY_ARRAY = [];\nMY_ARRAY = [\"B\"];\n
\n

Still, it's possible to push items into the array and thus mutate it.

\n

js

\n
MY_ARRAY.push(\"A\"); // [\"A\"]\n
\n
\n

Declaration with destructuring

\n
\n

The left-hand side of each = can also be a binding pattern. This allows creating multiple variables at once.

\n

js

\n
const result = /(a+)(b+)(c+)/.exec(\"aaabcc\");\nconst [, a, b, c] = result;\nconsole.log(a, b, c); // \"aaa\" \"b\" \"cc\"\n
\n

For more information, see Destructuring assignment.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-let-and-const-declarations
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
const2112
36[\"Before Firefox 13, const is implemented, but re-assignment is not failing.\", \"Before Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError.\"]
1195.14.425
36[\"Before Firefox 13, const is implemented, but re-assignment is not failing.\", \"Before Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError.\"]
10.151.51.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\n

\n
\n", + "statements/class": "

class

\n

The class declaration creates a binding of a new class to a given name.

You can also define classes using the class expression.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
class name {\n  // class body\n}\nclass name extends otherName {\n  // class body\n}\n
\n

Description

\n
\n

The class body of a class declaration is executed in strict mode. The class declaration is very similar to let:

Outside the class body, class declarations can be re-assigned like let, but you should avoid doing so. Within the class body, the binding is constant like const.

\n

js

\n
class Foo {\n  static {\n    Foo = 1; // TypeError: Assignment to constant variable.\n  }\n}\n\nclass Foo2 {\n  bar = (Foo2 = 1); // TypeError: Assignment to constant variable.\n}\n\nclass Foo3 {}\nFoo3 = 1;\nconsole.log(Foo3); // 1\n
\n
\n

Examples

\n

A simple class declaration

\n
\n

In the following example, we first define a class named Rectangle, then extend it to create a class named FilledRectangle.

Note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used.

\n

js

\n
class Rectangle {\n  constructor(height, width) {\n    this.name = \"Rectangle\";\n    this.height = height;\n    this.width = width;\n  }\n}\n\nclass FilledRectangle extends Rectangle {\n  constructor(height, width, color) {\n    super(height, width);\n    this.name = \"Filled rectangle\";\n    this.color = color;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-class-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
class49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
10.149
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
10.35.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class\n

\n
\n", + "statements/do...while": "

do...while

The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
do\n  statement\nwhile (condition);\n
\n
statement

A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ /* ... */ }) to group those statements.

condition

An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed. When condition evaluates to false, control passes to the statement following the do...while.

Note: Use the break statement to stop a loop before condition evaluates to false.

\n

Examples

\n

Using do...while\n

\n
\n

In the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.

\n

js

\n
let result = \"\";\nlet i = 0;\ndo {\n  i += 1;\n  result += `${i}`;\n} while (i > 0 && i < 5);\n// Despite i === 0 this will still loop as it starts off without the test\n\nconsole.log(result);\n
\n
\n

Using an assignment as a condition

\n
\n

In some cases, it can make sense to use an assignment as a condition, such as this:

\n

js

\n
do {\n  // …\n} while ((match = regexp.exec(str)));\n
\n

But when you do, there are readability tradeoffs. The while documentation has a Using an assignment as a condition section with our recommendations.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-do-while-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
do...while11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while\n

\n
\n", + "statements/for...in": "

for...in

The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

\n

Try it

\n

Syntax

\n
\n

js

\n
for (variable in object)\n  statement\n
\n

Parameters

\n
variable

Receives a string property name on each iteration. May be either a declaration with const, let, or var, or an assignment target (e.g. a previously declared variable, an object property, or a destructuring assignment pattern). Variables declared with var are not local to the loop, i.e. they are in the same scope the for...in loop is in.

object

Object whose non-symbol enumerable properties are iterated over.

statement

A statement to be executed on every iteration. May reference variable. You can use a block statement to execute multiple statements.

Description

\n
\n

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).

A for...in loop only iterates over enumerable, non-symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Array.prototype and Object.prototype, such as Array's indexOf() method or Object's toString() method, which will not be visited in the for...in loop.

The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.

The variable part of for...in accepts anything that can come before the = operator. You can use const to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use let. You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y in iterable) to assign the value to an object property.

A legacy syntax allows var declarations of the loop variable to have an initializer. This throws a syntax error in strict mode and is ignored in non–strict mode.

\n

Deleted, added, or modified properties

\n
\n

for...in visits property keys in the following fashion:

  1. It first gets all own string keys of the current object, in a fashion very similar to Object.getOwnPropertyNames().
  2. For each key, if no string with the same value has ever been visited, the property descriptor is retrieved and the property is only visited if it is enumerable. However, this property string will be marked as visited even if it's not enumerable.
  3. Then, the current object is replaced with its prototype, and the process is repeated.

This means:

In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. The spec explicitly allows the implementation to not follow the algorithm above in one of the following cases:

In these cases, implementations may behave differently from what you may expect, or even from each other.

\n

Array iteration and for...in

\n
\n

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. The for...in loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of for...in close to normal array iteration. However, the for...in loop will return all enumerable properties, including those with non–integer names and those that are inherited. Unlike for...of, for...in uses property enumeration instead of the array's iterator. In sparse arrays, for...of will visit the empty slots, but for...in will not.

It is better to use a for loop with a numeric index, Array.prototype.forEach(), or the for...of loop, because they will return the index as a number instead of a string, and also avoid non-index properties.

\n

Iterating over own properties only

\n
\n

If you only want to consider properties attached to the object itself, and not its prototypes, you can use one of the following techniques:

Object.keys will return a list of enumerable own string properties, while Object.getOwnPropertyNames will also contain non-enumerable ones.

Many JavaScript style guides and linters recommend against the use of for...in, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used for...of loop. for...in is most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). In situations where objects are used as ad hoc key-value pairs, for...in allows you check if any of those keys hold a particular value.

\n

Examples

\n

Using for...in

\n
\n

The for...in loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.

\n

js

\n
const obj = { a: 1, b: 2, c: 3 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n}\n\n// Logs:\n// \"obj.a = 1\"\n// \"obj.b = 2\"\n// \"obj.c = 3\"\n
\n
\n

Iterating own properties

\n
\n

The following function illustrates the use of Object.hasOwn(): the inherited properties are not displayed.

\n

js

\n
const triangle = { a: 1, b: 2, c: 3 };\n\nfunction ColoredTriangle() {\n  this.color = \"red\";\n}\n\nColoredTriangle.prototype = triangle;\n\nconst obj = new ColoredTriangle();\n\nfor (const prop in obj) {\n  if (Object.hasOwn(obj, prop)) {\n    console.log(`obj.${prop} = ${obj[prop]}`);\n  }\n}\n\n// Logs:\n// \"obj.color = red\"\n
\n
\n

Concurrent modification

\n
\n

Warning: You should not write code like this yourself. It is only included here to illustrate the behavior of for...in in some corner cases.

Properties added to the current object during iteration are never visited:

\n

js

\n
const obj = { a: 1, b: 2 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n  obj.c = 3;\n}\n\n// Logs:\n// obj.a = 1\n// obj.b = 2\n
\n

Shadowed properties are only visited once:

\n

js

\n
const proto = { a: 1 };\nconst obj = { __proto__: proto, a: 2 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n}\n\n// Logs:\n// obj.a = 2\n\nObject.defineProperty(obj, \"a\", { enumerable: false });\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n}\n// Logs nothing, because the first \"a\" property visited is non-enumerable.\n
\n

In addition, consider the following cases, where the behavior is unspecified, and implementations tend to diverge from the specified algorithm:

Changing the prototype during iteration:

\n

js

\n
const obj = { a: 1, b: 2 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n  Object.setPrototypeOf(obj, { c: 3 });\n}\n
\n

Deleting a property during iteration:

\n

js

\n
const obj = { a: 1, b: 2, c: 3 };\n\n// Deleting a property before it is visited\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n  delete obj.c;\n}\n\nconst obj2 = { a: 1, b: 2, c: 3 };\n\n// Deleting a property after it is visited\nfor (const prop in obj2) {\n  console.log(`obj2.${prop} = ${obj2[prop]}`);\n  delete obj2.a;\n}\n
\n

Enumerable properties added to the prototype during iteration:

\n

js

\n
const proto = {};\nconst obj = { __proto__: proto, a: 1, b: 2 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n  proto.c = 3;\n}\n
\n

Changing the enumerability of a property during iteration:

\n

js

\n
const obj = { a: 1, b: 2, c: 3 };\n\nfor (const prop in obj) {\n  console.log(`obj.${prop} = ${obj[prop]}`);\n  Object.defineProperty(obj, \"c\", { enumerable: false });\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-for-in-and-for-of-statements
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
for...in11213214.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\n

\n
\n", + "statements/for-await...of": "

for await...of

The for await...of statement creates a loop iterating over async iterable objects as well as sync iterables. This statement can only be used in contexts where await can be used, which includes inside an async function body and in a module.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
for await (variable of iterable)\n  statement\n
\n
variable

Receives a value from the sequence on each iteration. May be either a declaration with const, let, or var, or an assignment target (e.g. a previously declared variable, an object property, or a destructuring assignment pattern). Variables declared with var are not local to the loop, i.e. they are in the same scope the for await...of loop is in.

iterable

An async iterable or sync iterable. The source of the sequence of values on which the loop operates.

statement

A statement to be executed on every iteration. May reference variable. You can use a block statement to execute multiple statements.

\n

Description

\n
\n

When a for await...of loop iterates over an iterable, it first gets the iterable's [@@asyncIterator]() method and calls it, which returns an async iterator. If the @asyncIterator method does not exist, it then looks for an [@@iterator]() method, which returns a sync iterator. The sync iterator returned is then wrapped into an async iterator by wrapping every object returned from the next(), return(), and throw() methods into a resolved or rejected promise, with the value property resolved if it's also a promise. The loop then repeatedly calls the final async iterator's next() method and awaits the returned promise, producing the sequence of values to be assigned to variable.

If the for await...of loop exited early (e.g. a break statement is encountered or an error is thrown), the return() method of the iterator is called to perform any cleanup. The returned promise is awaited before the loop exits.

for await...of generally functions the same as the for...of loop and shares many of the same syntax and semantics. There are a few differences:

\n

Examples

\n

Iterating over async iterables

\n
\n

You can also iterate over an object that explicitly implements async iterable protocol:

\n

js

\n
const LIMIT = 3;\n\nconst asyncIterable = {\n  [Symbol.asyncIterator]() {\n    let i = 0;\n    return {\n      next() {\n        const done = i === LIMIT;\n        const value = done ? undefined : i++;\n        return Promise.resolve({ value, done });\n      },\n      return() {\n        // This will be reached if the consumer called 'break' or 'return' early in the loop.\n        return { done: true };\n      },\n    };\n  },\n};\n\n(async () => {\n  for await (const num of asyncIterable) {\n    console.log(num);\n  }\n})();\n// 0\n// 1\n// 2\n
\n
\n

Iterating over async generators

\n
\n

Since the return values of async generator functions conform to the async iterable protocol, they can be looped using for await...of.

\n

js

\n
async function* asyncGenerator() {\n  let i = 0;\n  while (i < 3) {\n    yield i++;\n  }\n}\n\n(async () => {\n  for await (const num of asyncGenerator()) {\n    console.log(num);\n  }\n})();\n// 0\n// 1\n// 2\n
\n

For a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an API.

This example first creates an async iterable for a stream of data, then uses it to find the size of the response from the API.

\n

js

\n
async function* streamAsyncIterable(stream) {\n  const reader = stream.getReader();\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) return;\n      yield value;\n    }\n  } finally {\n    reader.releaseLock();\n  }\n}\n\n// Fetches data from URL and calculates response size using the async generator.\nasync function getResponseSize(url) {\n  const response = await fetch(url);\n  // Will hold the size of the response, in bytes.\n  let responseSize = 0;\n  // The for-await-of loop. Async iterates over each portion of the response.\n  for await (const chunk of streamAsyncIterable(response.body)) {\n    // Incrementing the total response length.\n    responseSize += chunk.length;\n  }\n\n  console.log(`Response Size: ${responseSize} bytes`); // \"Response Size: 1071472\"\n  return responseSize;\n}\ngetResponseSize(\"https://jsonplaceholder.typicode.com/photos\");\n
\n
\n

Iterating over sync iterables and generators

\n
\n

for await...of loop also consumes sync iterables and generators. In that case it internally awaits emitted values before assign them to the loop control variable.

\n

js

\n
function* generator() {\n  yield 0;\n  yield 1;\n  yield Promise.resolve(2);\n  yield Promise.resolve(3);\n  yield 4;\n}\n\n(async () => {\n  for await (const num of generator()) {\n    console.log(num);\n  }\n})();\n// 0\n// 1\n// 2\n// 3\n// 4\n\n// compare with for-of loop:\n\nfor (const numOrPromise of generator()) {\n  console.log(numOrPromise);\n}\n// 0\n// 1\n// Promise { 2 }\n// Promise { 3 }\n// 4\n
\n

Note: Be aware of yielding rejected promises from a sync generator. In such case, for await...of throws when consuming the rejected promise and DOESN'T CALL finally blocks within that generator. This can be undesirable if you need to free some allocated resources with try/finally.

\n

js

\n
function* generatorWithRejectedPromises() {\n  try {\n    yield 0;\n    yield 1;\n    yield Promise.resolve(2);\n    yield Promise.reject(3);\n    yield 4;\n    throw 5;\n  } finally {\n    console.log(\"called finally\");\n  }\n}\n\n(async () => {\n  try {\n    for await (const num of generatorWithRejectedPromises()) {\n      console.log(num);\n    }\n  } catch (e) {\n    console.log(\"caught\", e);\n  }\n})();\n// 0\n// 1\n// 2\n// caught 3\n\n// compare with for-of loop:\n\ntry {\n  for (const numOrPromise of generatorWithRejectedPromises()) {\n    console.log(numOrPromise);\n  }\n} catch (e) {\n  console.log(\"caught\", e);\n}\n// 0\n// 1\n// Promise { 2 }\n// Promise { <rejected> 3 }\n// 4\n// caught 5\n// called finally\n
\n

To make finally blocks of a sync generator always called, use the appropriate form of the loop — for await...of for the async generator and for...of for the sync one — and await yielded promises explicitly inside the loop.

\n

js

\n
(async () => {\n  try {\n    for (const numOrPromise of generatorWithRejectedPromises()) {\n      console.log(await numOrPromise);\n    }\n  } catch (e) {\n    console.log(\"caught\", e);\n  }\n})();\n// 0\n// 1\n// 2\n// caught 3\n// called finally\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-for-in-and-for-of-statements
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
for-await...of637957No501263635746128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of\n

\n
\n", + "statements/empty": "

Empty statement

An empty statement is used to provide no statement, although the JavaScript syntax would expect one.

\n

Try it

\n

Syntax

\n
\n

js

\n
;\n
\n

Description

\n
\n

The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one.

The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.

\n

Examples

\n

Empty loop body

\n
\n

The empty statement is sometimes used with loop statements. See the following example with an empty loop body:

\n

js

\n
const arr = [1, 2, 3];\n\n// Assign all array values to 0\nfor (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;\n\nconsole.log(arr);\n// [0, 0, 0]\n
\n
\n

Unintentional usage

\n
\n

It is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon.

In the following example, the usage is probably not intentional:

\n

js

\n
if (condition);      // Caution, this \"if\" does nothing!\n  killTheUniverse(); // So this always gets executed!!!\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-empty-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Empty31213354.418410.14.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/Empty\n

\n
\n", + "statements/function": "

function

\n

The function declaration creates a binding of a new function to a given name.

You can also define functions using the function expression.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
function name(param0) {\n  statements\n}\nfunction name(param0, param1) {\n  statements\n}\nfunction name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Parameters

\n
name

The function name.

\nparam Optional\n

The name of a formal parameter for the function. Maximum number of arguments varies in different engines. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements which comprise the body of the function.

Description

\n
\n

A function declaration creates a Function object. Each time when a function is called, it returns the value specified by the last executed return statement, or undefined if the end of the function body is reached. See functions for detailed information on functions.

function declarations behave like a mix of var and let:

\n

Block-level function declaration

\n
\n

Warning: In non-strict mode, function declarations inside blocks behave strangely. Only declare functions in blocks if you are in strict mode.

Functions can be conditionally declared — that is, a function statement can be nested within an if statement. However, in non-strict mode, the results are inconsistent across implementations.

\n

js

\n
console.log(\n  `'foo' name ${\n    \"foo\" in globalThis ? \"is\" : \"is not\"\n  } global. typeof foo is ${typeof foo}`,\n);\nif (false) {\n  function foo() {\n    return 1;\n  }\n}\n\n// In Chrome:\n// 'foo' name is global. typeof foo is undefined\n//\n// In Firefox:\n// 'foo' name is global. typeof foo is undefined\n//\n// In Safari:\n// 'foo' name is global. typeof foo is function\n
\n

The scoping and hoisting effect won't change regardless of whether the if body is actually executed.

\n

js

\n
console.log(\n  `'foo' name ${\n    \"foo\" in globalThis ? \"is\" : \"is not\"\n  } global. typeof foo is ${typeof foo}`,\n);\nif (true) {\n  function foo() {\n    return 1;\n  }\n}\n\n// In Chrome:\n// 'foo' name is global. typeof foo is undefined\n//\n// In Firefox:\n// 'foo' name is global. typeof foo is undefined\n//\n// In Safari:\n// 'foo' name is global. typeof foo is function\n
\n

In strict mode, block-level function declarations are scoped to that block and are hoisted to the top of the block.

\n

js

\n
\"use strict\";\n\n{\n  foo(); // Logs \"foo\"\n  function foo() {\n    console.log(\"foo\");\n  }\n}\n\nconsole.log(\n  `'foo' name ${\n    \"foo\" in globalThis ? \"is\" : \"is not\"\n  } global. typeof foo is ${typeof foo}`,\n);\n// 'foo' name is not global. typeof foo is undefined\n
\n
\n

Hoisting

\n
\n

Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. You can use the function before you declared it:

\n

js

\n
hoisted(); // Logs \"foo\"\n\nfunction hoisted() {\n  console.log(\"foo\");\n}\n
\n

Note that function expressions are not hoisted:

\n

js

\n
notHoisted(); // TypeError: notHoisted is not a function\n\nvar notHoisted = function () {\n  console.log(\"bar\");\n};\n
\n
\n

Redeclarations

\n
\n

Whether function declarations can be redeclared in the same scope depends on what scope it's contained in.

At the top level of a script, function declarations behave like var and can be redeclared by another function or var but not by let, const, or class.

\n

js

\n
function a(b) {}\nfunction a(b, c) {}\nconsole.log(a.length); // 2\nlet a = 2; // SyntaxError: Identifier 'a' has already been declared\n
\n

When function declarations are redeclared by var, the var declaration's initializer always overrides the function's value, regardless of their relative position. This is because function declarations are hoisted before any initializer gets evaluated, so the initializer comes later and overrides the value.

\n

js

\n
var a = 1;\nfunction a() {}\nconsole.log(a); // 1\n
\n

At the top level of a function's body, function also behaves like var and can be redeclared or have the same name as a parameter.

\n

js

\n
function foo(a) {\n  function a() {}\n  console.log(typeof a);\n}\n\nfoo(2); // Logs \"function\"\n
\n

At the top level of a module or a block in strict mode, function declarations behave like let and cannot be redeclared by any other declaration.

\n

js

\n
// Assuming current source is a module\nfunction foo() {}\nfunction foo() {} // SyntaxError: Identifier 'foo' has already been declared\n
\n
\n

js

\n
\"use strict\";\n{\n  function foo() {}\n  function foo() {} // SyntaxError: Identifier 'foo' has already been declared\n}\n
\n

A function declaration within a catch block cannot have the same name as the catch-bound identifier, even in non-strict mode.

\n

js

\n
try {\n} catch (e) {\n  function e() {} // SyntaxError: Identifier 'e' has already been declared\n}\n
\n
\n

Examples

\n

Using function

\n
\n

The following code declares a function that returns the total amount of sales, when given the number of units sold of three products.

\n

js

\n
function calcSales(unitsA, unitsB, unitsC) {\n  return unitsA * 79 + unitsB * 129 + unitsC * 699;\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
function11213314.418410.111.01.00.10.0
trailing_comma_in_parameters581452No451058585243107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\n

\n
\n", + "statements/function*": "

function*

\n

The function* declaration creates a binding of a new generator function to a given name. A generator function can be exited and later re-entered, with its context (variable bindings) saved across re-entrances.

You can also define generator functions using the function* expression.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
function* name(param0) {\n  statements\n}\nfunction* name(param0, param1) {\n  statements\n}\nfunction* name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: Generator functions do not have arrow function counterparts.

Note: function and * are separate tokens, so they can be separated by whitespace or line terminators.

\n

Parameters

\n
name

The function name.

\nparam Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements comprising the body of the function.

Description

\n
\n

A function* declaration creates a GeneratorFunction object. Each time when a generator function is called, it returns a new Generator object, which conforms to the iterator protocol. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next().

Generators in JavaScript — especially when combined with Promises — are a very powerful tool for asynchronous programming as they mitigate — if not entirely eliminate -- the problems with callbacks, such as Callback Hell and Inversion of Control. However, an even simpler solution to these problems can be achieved with async functions.

A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). If a value is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error thrown inside the generator will make the generator finished — unless caught within the generator's body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}.

function* declarations behave similar to function declarations — they are hoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

\n

Examples

\n

Simple example

\n
\n

js

\n
function* idMaker() {\n  let index = 0;\n  while (true) {\n    yield index++;\n  }\n}\n\nconst gen = idMaker();\n\nconsole.log(gen.next().value); // 0\nconsole.log(gen.next().value); // 1\nconsole.log(gen.next().value); // 2\nconsole.log(gen.next().value); // 3\n// …\n
\n

Example with yield*

\n
\n

js

\n
function* anotherGenerator(i) {\n  yield i + 1;\n  yield i + 2;\n  yield i + 3;\n}\n\nfunction* generator(i) {\n  yield i;\n  yield* anotherGenerator(i);\n  yield i + 10;\n}\n\nconst gen = generator(10);\n\nconsole.log(gen.next().value); // 10\nconsole.log(gen.next().value); // 11\nconsole.log(gen.next().value); // 12\nconsole.log(gen.next().value); // 13\nconsole.log(gen.next().value); // 20\n
\n

Passing arguments into Generators

\n
\n

js

\n
function* logGenerator() {\n  console.log(0);\n  console.log(1, yield);\n  console.log(2, yield);\n  console.log(3, yield);\n}\n\nconst gen = logGenerator();\n\n// the first call of next executes from the start of the function\n// until the first yield statement\ngen.next(); // 0\ngen.next(\"pretzel\"); // 1 pretzel\ngen.next(\"california\"); // 2 california\ngen.next(\"mayonnaise\"); // 3 mayonnaise\n
\n

Return statement in a generator

\n
\n

js

\n
function* yieldAndReturn() {\n  yield \"Y\";\n  return \"R\";\n  yield \"unreachable\";\n}\n\nconst gen = yieldAndReturn();\nconsole.log(gen.next()); // { value: \"Y\", done: false }\nconsole.log(gen.next()); // { value: \"R\", done: true }\nconsole.log(gen.next()); // { value: undefined, done: true }\n
\n

Generator as an object property

\n
\n

js

\n
const someObj = {\n  *generator() {\n    yield \"a\";\n    yield \"b\";\n  },\n};\n\nconst gen = someObj.generator();\n\nconsole.log(gen.next()); // { value: 'a', done: false }\nconsole.log(gen.next()); // { value: 'b', done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n
\n

Generator as an object method

\n
\n

js

\n
class Foo {\n  *generator() {\n    yield 1;\n    yield 2;\n    yield 3;\n  }\n}\n\nconst f = new Foo();\nconst gen = f.generator();\n\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { value: 3, done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n
\n

Generator as a computed property

\n
\n

js

\n
class Foo {\n  *[Symbol.iterator]() {\n    yield 1;\n    yield 2;\n  }\n}\n\nconst SomeObj = {\n  *[Symbol.iterator]() {\n    yield \"a\";\n    yield \"b\";\n  },\n};\n\nconsole.log(Array.from(new Foo())); // [ 1, 2 ]\nconsole.log(Array.from(SomeObj)); // [ 'a', 'b' ]\n
\n

Generators are not constructable

\n
\n

js

\n
function* f() {}\nconst obj = new f(); // throws \"TypeError: f is not a constructor\n
\n

Generator defined in an expression

\n
\n

js

\n
const foo = function* () {\n  yield 10;\n  yield 20;\n};\n\nconst bar = foo();\nconsole.log(bar.next()); // {value: 10, done: false}\n
\n

Generator example

\n
\n

js

\n
function* powers(n) {\n  //endless loop to generate\n  for (let current = n; ; current *= n) {\n    yield current;\n  }\n}\n\nfor (const power of powers(2)) {\n  // controlling generator\n  if (power > 32) {\n    break;\n  }\n  console.log(power);\n  // 2\n  // 4\n  // 8\n  // 16\n  // 32\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
IteratorResult_object491329No361049492936105.01.06.0.0
function*391326No261039392626104.01.04.0.0
not_constructable_with_new501343No371050504337105.01.06.0.0
trailing_comma_in_parameters581452No451058585243107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*\n

\n
\n", + "statements/async_function*": "

async function*

\n

The async function* declaration creates a binding of a new async generator function to a given name.

You can also define async generator functions using the async function* expression.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
async function* name(param0) {\n  statements\n}\nasync function* name(param0, param1) {\n  statements\n}\nasync function* name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: Async generator functions do not have arrow function counterparts.

Note: function and * are separate tokens, so they can be separated by whitespace or line terminators. However, there cannot be a line terminator between async and function, otherwise a semicolon is automatically inserted, causing async to become an identifier and the rest to become a function* declaration.

\n

Parameters

\n
name

The function name.

\nparam Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements comprising the body of the function.

Description

\n
\n

An async function* declaration creates an AsyncGeneratorFunction object. Each time when an async generator function is called, it returns a new AsyncGenerator object, which conforms to the async iterator protocol. Every call to next() returns a Promise that resolves to the iterator result object.

An async generator function combines the features of async functions and generator functions. You can use both the await and yield keywords within the function body. This empowers you to handle asynchronous tasks ergonomically with await, while leveraging the lazy nature of generator functions.

When a promise is yielded from an async generator, the iterator result promise's eventual state will match that of the yielded promise. For example:

\n

js

\n
async function* foo() {\n  yield Promise.reject(1);\n}\n\nfoo()\n  .next()\n  .catch((e) => console.error(e));\n
\n

1 will be logged, because if the yielded promise rejects, the iterator result will reject as well. The value property of an async generator's resolved result will not be another promise.

async function* declarations behave similar to function declarations — they are hoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

\n

Examples

\n

Declaring an async generator function

\n
\n

Async generator functions always produce promises of results — even when each yield step is synchronous.

\n

js

\n
async function* myGenerator(step) {\n  await new Promise((resolve) => setTimeout(resolve, 10));\n  yield 0;\n  yield step;\n  yield step * 2;\n}\n\nconst gen = myGenerator(2);\ngen\n  .next()\n  .then((res) => {\n    console.log(res); // { value: 0, done: false }\n    return gen.next();\n  })\n  .then((res) => {\n    console.log(res); // { value: 2, done: false }\n    return gen.next();\n  })\n  .then((res) => {\n    console.log(res); // { value: 4, done: false }\n    return gen.next();\n  })\n  .then((res) => {\n    console.log(res); // { value: undefined, done: true }\n    return gen.next();\n  });\n
\n
\n

Using an async generator function to read a series of files

\n
\n

In this example, we read a series of files and only access its content when requested, using Node's fs/promises module.

\n

js

\n
async function* readFiles(directory) {\n  const files = await fs.readdir(directory);\n  for (const file of files) {\n    const stats = await fs.stat(file);\n    if (stats.isFile()) {\n      yield {\n        name: file,\n        content: await fs.readFile(file, \"utf8\"),\n      };\n    }\n  }\n}\n\nconst files = readFiles(\".\");\nconsole.log((await files.next()).value);\n// Possible output: { name: 'file1.txt', content: '...' }\nconsole.log((await files.next()).value);\n// Possible output: { name: 'file2.txt', content: '...' }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-generator-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
async_function*637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*\n

\n
\n", + "statements/for": "

for

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
for (initialization; condition; afterthought)\n  statement\n
\n
\ninitialization Optional\n

An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.

The result of this expression is discarded.

\ncondition Optional\n

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. If the expression evaluates to false, execution exits the loop and goes to the first statement after the for construct.

This conditional test is optional. If omitted, the condition always evaluates to true.

\nafterthought Optional\n

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.

statement

A statement that is executed as long as the condition evaluates to true. You can use a block statement to execute multiple statements. To execute no statement within the loop, use an empty statement (;).

\n

Examples

\n

Using for

\n
\n

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

\n

js

\n
for (let i = 0; i < 9; i++) {\n  console.log(i);\n  // more statements\n}\n
\n
\n

Initialization block syntax

\n
\n

The initialization block accepts both expressions and variable declarations. However, expressions cannot use the in operator unparenthesized, because that is ambiguous with a for...in loop.

\n

js

\n
for (let i = \"start\" in window ? window.start : 0; i < 9; i++) {\n  console.log(i);\n}\n// SyntaxError: 'for-in' loop variable declaration may not have an initializer.\n
\n
\n

js

\n
// Parenthesize the whole initializer\nfor (let i = (\"start\" in window ? window.start : 0); i < 9; i++) {\n  console.log(i);\n}\n\n// Parenthesize the `in` expression\nfor (let i = (\"start\" in window) ? window.start : 0; i < 9; i++) {\n  console.log(i);\n}\n
\n
\n

Optional for expressions

\n
\n

All three expressions in the head of the for loop are optional. For example, it is not required to use the initialization block to initialize variables:

\n

js

\n
let i = 0;\nfor (; i < 9; i++) {\n  console.log(i);\n  // more statements\n}\n
\n

Like the initialization block, the condition part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

\n

js

\n
for (let i = 0; ; i++) {\n  console.log(i);\n  if (i > 3) break;\n  // more statements\n}\n
\n

You can also omit all three expressions. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

\n

js

\n
let i = 0;\n\nfor (;;) {\n  if (i > 3) break;\n  console.log(i);\n  i++;\n}\n
\n

However, in the case where you are not fully using all three expression positions — especially if you are not declaring variables with the first expression but mutating something in the upper scope — consider using a while loop instead, which makes the intention clearer.

\n

js

\n
let i = 0;\n\nwhile (i <= 3) {\n  console.log(i);\n  i++;\n}\n
\n
\n

Lexical declarations in the initialization block

\n
\n

Declaring a variable within the initialization block has important differences from declaring it in the upper scope, especially when creating a closure within the loop body. For example, for the code below:

\n

js

\n
for (let i = 0; i < 3; i++) {\n  setTimeout(() => {\n    console.log(i);\n  }, 1000);\n}\n
\n

It logs 0, 1, and 2, as expected. However, if the variable is defined in the upper scope:

\n

js

\n
let i = 0;\nfor (; i < 3; i++) {\n  setTimeout(() => {\n    console.log(i);\n  }, 1000);\n}\n
\n

It logs 3, 3, and 3. The reason is that each setTimeout creates a new closure that closes over the i variable, but if the i is not scoped to the loop body, all closures will reference the same variable when they eventually get called — and due to the asynchronous nature of setTimeout, it will happen after the loop has already exited, causing the value of i in all queued callbacks' bodies to have the value of 3.

This also happens if you use a var statement as the initialization, because variables declared with var are only function-scoped, but not lexically scoped (i.e. they can't be scoped to the loop body).

\n

js

\n
for (var i = 0; i < 3; i++) {\n  setTimeout(() => {\n    console.log(i);\n  }, 1000);\n}\n// Logs 3, 3, 3\n
\n

The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within the condition and afterthought parts. More precisely, let declarations are special-cased by for loops — if initialization is a let declaration, then every time, after the loop body is evaluated, the following happens:

  1. A new lexical scope is created with new let-declared variables.
  2. The binding values from the last iteration are used to re-initialize the new variables.
  3. \nafterthought is evaluated in the new scope.

So re-assigning the new variables within afterthought does not affect the bindings from the previous iteration.

Creating closures allows you to get hold of a binding during any particular iteration. This explains why closures created within the initialization section do not get updated by re-assignments of i in the afterthought.

\n

js

\n
for (let i = 0, getI = () => i; i < 3; i++) {\n  console.log(getI());\n}\n// Logs 0, 0, 0\n
\n

This does not log \"0, 1, 2\", like what would happen if getI is declared in the loop body. This is because getI is not re-evaluated on each iteration — rather, the function is created once and closes over the i variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value of i actually create new variables called i, which getI does not see. A way to fix this is to re-compute getI every time i updates:

\n

js

\n
for (let i = 0, getI = () => i; i < 3; i++, getI = () => i) {\n  console.log(getI());\n}\n// Logs 0, 1, 2\n
\n

In fact, you can capture the initial binding of the i variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding of i.

\n

js

\n
for (\n  let i = 0, getI = () => i, incrementI = () => i++;\n  getI() < 3;\n  incrementI()\n) {\n  console.log(i);\n}\n// Logs 0, 0, 0\n
\n

This logs \"0, 0, 0\", because the i variable in each loop evaluation is actually a separate variable, but getI and incrementI both read and write the initial binding of i, not what was subsequently declared.

\n

Using for without a body

\n
\n

The following for cycle calculates the offset position of a node in the afterthought section, and therefore it does not require the use of a statement section, a semicolon is used instead.

\n

js

\n
function showOffsetPos(id) {\n  let left = 0;\n  let top = 0;\n  for (\n    let itNode = document.getElementById(id); // initialization\n    itNode; // condition\n    left += itNode.offsetLeft,\n      top += itNode.offsetTop,\n      itNode = itNode.offsetParent // afterthought\n  ); // semicolon\n\n  console.log(\n    `Offset position of \"${id}\" element:\nleft: ${left}px;\ntop: ${top}px;`,\n  );\n}\n\nshowOffsetPos(\"content\");\n\n// Logs:\n// Offset position of \"content\" element:\n// left: 0px;\n// top: 153px;\n
\n

Note that the semicolon after the for statement is mandatory, because it stands as an empty statement. Otherwise, the for statement acquires the following console.log line as its statement section, which makes the log execute multiple times.

\n

Using for with two iterating variables

\n
\n

You can create two counters that are updated simultaneously in a for loop using the comma operator. Multiple let and var declarations can also be joined with commas.

\n

js

\n
const arr = [1, 2, 3, 4, 5, 6];\nfor (let l = 0, r = arr.length - 1; l < r; l++, r--) {\n  console.log(arr[l], arr[r]);\n}\n// 1 6\n// 2 5\n// 3 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-for-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
for11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\n

\n
\n", + "statements/for...of": "

for...of

The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
for (variable of iterable)\n  statement\n
\n
variable

Receives a value from the sequence on each iteration. May be either a declaration with const, let, or var, or an assignment target (e.g. a previously declared variable, an object property, or a destructuring assignment pattern). Variables declared with var are not local to the loop, i.e. they are in the same scope the for...of loop is in.

iterable

An iterable object. The source of the sequence of values on which the loop operates.

statement

A statement to be executed on every iteration. May reference variable. You can use a block statement to execute multiple statements.

\n

Description

\n
\n

A for...of loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an iteration, and the loop is said to iterate over the iterable. Each iteration executes statements that may refer to the current sequence value.

When a for...of loop iterates over an iterable, it first calls the iterable's [@@iterator]() method, which returns an iterator, and then repeatedly calls the resulting iterator's next() method to produce the sequence of values to be assigned to variable.

A for...of loop exits when the iterator has completed (the iterator's next() method returns an object containing done: true). You may also use control flow statements to change the normal control flow. break exits the loop and goes to the first statement after the loop body, while continue skips the rest of the statements of the current iteration and proceeds to the next iteration.

If the for...of loop exited early (e.g. a break statement is encountered or an error is thrown), the return() method of the iterator is called to perform any cleanup.

The variable part of for...of accepts anything that can come before the = operator. You can use const to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use let.

\n

js

\n
const iterable = [10, 20, 30];\n\nfor (let value of iterable) {\n  value += 1;\n  console.log(value);\n}\n// 11\n// 21\n// 31\n
\n

Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).

You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y of iterable) to assign the value to an object property.

However, a special rule forbids using async as the variable name. This is invalid syntax:

\n

js

\n
let async;\nfor (async of [1, 2, 3]); // SyntaxError: The left-hand side of a for-of loop may not be 'async'.\n
\n

This is to avoid syntax ambiguity with the valid code for (async of => {};;), which is a for loop.

\n

Examples

\n

Iterating over an Array

\n
\n

js

\n
const iterable = [10, 20, 30];\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// 10\n// 20\n// 30\n
\n

Iterating over a string

\n
\n

Strings are iterated by Unicode code points.

\n

js

\n
const iterable = \"boo\";\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// \"b\"\n// \"o\"\n// \"o\"\n
\n
\n

Iterating over a TypedArray

\n
\n

js

\n
const iterable = new Uint8Array([0x00, 0xff]);\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// 0\n// 255\n
\n

Iterating over a Map

\n
\n

js

\n
const iterable = new Map([\n  [\"a\", 1],\n  [\"b\", 2],\n  [\"c\", 3],\n]);\n\nfor (const entry of iterable) {\n  console.log(entry);\n}\n// ['a', 1]\n// ['b', 2]\n// ['c', 3]\n\nfor (const [key, value] of iterable) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n

Iterating over a Set

\n
\n

js

\n
const iterable = new Set([1, 1, 2, 2, 3, 3]);\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n

Iterating over the arguments object

\n
\n

You can iterate over the arguments object to examine all parameters passed into a function.

\n

js

\n
function foo() {\n  for (const value of arguments) {\n    console.log(value);\n  }\n}\n\nfoo(1, 2, 3);\n// 1\n// 2\n// 3\n
\n
\n

Iterating over a NodeList

\n
\n

The following example adds a read class to paragraphs that are direct descendants of the <article> element by iterating over a NodeList DOM collection.

\n

js

\n
const articleParagraphs = document.querySelectorAll(\"article > p\");\nfor (const paragraph of articleParagraphs) {\n  paragraph.classList.add(\"read\");\n}\n
\n
\n

Iterating over a user-defined iterable

\n
\n

Iterating over an object with an @@iterator method that returns a custom iterator:

\n

js

\n
const iterable = {\n  [Symbol.iterator]() {\n    let i = 1;\n    return {\n      next() {\n        if (i <= 3) {\n          return { value: i++, done: false };\n        }\n        return { value: undefined, done: true };\n      },\n    };\n  },\n};\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n

Iterating over an object with an @@iterator generator method:

\n

js

\n
const iterable = {\n  *[Symbol.iterator]() {\n    yield 1;\n    yield 2;\n    yield 3;\n  },\n};\n\nfor (const value of iterable) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n

Iterable iterators (iterators with a [@@iterator]() method that returns this) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such as for...of.

\n

js

\n
let i = 1;\n\nconst iterator = {\n  next() {\n    if (i <= 3) {\n      return { value: i++, done: false };\n    }\n    return { value: undefined, done: true };\n  },\n  [Symbol.iterator]() {\n    return this;\n  },\n};\n\nfor (const value of iterator) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n
\n

Iterating over a generator

\n
\n

js

\n
function* source() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst generator = source();\n\nfor (const value of generator) {\n  console.log(value);\n}\n// 1\n// 2\n// 3\n
\n

Early exiting

\n
\n

Execution of the break statement in the first loop causes it to exit early. The iterator is not finished yet, so the second loop will continue from where the first one stopped at.

\n

js

\n
const source = [1, 2, 3];\n\nconst iterator = source[Symbol.iterator]();\n\nfor (const value of iterator) {\n  console.log(value);\n  if (value === 1) {\n    break;\n  }\n  console.log(\"This string will not be logged.\");\n}\n// 1\n\n// Another loop using the same iterator\n// picks up where the last loop left off.\nfor (const value of iterator) {\n  console.log(value);\n}\n// 2\n// 3\n\n// The iterator is used up.\n// This loop will execute no iterations.\nfor (const value of iterator) {\n  console.log(value);\n}\n// [No output]\n
\n

Generators implement the return() method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.

\n

js

\n
function* source() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst generator = source();\n\nfor (const value of generator) {\n  console.log(value);\n  if (value === 1) {\n    break;\n  }\n  console.log(\"This string will not be logged.\");\n}\n// 1\n\n// The generator is used up.\n// This loop will execute no iterations.\nfor (const value of generator) {\n  console.log(value);\n}\n// [No output]\n
\n
\n

Difference between for...of and for...in

\n
\n

Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over.

The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.

The following example shows the difference between a for...of loop and a for...in loop when used with an Array.

\n

js

\n
Object.prototype.objCustom = function () {};\nArray.prototype.arrCustom = function () {};\n\nconst iterable = [3, 5, 7];\niterable.foo = \"hello\";\n\nfor (const i in iterable) {\n  console.log(i);\n}\n// \"0\", \"1\", \"2\", \"foo\", \"arrCustom\", \"objCustom\"\n\nfor (const i in iterable) {\n  if (Object.hasOwn(iterable, i)) {\n    console.log(i);\n  }\n}\n// \"0\" \"1\" \"2\" \"foo\"\n\nfor (const i of iterable) {\n  console.log(i);\n}\n// 3 5 7\n
\n

The object iterable inherits the properties objCustom and arrCustom because it contains both Object.prototype and Array.prototype in its prototype chain.

The for...in loop logs only enumerable properties of the iterable object. It doesn't log array elements 3, 5, 7 or \"hello\" because those are not properties — they are values. It logs array indexes as well as arrCustom and objCustom, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of how array iteration and for...in work.

The second loop is similar to the first one, but it uses Object.hasOwn() to check if the found enumerable property is the object's own, i.e. not inherited. If it is, the property is logged. Properties 0, 1, 2 and foo are logged because they are own properties. Properties arrCustom and objCustom are not logged because they are inherited.

The for...of loop iterates and logs values that iterable, as an array (which is iterable), defines to be iterated over. The object's elements 3, 5, 7 are shown, but none of the object's properties are.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-for-in-and-for-of-statements
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
for...of3812
13Before Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError (\"missing = in const declaration\").
No2573838
14Before Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError (\"missing = in const declaration\").
2573.01.00.12.0
async_iterators631257No5076363574678.01.010.0.0
closing_iterators511453No3875151534175.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\n

\n
\n", + "statements/async_function": "

async function

\n

The async function declaration creates a binding of a new async function to a given name. The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.

You can also define async functions using the async function expression.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
async function name(param0) {\n  statements\n}\nasync function name(param0, param1) {\n  statements\n}\nasync function name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: There cannot be a line terminator between async and function, otherwise a semicolon is automatically inserted, causing async to become an identifier and the rest to become a function declaration.

\n

Parameters

\n
name

The function's name.

\nparam Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements comprising the body of the function. The await mechanism may be used.

Description

\n
\n

An async function declaration creates an AsyncFunction object. Each time when an async function is called, it returns a new Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.

Async functions can contain zero or more await expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of async and await enables the use of ordinary try / catch blocks around asynchronous code.

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError.

await can be used on its own with JavaScript modules.

Note: The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async/await is similar to combining generators and promises.

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

For example, consider the following code:

\n

js

\n
async function foo() {\n  return 1;\n}\n
\n

It is similar to:

\n

js

\n
function foo() {\n  return Promise.resolve(1);\n}\n
\n

Note:

Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve, they are not equivalent.

An async function will return a different reference, whereas Promise.resolve returns the same reference if the given value is a promise.

It can be a problem when you want to check the equality of a promise and a return value of an async function.

\n

js

\n
const p = new Promise((res, rej) => {\n  res(1);\n});\n\nasync function asyncReturn() {\n  return p;\n}\n\nfunction basicReturn() {\n  return Promise.resolve(p);\n}\n\nconsole.log(p === basicReturn()); // true\nconsole.log(p === asyncReturn()); // false\n
\n

The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

For example:

\n

js

\n
async function foo() {\n  await 1;\n}\n
\n

It is also equivalent to:

\n

js

\n
function foo() {\n  return Promise.resolve(1).then(() => undefined);\n}\n
\n

Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain.

In the following example, we successively await two promises. Progress moves through function foo in three stages.

  1. The first line of the body of function foo is executed synchronously, with the await expression configured with the pending promise. Progress through foo is then suspended and control is yielded back to the function that called foo.
  2. Some time later, when the first promise has either been fulfilled or rejected, control moves back into foo. The result of the first promise fulfillment (if it was not rejected) is returned from the await expression. Here 1 is assigned to result1. Progress continues, and the second await expression is evaluated. Again, progress through foo is suspended and control is yielded.
  3. Some time later, when the second promise has either been fulfilled or rejected, control re-enters foo. The result of the second promise resolution is returned from the second await expression. Here 2 is assigned to result2. Control moves to the return expression (if any). The default return value of undefined is returned as the resolution value of the current promise.
\n

js

\n
async function foo() {\n  const result1 = await new Promise((resolve) =>\n    setTimeout(() => resolve(\"1\")),\n  );\n  const result2 = await new Promise((resolve) =>\n    setTimeout(() => resolve(\"2\")),\n  );\n}\nfoo();\n
\n

Note how the promise chain is not built-up in one go. Instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. As a result, we must be mindful of error handling behavior when dealing with concurrent asynchronous operations.

For example, in the following code an unhandled promise rejection error will be thrown, even if a .catch handler has been configured further along the promise chain. This is because p2 will not be \"wired into\" the promise chain until control returns from p1.

\n

js

\n
async function foo() {\n  const p1 = new Promise((resolve) => setTimeout(() => resolve(\"1\"), 1000));\n  const p2 = new Promise((_, reject) => setTimeout(() => reject(\"2\"), 500));\n  const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead.\n}\nfoo().catch(() => {}); // Attempt to swallow all errors...\n
\n

async function declarations behave similar to function declarations — they are hoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

\n

Examples

\n

Async functions and execution order

\n
\n
\n

js

\n
function resolveAfter2Seconds() {\n  console.log(\"starting slow promise\");\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve(\"slow\");\n      console.log(\"slow promise is done\");\n    }, 2000);\n  });\n}\n\nfunction resolveAfter1Second() {\n  console.log(\"starting fast promise\");\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve(\"fast\");\n      console.log(\"fast promise is done\");\n    }, 1000);\n  });\n}\n\nasync function sequentialStart() {\n  console.log(\"== sequentialStart starts ==\");\n\n  // 1. Start a timer, log after it's done\n  const slow = resolveAfter2Seconds();\n  console.log(await slow);\n\n  // 2. Start the next timer after waiting for the previous one\n  const fast = resolveAfter1Second();\n  console.log(await fast);\n\n  console.log(\"== sequentialStart done ==\");\n}\n\nasync function sequentialWait() {\n  console.log(\"== sequentialWait starts ==\");\n\n  // 1. Start two timers without waiting for each other\n  const slow = resolveAfter2Seconds();\n  const fast = resolveAfter1Second();\n\n  // 2. Wait for the slow timer to complete, and then log the result\n  console.log(await slow);\n  // 3. Wait for the fast timer to complete, and then log the result\n  console.log(await fast);\n\n  console.log(\"== sequentialWait done ==\");\n}\n\nasync function concurrent1() {\n  console.log(\"== concurrent1 starts ==\");\n\n  // 1. Start two timers concurrently and wait for both to complete\n  const results = await Promise.all([\n    resolveAfter2Seconds(),\n    resolveAfter1Second(),\n  ]);\n  // 2. Log the results together\n  console.log(results[0]);\n  console.log(results[1]);\n\n  console.log(\"== concurrent1 done ==\");\n}\n\nasync function concurrent2() {\n  console.log(\"== concurrent2 starts ==\");\n\n  // 1. Start two timers concurrently, log immediately after each one is done\n  await Promise.all([\n    (async () => console.log(await resolveAfter2Seconds()))(),\n    (async () => console.log(await resolveAfter1Second()))(),\n  ]);\n  console.log(\"== concurrent2 done ==\");\n}\n\nsequentialStart(); // after 2 seconds, logs \"slow\", then after 1 more second, \"fast\"\n\n// wait above to finish\nsetTimeout(sequentialWait, 4000); // after 2 seconds, logs \"slow\" and then \"fast\"\n\n// wait again\nsetTimeout(concurrent1, 7000); // same as sequentialWait\n\n// wait again\nsetTimeout(concurrent2, 10000); // after 1 second, logs \"fast\", then after 1 more second, \"slow\"\n
\n

await and concurrency

In sequentialStart, execution suspends 2 seconds for the first await, and then another second for the second await. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.

In sequentialWait, both timers are created and then awaited. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer. However, the await calls still run in series, which means the second await will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.

If you wish to safely perform other jobs after two or more jobs run concurrently and are complete, you must await a call to Promise.all() or Promise.allSettled() before that job.

Warning: The functions sequentialWait and concurrent1 are not functionally equivalent.

In sequentialWait, if promise fast rejects before promise slow is fulfilled, then an unhandled promise rejection error will be raised, regardless of whether the caller has configured a catch clause.

In concurrent1, Promise.all wires up the promise chain in one go, meaning that the operation will fail-fast regardless of the order of rejection of the promises, and the error will always occur within the configured promise chain, enabling it to be caught in the normal way.

\n

Rewriting a Promise chain with an async function

\n
\n

An API that returns a Promise will result in a promise chain, and it splits the function into many parts. Consider the following code:

\n

js

\n
function getProcessedData(url) {\n  return downloadData(url) // returns a promise\n    .catch((e) => downloadFallbackData(url)) // returns a promise\n    .then((v) => processDataInWorker(v)); // returns a promise\n}\n
\n

it can be rewritten with a single async function as follows:

\n

js

\n
async function getProcessedData(url) {\n  let v;\n  try {\n    v = await downloadData(url);\n  } catch (e) {\n    v = await downloadFallbackData(url);\n  }\n  return processDataInWorker(v);\n}\n
\n

Alternatively, you can chain the promise with catch():

\n

js

\n
async function getProcessedData(url) {\n  const v = await downloadData(url).catch((e) => downloadFallbackData(url));\n  return processDataInWorker(v);\n}\n
\n

In the two rewritten versions, notice there is no await statement after the return keyword, although that would be valid too: The return value of an async function is implicitly wrapped in Promise.resolve - if it's not already a promise itself (as in the examples).

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
async_function551552No4210.15555524210.36.01.07.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\n

\n
\n", + "statements/while": "

while

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
while (condition)\n  statement\n
\n
condition

An expression evaluated before each pass through the loop. If this condition evaluates to true, statement is executed. When condition evaluates to false, execution continues with the statement after the while loop.

statement

An optional statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ /* ... */ }) to group those statements.

Note: Use the break statement to stop a loop before condition evaluates to true.

\n

Examples

\n

Using while

\n
\n

The following while loop iterates as long as n is less than three.

\n

js

\n
let n = 0;\nlet x = 0;\n\nwhile (n < 3) {\n  n++;\n  x += n;\n}\n
\n

Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

\n

Using an assignment as a condition

\n
\n

In some cases, it can make sense to use an assignment as a condition. This comes with readability tradeoffs, so there are certain stylistic recommendations that would make the pattern more obvious for everyone.

Consider the following example, which iterates over a document's comments, logging them to the console.

\n

js

\n
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);\nlet currentNode;\nwhile (currentNode = iterator.nextNode()) {\n  console.log(currentNode.textContent.trim());\n}\n
\n

That's not completely a good-practice example, due to the following line specifically:

\n

js

\n
while (currentNode = iterator.nextNode()) {\n
\n

The effect of that line is fine — in that, each time a comment node is found:

  1. \niterator.nextNode() returns that comment node, which gets assigned to currentNode.
  2. The value of currentNode = iterator.nextNode() is therefore truthy.
  3. So the console.log() call executes and the loop continues.

…and then, when there are no more comment nodes in the document:

  1. \niterator.nextNode() returns null.
  2. The value of currentNode = iterator.nextNode() is therefore also null, which is falsy.
  3. So the loop ends.

The problem with this line is: conditions typically use comparison operators such as ===, but the = in that line isn't a comparison operator — instead, it's an assignment operator. So that = looks like it's a typo for === — even though it's not actually a typo.

Therefore, in cases like that one, some code-linting tools such as ESLint's no-cond-assign rule — in order to help you catch a possible typo so that you can fix it — will report a warning such as the following:

Expected a conditional expression and instead saw an assignment.

Many style guides recommend more explicitly indicating the intention for the condition to be an assignment. You can do that minimally by putting additional parentheses as a grouping operator around the assignment:

\n

js

\n
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);\nlet currentNode;\nwhile ((currentNode = iterator.nextNode())) {\n  console.log(currentNode.textContent.trim());\n}\n
\n

In fact, this is the style enforced by ESLint's no-cond-assign's default configuration, as well as Prettier, so you'll likely see this pattern a lot in the wild.

Some people may further recommend adding a comparison operator to turn the condition into an explicit comparison:

\n

js

\n
while ((currentNode = iterator.nextNode()) !== null) {\n
\n

There are other ways to write this pattern, such as:

\n

js

\n
while ((currentNode = iterator.nextNode()) && currentNode) {\n
\n

Or, forgoing the idea of using a while loop altogether:

\n

js

\n
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);\nfor (\n  let currentNode = iterator.nextNode();\n  currentNode;\n  currentNode = iterator.nextNode()\n) {\n  console.log(currentNode.textContent.trim());\n}\n
\n

If the reader is sufficiently familiar with the assignment as condition pattern, all these variations should have equivalent readability. Otherwise, the last form is probably the most readable, albeit the most verbose.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-while-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
while11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while\n

\n
\n", + "statements/block": "

Block statement

A block statement is used to group zero or more statements. The block is delimited by a pair of braces (\"curly braces\") and contains a list of zero or more statements and declarations.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
{\n  StatementList\n}\n
\n
StatementList

Statements and declarations grouped within the block statement.

\n

Description

\n
\n

The block statement is often called the compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript, especially when used in association with control flow statements like if...else and for. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

In addition, combined with block-scoped declarations like let, const, and class, blocks can prevent temporary variables from polluting the global namespace, just like IIFEs do.

\n

Block scoping rules with var or function declaration in non-strict mode

\n
\n

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:

\n

js

\n
var x = 1;\n{\n  var x = 2;\n}\nconsole.log(x); // 2\n
\n

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

\n

Block scoping rules with let, const, class, or function declaration in strict mode

\n
\n

By contrast, identifiers declared with let, const, and class do have block scope:

\n

js

\n
let x = 1;\n{\n  let x = 2;\n}\nconsole.log(x); // 1\n
\n

The x = 2 is limited in scope to the block in which it was defined.

The same is true of const:

\n

js

\n
const c = 1;\n{\n  const c = 2;\n}\nconsole.log(c); // 1; does not throw SyntaxError\n
\n

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

In strict mode, function declarations inside blocks are scoped to that block and are hoisted.

\n

js

\n
\"use strict\";\n\n{\n  foo(); // Logs \"foo\"\n  function foo() {\n    console.log(\"foo\");\n  }\n}\n\nfoo(); // ReferenceError: foo is not defined\n
\n
\n

Examples

\n

Using a block statement as the body of a for loop

\n
\n

A for loop accepts a single statement as its body.

\n

js

\n
for (let i = 0; i < 10; i++) console.log(i);\n
\n

If you want to use more than one statement in the loop body, you can group them into one block statement:

\n

js

\n
for (let i = 0; i < 10; i++) {\n  console.log(i);\n  console.log(i ** 2);\n}\n
\n
\n

Using a block statement to encapsulate data

\n
\n

let and const declarations are scoped to the containing block. This allows you to hide data from the global scope without wrapping it in a function.

\n

js

\n
let sector;\n{\n  // These variables are scoped to this block and are not\n  // accessible after the block\n  const angle = Math.PI / 3;\n  const radius = 10;\n  sector = {\n    radius,\n    angle,\n    area: (angle / 2) * radius ** 2,\n    perimeter: 2 * radius + angle * radius,\n  };\n}\nconsole.log(sector);\n// {\n//   radius: 10,\n//   angle: 1.0471975511965976,\n//   area: 52.35987755982988,\n//   perimeter: 30.471975511965976\n// }\nconsole.log(typeof radius); // \"undefined\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-block
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
block112111314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block\n

\n
\n", + "statements/expression_statement": "

Expression statement

An expression statement is an expression used in a place where a statement is expected. The expression is evaluated and its result is discarded — therefore, it makes sense only for expressions that have side effects, such as executing a function or updating a variable.

\n

Syntax

\n
\n
\n

js

\n
expression;\n
\n
expression

An arbitrary expression to be evaluated. There are certain expressions that may be ambiguous with other statements and are thus forbidden.

\n

Description

\n
\n

Apart from the dedicated statement syntaxes, you can also use almost any expression as a statement on its own. The expression statement syntax requires a semicolon at the end, but the automatic semicolon insertion process may insert one for you if the lack of a semicolon results in invalid syntax.

Because the expression is evaluated and then discarded, the result of the expression is not available. Therefore, the expression must have some side effect for it to be useful. Expression statements are commonly:

Others may also have side effects if they invoke getters or trigger type coercions.

\n

Forbidden expressions

\n
\n

In order for an expression to be used as a statement, it must not be ambiguous with other statement syntaxes. Therefore, the expression must not start with any of the following tokens:

Therefore, all of the following are invalid:

\n

js

\n
function foo() {\n  console.log(\"foo\");\n}(); // SyntaxError: Unexpected token '('\n\n// For some reason, you have a variable called `let`\nvar let = [1, 2, 3];\nlet[0] = 4; // SyntaxError: Invalid destructuring assignment target\n\n{\n  foo: 1,\n  bar: 2, // SyntaxError: Unexpected token ':'\n};\n
\n

More dangerously, sometimes the code happens to be valid syntax, but is not what you intend.

\n

js

\n
// For some reason, you have a variable called `let`\nvar let = [1, 2, 3];\n\nfunction setIndex(index, value) {\n  if (index >= 0) {\n    // Intend to assign to the array `let`, but instead creates an extra variable!\n    let[index] = value;\n  }\n}\n\nsetIndex(0, [1, 2]);\nconsole.log(let); // [1, 2, 3]\n\n// This is not an object literal, but a block statement,\n// where `foo` is a label and `1` is an expression statement.\n// This often happens in the console\n{ foo: 1 };\n
\n

To avoid these problems, you can use parentheses, so that the statement is unambiguously an expression statement.

\n

js

\n
(function foo() {\n  console.log(\"foo\");\n})();\n
\n
\n

Examples

\n

Avoiding control flow statements

\n
\n

You can avoid almost all use of control flow statements using expression statements. For example, if...else can be replaced with ternary operators and logical operators. Iterative statements like for or for...of can be replaced with array methods.

\n

js

\n
// Using control flow statements\nfunction range(start, end) {\n  if (start > end) {\n    [start, end] = [end, start];\n  }\n  const result = [];\n  for (let i = start; i < end; i++) {\n    result.push(i);\n  }\n  return result;\n}\n\n// Using expression statements\nfunction range2(start, end) {\n  start > end && ([start, end] = [end, start]);\n  return Array.from({ length: end - start }, (_, i) => start + i);\n}\n
\n

Warning: This only demonstrates a capability of the language. Excessive use of expression statements as a substitute for control-flow statements can make code much less readable.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-expression-statement
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement\n

\n
\n", + "statements/debugger": "

debugger

The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect.

\n

Syntax

\n
\n

js

\n
debugger;\n
\n

Examples

\n

Using the debugger statement

\n
\n

The following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is called.

\n

js

\n
function potentiallyBuggyCode() {\n  debugger;\n  // do potentially buggy stuff to examine, step through, etc.\n}\n
\n

When the debugger is invoked, execution is paused at the debugger statement. It is like a breakpoint in the script source.

\"A

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-debugger-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
debugger512141054.418410.14.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger\n

\n
\n", + "statements/export": "

export

\n

The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import. The value of an imported binding is subject to change in the module that exports it — when a module updates the value of a binding that it exports, the update will be visible in its imported value.

In order to use the export declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding type=\"module\" to the <script> tag, or by being imported by another module. Modules are automatically interpreted in strict mode.

\n
\n

Syntax

\n
\n
\n

js

\n
// Exporting declarations\nexport let name1, name2/*, … */; // also var\nexport const name1 = 1, name2 = 2/*, … */; // also var, let\nexport function functionName() { /* … */ }\nexport class ClassName { /* … */ }\nexport function* generatorFunctionName() { /* … */ }\nexport const { name1, name2: bar } = o;\nexport const [ name1, name2 ] = array;\n\n// Export list\nexport { name1, /* …, */ nameN };\nexport { variable1 as name1, variable2 as name2, /* …, */ nameN };\nexport { variable1 as \"string name\" };\nexport { name1 as default /*, … */ };\n\n// Default exports\nexport default expression;\nexport default function functionName() { /* … */ }\nexport default class ClassName { /* … */ }\nexport default function* generatorFunctionName() { /* … */ }\nexport default function () { /* … */ }\nexport default class { /* … */ }\nexport default function* () { /* … */ }\n\n// Aggregating modules\nexport * from \"module-name\";\nexport * as name1 from \"module-name\";\nexport { name1, /* …, */ nameN } from \"module-name\";\nexport { import1 as name1, import2 as name2, /* …, */ nameN } from \"module-name\";\nexport { default, /* …, */ } from \"module-name\";\nexport { default as name1 } from \"module-name\";\n
\n
nameN

Identifier to be exported (so that it can be imported via import in another script). If you use an alias with as, the actual exported name can be specified as a string literal, which may not be a valid identifier.

\n

Description

\n
\n

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.

Named exports:

\n

js

\n
// export features declared elsewhere\nexport { myFunction2, myVariable2 };\n\n// export individual features (can export var, let,\n// const, function, class)\nexport let myVariable = Math.sqrt(2);\nexport function myFunction() {\n  // …\n}\n
\n

After the export keyword, you can use let, const, and var declarations, as well as function or class declarations. You can also use the export { name1, name2 } syntax to export a list of names declared elsewhere. Note that export {} does not export an empty object — it's a no-op declaration that exports nothing (an empty name list).

Export declarations are not subject to temporal dead zone rules. You can declare that the module exports X before the name X itself is declared.

\n

js

\n
export { x };\nconst x = 1;\n// This works, because `export` is only a declaration, but doesn't\n// utilize the value of `x`.\n
\n

Default exports:

\n

js

\n
// export feature declared elsewhere as default\nexport { myFunction as default };\n// This is equivalent to:\nexport default myFunction;\n\n// export individual features as default\nexport default function () { /* … */ }\nexport default class { /* … */ }\n
\n

Note: Names for export declarations must be distinct from each other. Having exports with duplicate names or using more than one default export will result in a SyntaxError and prevent the module from being evaluated.

The export default syntax allows any expression.

\n

js

\n
export default 1 + 1;\n
\n

As a special case, functions and classes are exported as declarations, not expressions, and these declarations can be anonymous. This means functions will be hoisted.

\n

js

\n
// Works because `foo` is a function declaration,\n// not a function expression\nfoo();\n\nexport default function foo() {\n  console.log(\"Hi\");\n}\n\n// It's still technically a declaration, but it's allowed\n// to be anonymous\nexport default function () {\n  console.log(\"Hi\");\n}\n
\n

Named exports are useful when you need to export several values. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with as), but the default export can be imported with any name. For example:

\n

js

\n
// file test.js\nconst k = 12;\nexport default k;\n
\n
\n

js

\n
// some other file\nimport m from \"./test\"; // note that we have the freedom to use import m instead of import k, because k was default export\nconsole.log(m); // 12\n
\n

You can also rename named exports to avoid naming conflicts:

\n

js

\n
export { myFunction as function1, myVariable as variable };\n
\n

You can rename a name to something that's not a valid identifier by using a string literal. For example:

\n

js

\n
export { myFunction as \"my-function\" };\n
\n
\n

Re-exporting / Aggregating

\n
\n

A module can also \"relay\" values exported from other modules without the hassle of writing two separate import/export statements. This is often useful when creating a single module concentrating various exports from various modules (usually called a \"barrel module\").

This can be achieved with the \"export from\" syntax:

\n

js

\n
export { default as function1, function2 } from \"bar.js\";\n
\n

Which is comparable to a combination of import and export, except that function1 and function2 do not become available inside the current module:

\n

js

\n
import { default as function1, function2 } from \"bar.js\";\nexport { function1, function2 };\n
\n

Most of the \"import from\" syntaxes have \"export from\" counterparts.

\n

js

\n
export { x } from \"mod\";\nexport { x as v } from \"mod\";\nexport * as ns from \"mod\";\n
\n

There is also export * from \"mod\", although there's no import * from \"mod\". This re-exports all named exports from mod as the named exports of the current module, but the default export of mod is not re-exported. If there are two wildcard exports statements that implicitly re-export the same name, neither one is re-exported.

\n

js

\n
// -- mod1.js --\nexport const a = 1;\n\n// -- mod2.js --\nexport const a = 3;\n\n// -- barrel.js --\nexport * from \"./mod1.js\";\nexport * from \"./mod2.js\";\n\n// -- main.js --\nimport * as ns from \"./barrel.js\";\nconsole.log(ns.a); // undefined\n
\n

Attempting to import the duplicate name directly will throw an error.

\n

js

\n
import { a } from \"./barrel.js\";\n// SyntaxError: The requested module './barrel.js' contains conflicting star exports for name 'a'\n
\n

The following is syntactically invalid despite its import equivalent:

\n

js

\n
export DefaultExport from \"bar.js\"; // Invalid\n
\n

The correct way of doing this is to rename the export:

\n

js

\n
export { default as DefaultExport } from \"bar.js\";\n
\n

The \"export from\" syntax allows the as token to be omitted, which makes the default export still re-exported as default export.

\n

js

\n
export { default, function2 } from \"bar.js\";\n
\n
\n

Examples

\n

Using named exports

\n
\n

In a module my-module.js, we could include the following code:

\n

js

\n
// module \"my-module.js\"\nfunction cube(x) {\n  return x * x * x;\n}\n\nconst foo = Math.PI + Math.SQRT2;\n\nconst graph = {\n  options: {\n    color: \"white\",\n    thickness: \"2px\",\n  },\n  draw() {\n    console.log(\"From graph draw function\");\n  },\n};\n\nexport { cube, foo, graph };\n
\n

Then in the top-level module included in your HTML page, we could have:

\n

js

\n
import { cube, foo, graph } from \"./my-module.js\";\n\ngraph.options = {\n  color: \"blue\",\n  thickness: \"3px\",\n};\n\ngraph.draw();\nconsole.log(cube(3)); // 27\nconsole.log(foo); // 4.555806215962888\n
\n

It is important to note the following:

\n

Using the default export

\n
\n

If we want to export a single value or to have a fallback value for your module, you could use a default export:

\n

js

\n
// module \"my-module.js\"\n\nexport default function cube(x) {\n  return x * x * x;\n}\n
\n

Then, in another script, it is straightforward to import the default export:

\n

js

\n
import cube from \"./my-module.js\";\nconsole.log(cube(3)); // 27\n
\n
\n

Using export from

\n
\n

Let's take an example where we have the following hierarchy:

This is what it would look like using code snippets:

\n

js

\n
// In childModule1.js\nfunction myFunction() {\n  console.log(\"Hello!\");\n}\nconst myVariable = 1;\nexport { myFunction, myVariable };\n
\n
\n

js

\n
// In childModule2.js\nclass MyClass {\n  constructor(x) {\n    this.x = x;\n  }\n}\n\nexport { MyClass };\n
\n
\n

js

\n
// In parentModule.js\n// Only aggregating the exports from childModule1 and childModule2\n// to re-export them\nexport { myFunction, myVariable } from \"childModule1.js\";\nexport { MyClass } from \"childModule2.js\";\n
\n
\n

js

\n
// In top-level module\n// We can consume the exports from a single module since parentModule\n// \"collected\"/\"bundled\" them in a single source\nimport { myFunction, myVariable, MyClass } from \"parentModule.js\";\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-exports
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
export611660No4810.16161604510.38.01.0
13.2.0Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain \"type\": \"module\". See Node's ECMAScript Modules documentation for more details.
default611660No4810.1No61604510.38.01.0
13.2.0Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain \"type\": \"module\". See Node's ECMAScript Modules documentation for more details.
namespace727980No6014.1No72805114.511.01.0
13.2.0Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain \"type\": \"module\". See Node's ECMAScript Modules documentation for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export\n

\n
\n", + "statements/import": "

import

\n

The static import declaration is used to import read-only live bindings which are exported by another module. The imported bindings are called live bindings because they are updated by the module that exported the binding, but cannot be re-assigned by the importing module.

In order to use the import declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding type=\"module\" to the <script> tag. Modules are automatically interpreted in strict mode.

There is also a function-like dynamic import(), which does not require scripts of type=\"module\".

\n
\n

Syntax

\n
\n
\n

js

\n
import defaultExport from \"module-name\";\nimport * as name from \"module-name\";\nimport { export1 } from \"module-name\";\nimport { export1 as alias1 } from \"module-name\";\nimport { default as alias } from \"module-name\";\nimport { export1, export2 } from \"module-name\";\nimport { export1, export2 as alias2, /* … */ } from \"module-name\";\nimport { \"string name\" as alias } from \"module-name\";\nimport defaultExport, { export1, /* … */ } from \"module-name\";\nimport defaultExport, * as name from \"module-name\";\nimport \"module-name\";\n
\n
defaultExport

Name that will refer to the default export from the module. Must be a valid JavaScript identifier.

module-name

The module to import from. The evaluation of the specifier is host-specified. This is often a relative or absolute URL to the .js file containing the module. In Node, extension-less imports often refer to packages in node_modules. Certain bundlers may permit importing files without extensions; check your environment. Only single quoted and double quoted Strings are allowed.

name

Name of the module object that will be used as a kind of namespace when referring to the imports. Must be a valid JavaScript identifier.

exportN

Name of the exports to be imported. The name can be either an identifier or a string literal, depending on what module-name declares to export. If it is a string literal, it must be aliased to a valid identifier.

aliasN

Names that will refer to the named imports. Must be a valid JavaScript identifier.

\n

Description

\n
\n

import declarations can only be present in modules, and only at the top-level (i.e. not inside blocks, functions, etc.). If an import declaration is encountered in non-module contexts (for example, <script> tags without type=\"module\", eval, new Function, which all have \"script\" or \"function body\" as parsing goals), a SyntaxError is thrown. To load modules in non-module contexts, use the dynamic import syntax instead.

All imported bindings cannot be in the same scope as any other declaration, including let, const, class, function, var, and import declaration.

import declarations are designed to be syntactically rigid (for example, only string literal specifiers, only permitted at the top-level, all bindings must be identifiers), which allows modules to be statically analyzed and linked before getting evaluated. This is the key to making modules asynchronous by nature, powering features like top-level await.

\n

Forms of import declarations

\n
\n

There are four forms of import declarations:

Below are examples to clarify the syntax.

Named import

Given a value named myExport which has been exported from the module my-module either implicitly as export * from \"another.js\" or explicitly using the export statement, this inserts myExport into the current scope.

\n

js

\n
import { myExport } from \"/modules/my-module.js\";\n
\n

You can import multiple names from the same module.

\n

js

\n
import { foo, bar } from \"/modules/my-module.js\";\n
\n

You can rename an export when importing it. For example, this inserts shortName into the current scope.

\n

js

\n
import { reallyReallyLongModuleExportName as shortName } from \"/modules/my-module.js\";\n
\n

A module may also export a member as a string literal which is not a valid identifier, in which case you must alias it in order to use it in the current module.

\n

js

\n
// /modules/my-module.js\nconst a = 1;\nexport { a as \"a-b\" };\n
\n
\n

js

\n
import { \"a-b\" as a } from \"/modules/my-module.js\";\n
\n

Note: import { x, y } from \"mod\" is not equivalent to import defaultExport from \"mod\" and then destructuring x and y from defaultExport. Named and default imports are distinct syntaxes in JavaScript modules.

Default import

Default exports need to be imported with the corresponding default import syntax. The simplest version directly imports the default:

\n

js

\n
import myDefault from \"/modules/my-module.js\";\n
\n

Since the default export doesn't explicitly specify a name, you can give the identifier any name you like.

It is also possible to specify a default import with namespace imports or named imports. In such cases, the default import will have to be declared first. For instance:

\n

js

\n
import myDefault, * as myModule from \"/modules/my-module.js\";\n// myModule.default and myDefault point to the same binding\n
\n

or

\n

js

\n
import myDefault, { foo, bar } from \"/modules/my-module.js\";\n
\n

Importing a name called default has the same effect as a default import. It is necessary to alias the name because default is a reserved word.

\n

js

\n
import { default as myDefault } from \"/modules/my-module.js\";\n
\n

Namespace import

The following code inserts myModule into the current scope, containing all the exports from the module located at /modules/my-module.js.

\n

js

\n
import * as myModule from \"/modules/my-module.js\";\n
\n

Here, myModule represents a namespace object which contains all exports as properties. For example, if the module imported above includes an export doAllTheAmazingThings(), you would call it like this:

\n

js

\n
myModule.doAllTheAmazingThings();\n
\n

myModule is a sealed object with null prototype. The default export available as a key called default. For more information, see module namespace object.

Note: JavaScript does not have wildcard imports like import * from \"module-name\", because of the high possibility of name conflicts.

Import a module for its side effects only

Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.

\n

js

\n
import \"/modules/my-module.js\";\n
\n

This is often used for polyfills, which mutate the global variables.

\n

Hoisting

\n
\n

Import declarations are hoisted. In this case, that means that the identifiers the imports introduce are available in the entire module scope, and their side effects are produced before the rest of the module's code runs.

\n

js

\n
myModule.doAllTheAmazingThings(); // myModule.doAllTheAmazingThings is imported by the next line\n\nimport * as myModule from \"/modules/my-module.js\";\n
\n
\n

Examples

\n

Standard Import

\n
\n

In this example, we create a re-usable module that exports a function to get all primes within a given range.

\n

js

\n
// getPrimes.js\n/**\n * Returns a list of prime numbers that are smaller than `max`.\n */\nexport function getPrimes(max) {\n  const isPrime = Array.from({ length: max }, () => true);\n  isPrime[0] = isPrime[1] = false;\n  isPrime[2] = true;\n  for (let i = 2; i * i < max; i++) {\n    if (isPrime[i]) {\n      for (let j = i ** 2; j < max; j += i) {\n        isPrime[j] = false;\n      }\n    }\n  }\n  return [...isPrime.entries()]\n    .filter(([, isPrime]) => isPrime)\n    .map(([number]) => number);\n}\n
\n
\n

js

\n
import { getPrimes } from \"/modules/getPrimes.js\";\n\nconsole.log(getPrimes(10)); // [2, 3, 5, 7]\n
\n
\n

Imported values can only be modified by the exporter

\n
\n

The identifier being imported is a live binding, because the module exporting it may re-assign it and the imported value would change. However, the module importing it cannot re-assign it. Still, any module holding an exported object can mutate the object, and the mutated value can be observed by all other modules importing the same value.

You can also observe the new value through the module namespace object.

\n

js

\n
// my-module.js\nexport let myValue = 1;\nsetTimeout(() => {\n  myValue = 2;\n}, 500);\n
\n
\n

js

\n
// main.js\nimport { myValue } from \"/modules/my-module.js\";\nimport * as myModule from \"/modules/my-module.js\";\n\nconsole.log(myValue); // 1\nconsole.log(myModule.myValue); // 1\nsetTimeout(() => {\n  console.log(myValue); // 2; my-module has updated its value\n  console.log(myModule.myValue); // 2\n  myValue = 3; // TypeError: Assignment to constant variable.\n  // The importing module can only read the value but can't re-assign it.\n}, 1000);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-imports
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
import611660No4810.16161604510.38.01.0
13.2.0Modules must either have a filename ending in .mjs, or the nearest parent package.json file must contain \"type\": \"module\". See Node's ECMAScript Modules documentation for more details.
import_assertions9191NoNoNo159191NoNo1516.01.1716.14.0
service_worker_support9191114No77159191114641516.0NoNo
worker_support8080114No67158080114571513.01.0No
worklet_supportNoNo114NoNoNoNoNo114NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import\n

\n
\n", + "statements/label": "

Labeled statement

A labeled statement is any statement that is prefixed with an identifier. You can jump to this label using a break or continue statement nested within the labeled statement.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
label:\n  statement\n
\n
label

Any JavaScript identifier that is not a reserved word.

statement

A JavaScript statement. break can be used within any labeled statement, and continue can be used within labeled looping statements.

\n

Description

\n
\n

You can use a label to identify a statement, and later refer to it using a break or continue statement. Note that JavaScript has no goto statement; you can only use labels with break or continue.

Any break or continue that references label must be contained within the statement that's labeled by label. Think about label as a variable that's only available in the scope of statement.

If a break label; statement is encountered when executing statement, execution of statement terminates, and execution continues at the statement immediately following the labeled statement.

continue label; can only be used if statement is one of the looping statements. If a continue label; statement is encountered when executing statement, execution of statement continues at the next iteration of the loop. continue; without a label can only continue the innermost loop, while continue label; allows continuing any given loop even when the statement is nested within other loops.

A statement can have multiple labels. In this case, the labels are all functionally equivalent.

\n

Examples

\n

Using a labeled continue with for loops

\n
\n
\n

js

\n
// The first for statement is labeled \"loop1\"\nloop1: for (let i = 0; i < 3; i++) {\n  // The second for statement is labeled \"loop2\"\n  loop2: for (let j = 0; j < 3; j++) {\n    if (i === 1 && j === 1) {\n      continue loop1;\n    }\n    console.log(`i = ${i}, j = ${j}`);\n  }\n}\n\n// Logs:\n// i = 0, j = 0\n// i = 0, j = 1\n// i = 0, j = 2\n// i = 1, j = 0\n// i = 2, j = 0\n// i = 2, j = 1\n// i = 2, j = 2\n
\n

Notice how it skips both \"i = 1, j = 1\" and \"i = 1, j = 2\".

\n

Using a labeled break with for loops

\n
\n
\n

js

\n
let i, j;\n\n// The first for statement is labeled \"loop1\"\nloop1: for (i = 0; i < 3; i++) {\n  // The second for statement is labeled \"loop2\"\n  loop2: for (j = 0; j < 3; j++) {\n    if (i === 1 && j === 1) {\n      break loop1;\n    }\n    console.log(`i = ${i}, j = ${j}`);\n  }\n}\n\n// Logs:\n// i = 0, j = 0\n// i = 0, j = 1\n// i = 0, j = 2\n// i = 1, j = 0\n
\n

Notice the difference with the previous continue example: when break loop1 is encountered, the execution of the outer loop is terminated, so there are no further logs beyond \"i = 1, j = 0\"; when continue loop1 is encountered, the execution of the outer loop continues at the next iteration, so only \"i = 1, j = 1\" and \"i = 1, j = 2\" are skipped.

\n

Using a labeled continue statement

\n
\n

Given an array of items and an array of tests, this example counts the number of items that pass all the tests.

\n

js

\n
// Numbers from 1 to 100\nconst items = Array.from({ length: 100 }, (_, i) => i + 1);\nconst tests = [\n  { pass: (item) => item % 2 === 0 },\n  { pass: (item) => item % 3 === 0 },\n  { pass: (item) => item % 5 === 0 },\n];\nlet itemsPassed = 0;\n\nitemIteration: for (const item of items) {\n  for (const test of tests) {\n    if (!test.pass(item)) {\n      continue itemIteration;\n    }\n  }\n\n  itemsPassed++;\n}\n
\n

Note how the continue itemIteration; statement skips the rest of the tests for the current item as well as the statement that updates the itemsPassed counter, and continues with the next item. If you don't use a label, you would need to use a boolean flag instead.

\n

js

\n
// Numbers from 1 to 100\nconst items = Array.from({ length: 100 }, (_, i) => i + 1);\nconst tests = [\n  { pass: (item) => item % 2 === 0 },\n  { pass: (item) => item % 3 === 0 },\n  { pass: (item) => item % 5 === 0 },\n];\nlet itemsPassed = 0;\n\nfor (const item of items) {\n  let passed = true;\n  for (const test of tests) {\n    if (!test.pass(item)) {\n      passed = false;\n      break;\n    }\n  }\n  if (passed) {\n    itemsPassed++;\n  }\n}\n
\n
\n

Using a labeled break statement

\n
\n

Given an array of items and an array of tests, this example determines whether all items pass all tests.

\n

js

\n
// Numbers from 1 to 100\nconst items = Array.from({ length: 100 }, (_, i) => i + 1);\nconst tests = [\n  { pass: (item) => item % 2 === 0 },\n  { pass: (item) => item % 3 === 0 },\n  { pass: (item) => item % 5 === 0 },\n];\nlet allPass = true;\n\nitemIteration: for (const item of items) {\n  for (const test of tests) {\n    if (!test.pass(item)) {\n      allPass = false;\n      break itemIteration;\n    }\n  }\n}\n
\n

Again, if you don't use a label, you would need to use a boolean flag instead.

\n

js

\n
// Numbers from 1 to 100\nconst items = Array.from({ length: 100 }, (_, i) => i + 1);\nconst tests = [\n  { pass: (item) => item % 2 === 0 },\n  { pass: (item) => item % 3 === 0 },\n  { pass: (item) => item % 5 === 0 },\n];\nlet allPass = true;\n\nfor (const item of items) {\n  let passed = true;\n  for (const test of tests) {\n    if (!test.pass(item)) {\n      passed = false;\n      break;\n    }\n  }\n  if (!passed) {\n    allPass = false;\n    break;\n  }\n}\n
\n
\n

Using a labeled block with break

\n
\n

You can label statements other than loops, such as simple blocks, but only break statements can reference non-loop labels.

\n

js

\n
foo: {\n  console.log(\"face\");\n  break foo;\n  console.log(\"this will not be executed\");\n}\nconsole.log(\"swap\");\n\n// Logs:\n// \"face\"\n// \"swap\"\n
\n
\n

Labeled function declarations

\n
\n

Labels can only be applied to statements, not declarations. There is a legacy grammar that allows function declarations to be labeled in non-strict code:

\n

js

\n
L: function F() {}\n
\n

In strict mode code, however, this will throw a SyntaxError:

\n

js

\n
\"use strict\";\nL: function F() {}\n// SyntaxError: functions cannot be labelled\n
\n

Non-plain functions, such as generator functions and async functions can neither be labeled in strict code, nor in non-strict code:

\n

js

\n
L: function* F() {}\n// SyntaxError: generator functions cannot be labelled\n
\n

The labeled function declaration syntax is deprecated and you should not use it, even in non-strict code. You cannot actually jump to this label within the function body.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-labelled-statements
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
label11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label\n

\n
\n", + "statements/with": "

with

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues, makes optimization impossible, and is forbidden in strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

The with statement extends the scope chain for a statement.

\n
\n

Syntax

\n
\n
\n

js

\n
with (expression)\n  statement\n
\n
expression

Adds the given expression to the scope chain used when evaluating the statement. The parentheses around the expression are required.

statement

Any statement. To execute multiple statements, use a block statement ({ ... }) to group those statements.

\n

Description

\n
\n

There are two types of identifiers: a qualified identifier and an unqualified identifier. An unqualified identifier is one that does not indicate where it comes from.

\n

js

\n
foo; // unqualified identifier\nfoo.bar; // bar is a qualified identifier\n
\n

Normally, an unqualified identifier is resolved by searching the scope chain for a variable with that name, while a qualified identifier is resolved by searching the prototype chain of an object for a property with that name.

\n

js

\n
const foo = { bar: 1 };\nconsole.log(foo.bar);\n// foo is found in the scope chain as a variable;\n// bar is found in foo as a property\n
\n

One exception to this is the global object, which sits on top of the scope chain, and whose properties automatically become global variables that can be referred to without qualifiers.

\n

js

\n
console.log(globalThis.Math === Math); // true\n
\n

The with statement adds the given object to the head of this scope chain during the evaluation of its statement body. Every unqualified name would first be searched within the object (through a in check) before searching in the upper scope chain.

Note that if the unqualified reference refers to a method of the object, the method is called with the object as its this value.

\n

js

\n
with ([1, 2, 3]) {\n  console.log(toString()); // 1,2,3\n}\n
\n

The object may have an @@unscopables property, which defines a list of properties that should not be added to the scope chain (for backward compatibility). See the Symbol.unscopables documentation for more information.

The reasons to use a with statement include saving one temporary variable and reducing file size by avoiding repeating a lengthy object reference. However, there are far more reasons why with statements are not desirable:

\n

Examples

\n

Using the with statement

\n
\n

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

\n

js

\n
let a, x, y;\nconst r = 10;\n\nwith (Math) {\n  a = PI * r * r;\n  x = r * cos(PI);\n  y = r * sin(PI / 2);\n}\n
\n
\n

Avoiding the with statement by destructuring properties into the current scope

\n
\n

You can usually avoid using with through property destructuring. Here we create an extra block to mimic the behavior of with creating an extra scope — but in actual usage, this block can usually be omitted.

\n

js

\n
let a, x, y;\nconst r = 10;\n\n{\n  const { PI, cos, sin } = Math;\n  a = PI * r * r;\n  x = r * cos(PI);\n  y = r * sin(PI / 2);\n}\n
\n
\n

Avoiding the with statement by using an IIFE

\n
\n

If you're producing an expression that must reuse a long-named reference multiple times, and your goal is to eliminate that lengthy name within your expression, you can wrap the expression in an IIFE and provide the long name as an argument.

\n

js

\n
const objectHavingAnEspeciallyLengthyName = { foo: true, bar: false };\n\nif (((o) => o.foo && !o.bar)(objectHavingAnEspeciallyLengthyName)) {\n  // This branch runs.\n}\n
\n
\n

Creating dynamic namespaces using the with statement and a proxy

\n
\n

with will transform every variable lookup to a property lookup, while Proxies allow trapping every property lookup call. You can create a dynamic namespace by combining them.

\n

js

\n
const namespace = new Proxy(\n  {},\n  {\n    has(target, key) {\n      // Avoid trapping global properties like `console`\n      if (key in globalThis) {\n        return false;\n      }\n      // Trap all property lookups\n      return true;\n    },\n    get(target, key) {\n      return key;\n    },\n  },\n);\n\nwith (namespace) {\n  console.log(a, b, c); // \"a\" \"b\" \"c\"\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-with-statement
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
with11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with\n

\n
\n", + "operators/object_initializer": "

Object initializer

An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). Objects can also be initialized using Object.create() or by invoking a constructor function with the new operator.

\n

Try it

\n

Syntax

\n
\n

js

\n
o = {\n  a: \"foo\",\n  b: 42,\n  c: {},\n  1: \"number literal property\",\n  \"foo:bar\": \"string literal property\",\n\n  shorthandProperty,\n\n  method(parameters) {\n    // …\n  },\n\n  get property() {},\n  set property(value) {},\n\n  [expression]: \"computed property\",\n\n  __proto__: prototype,\n\n  ...spreadProperty,\n};\n
\n

Description

\n

An object initializer is an expression that describes the initialization of an Object. Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

Object literal syntax vs. JSON

\n
\n

The object literal syntax is not the same as the JavaScript Object Notation (JSON). Although they look similar, there are differences between them:

JSON is a strict subset of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate __proto__ keys, which does not apply to JSON.parse(). The latter treats __proto__ like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the __proto__ key — for object literals, it sets the object's prototype; for JSON, it's a normal property.

\n

js

\n
console.log(JSON.parse('{ \"__proto__\": 0, \"__proto__\": 1 }')); // {__proto__: 1}\nconsole.log({ \"__proto__\": 0, \"__proto__\": 1 }); // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\n\nconsole.log(JSON.parse('{ \"__proto__\": {} }')); // { __proto__: {} }\nconsole.log({ \"__proto__\": {} }); // {} (with {} as prototype)\n
\n
\n

Examples

\n

Creating objects

\n
\n

An empty object with no properties can be created like this:

\n

js

\n
const object = {};\n
\n

However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of key: value pairs delimited by commas.

The following code creates an object with three properties and the keys are \"foo\", \"age\" and \"baz\". The values of these keys are a string \"bar\", the number 42, and another object.

\n

js

\n
const object = {\n  foo: \"bar\",\n  age: 42,\n  baz: { myProp: 12 },\n};\n
\n
\n

Accessing properties

\n
\n

Once you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See property accessors for detailed information.)

\n

js

\n
object.foo; // \"bar\"\nobject[\"age\"]; // 42\nobject.baz; // {myProp: 12}\nobject.baz.myProp; //12\n
\n
\n

Property definitions

\n
\n

We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:

\n

js

\n
const a = \"foo\";\nconst b = 42;\nconst c = {};\n\nconst o = {\n  a: a,\n  b: b,\n  c: c,\n};\n
\n

There is a shorter notation available to achieve the same:

\n

js

\n
const a = \"foo\";\nconst b = 42;\nconst c = {};\n\n// Shorthand property names\nconst o = { a, b, c };\n\n// In other words,\nconsole.log(o.a === { a }.a); // true\n
\n

Duplicate property names

When using the same name for your properties, the second property will overwrite the first.

\n

js

\n
const a = { x: 1, x: 2 };\nconsole.log(a); // {x: 2}\n
\n

After ES2015, duplicate property names are allowed everywhere, including strict mode. You can also have duplicate property names in classes. The only exception is private properties, which must be unique in the class body.

\n

Method definitions

\n
\n

A property of an object can also refer to a function or a getter or setter method.

\n

js

\n
const o = {\n  property: function (parameters) {},\n  get property() {},\n  set property(value) {},\n};\n
\n

A shorthand notation is available, so that the keyword function is no longer necessary.

\n

js

\n
// Shorthand method names\nconst o = {\n  property(parameters) {},\n};\n
\n

There is also a way to concisely define generator methods.

\n

js

\n
const o = {\n  *generator() {\n    // …\n  },\n};\n
\n

Which is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):

\n

js

\n
const o = {\n  generator: function* () {\n    // …\n  },\n};\n
\n

For more information and examples about methods, see method definitions.

\n

Computed property names

\n
\n

The object initializer syntax also supports computed property names. That allows you to put an expression in square brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.

Now you can use a similar syntax in object literals, too:

\n

js

\n
// Computed property names\nlet i = 0;\nconst a = {\n  [`foo${++i}`]: i,\n  [`foo${++i}`]: i,\n  [`foo${++i}`]: i,\n};\n\nconsole.log(a.foo1); // 1\nconsole.log(a.foo2); // 2\nconsole.log(a.foo3); // 3\n\nconst items = [\"A\", \"B\", \"C\"];\nconst obj = {\n  [items]: \"Hello\",\n};\nconsole.log(obj); // A,B,C: \"Hello\"\nconsole.log(obj[\"A,B,C\"]); // \"Hello\"\n\nconst param = \"size\";\nconst config = {\n  [param]: 12,\n  [`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,\n};\n\nconsole.log(config); // {size: 12, mobileSize: 4}\n
\n
\n

Spread properties

\n
\n

Object literals support the spread syntax. It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging objects is now possible using a shorter syntax than Object.assign().

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\n\nconst clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\n\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"baz\", x: 42, y: 13 }\n
\n

Warning: Note that Object.assign() triggers setters, whereas the spread syntax doesn't!

\n

Prototype setter

\n
\n

A property definition of the form __proto__: value or \"__proto__\": value does not create a property with the name __proto__. Instead, if the provided value is an object or null, it points the [[Prototype]] of the created object to that value. (If the value is not an object or null, the object is not changed.)

Note that the __proto__ key is standardized syntax, in contrast to the non-standard and non-performant Object.prototype.__proto__ accessors. It sets the [[Prototype]] during object creation, similar to Object.create — instead of mutating the prototype chain.

\n

js

\n
const obj1 = {};\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\n\nconst obj2 = { __proto__: null };\nconsole.log(Object.getPrototypeOf(obj2)); // null\n\nconst protoObj = {};\nconst obj3 = { \"__proto__\": protoObj };\nconsole.log(Object.getPrototypeOf(obj3) === protoObj); // true\n\nconst obj4 = { __proto__: \"not an object or null\" };\nconsole.log(Object.getPrototypeOf(obj4) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj4, \"__proto__\")); // false\n
\n

Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.

Property definitions that do not use \"colon\" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.

\n

js

\n
const __proto__ = \"variable\";\n\nconst obj1 = { __proto__ };\nconsole.log(Object.getPrototypeOf(obj1) === Object.prototype); // true\nconsole.log(Object.hasOwn(obj1, \"__proto__\")); // true\nconsole.log(obj1.__proto__); // \"variable\"\n\nconst obj2 = { __proto__() { return \"hello\"; } };\nconsole.log(obj2.__proto__()); // \"hello\"\n\nconst obj3 = { [\"__proto__\"]: 17 };\nconsole.log(obj3.__proto__); // 17\n\n// Mixing prototype setter with normal own properties with \"__proto__\" key\nconst obj4 = { [\"__proto__\"]: 17, __proto__: {} }; // {__proto__: 17} (with {} as prototype)\nconst obj5 = {\n  [\"__proto__\"]: 17,\n  __proto__: {},\n  __proto__: null, // SyntaxError: Duplicate __proto__ fields are not allowed in object literals\n};\nconst obj6 = {\n  [\"__proto__\"]: 17,\n  [\"__proto__\"]: \"hello\",\n  __proto__: null,\n}; // {__proto__: \"hello\"} (with null as prototype)\nconst obj7 =  {\n  [\"__proto__\"]: 17,\n  __proto__,\n  __proto__: null,\n}; // {__proto__: \"variable\"} (with null as prototype)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object-initializer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Object_initializer11211414.418410.111.01.00.10.0
computed_property_names471234No3484747343485.0?4.0.0
shorthand_method_names471234No3494747343495.0?4.0.0
shorthand_property_names471233No3494747333495.0?4.0.0
spread_properties607955No4711.16060554411.38.0?8.3.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer\n

\n
\n", + "operators/function": "

function expression

\n

The function keyword can be used to define a function inside an expression.

You can also define functions using the function declaration or the arrow syntax.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
function (param0) {\n  statements\n}\nfunction (param0, param1) {\n  statements\n}\nfunction (param0, param1, /* …, */ paramN) {\n  statements\n}\n\nfunction name(param0) {\n  statements\n}\nfunction name(param0, param1) {\n  statements\n}\nfunction name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: An expression statement cannot begin with the keyword function to avoid ambiguity with a function declaration. The function keyword only begins an expression when it appears in a context that cannot accept statements.

\n

Parameters

\n
\nname Optional\n

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

\nparamN Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements which comprise the body of the function.

Description

\n

A function expression is very similar to, and has almost the same syntax as, a function declaration. The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.

Function expression hoisting

\n
\n

Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them:

\n

js

\n
console.log(notHoisted); // undefined\n// Even though the variable name is hoisted,\n// the definition isn't. so it's undefined.\nnotHoisted(); // TypeError: notHoisted is not a function\n\nvar notHoisted = function () {\n  console.log(\"bar\");\n};\n
\n
\n

Named function expression

\n
\n

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This avoids using the deprecated arguments.callee property to call the function recursively.

\n

js

\n
const math = {\n  factit: function factorial(n) {\n    console.log(n);\n    if (n <= 1) {\n      return 1;\n    }\n    return n * factorial(n - 1);\n  },\n};\n\nmath.factit(3); //3;2;1;\n
\n

If a function expression is named, the name property of the function is set to that name, instead of the implicit name inferred from syntax (such as the variable the function is assigned to).

Unlike declarations, the name of the function expressions is read-only.

\n

js

\n
function foo() {\n  foo = 1;\n}\nfoo();\nconsole.log(foo); // 1\n(function foo() {\n  foo = 1; // TypeError: Assignment to constant variable.\n})();\n
\n
\n

Examples

\n

Creating an unnamed function

\n
\n

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

\n

js

\n
const x = function (y) {\n  return y * y;\n};\n
\n
\n

Using a function as a callback

\n
\n

More commonly it is used as a callback:

\n

js

\n
button.addEventListener(\"click\", function (event) {\n  console.log(\"button is clicked!\");\n});\n
\n
\n

Using an Immediately Invoked Function Expression (IIFE)

\n
\n

An anonymous function is created and called:

\n

js

\n
(function () {\n  console.log(\"Code runs!\");\n})();\n\n// or\n\n!function () {\n  console.log(\"Code runs!\");\n}();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
function11213314.418410.111.01.00.10.0
trailing_comma581452No451058585243107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function\n

\n
\n", + "operators/class": "

class expression

\n

The class keyword can be used to define a class inside an expression.

You can also define classes using the class declaration.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
class {\n  // class body\n}\nclass name {\n  // class body\n}\n
\n

Note: An expression statement cannot begin with the keyword class to avoid ambiguity with a class declaration. The class keyword only begins an expression when it appears in a context that cannot accept statements.

\n

Description

\n

A class expression is very similar to, and has almost the same syntax as, a class declaration. As with class declarations, the body of a class expression is executed in strict mode. The main difference between a class expression and a class declaration is the class name, which can be omitted in class expressions to create anonymous classes. Class expressions allow you to redefine classes, while redeclaring a class using class declarations throws a SyntaxError. See also the chapter about classes for more information.

Examples

\n

A simple class expression

\n
\n

This is just a simple anonymous class expression which you can refer to using the variable Foo.

\n

js

\n
const Foo = class {\n  constructor() {}\n  bar() {\n    return \"Hello World!\";\n  }\n};\n\nconst instance = new Foo();\ninstance.bar(); // \"Hello World!\"\nFoo.name; // \"Foo\"\n
\n
\n

Named class expressions

\n
\n

If you want to refer to the current class inside the class body, you can create a named class expression. The name is only visible within the scope of the class expression itself.

\n

js

\n
const Foo = class NamedFoo {\n  constructor() {}\n  whoIsThere() {\n    return NamedFoo.name;\n  }\n};\nconst bar = new Foo();\nbar.whoIsThere(); // \"NamedFoo\"\nNamedFoo.name; // ReferenceError: NamedFoo is not defined\nFoo.name; // \"NamedFoo\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-class-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
class421345No2974242452974.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/class\n

\n
\n", + "operators/function*": "

function* expression

\n

The function* keyword can be used to define a generator function inside an expression.

You can also define generator functions using the function* declaration.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
function* (param0) {\n  statements\n}\nfunction* (param0, param1) {\n  statements\n}\nfunction* (param0, param1, /* …, */ paramN) {\n  statements\n}\n\nfunction* name(param0) {\n  statements\n}\nfunction* name(param0, param1) {\n  statements\n}\nfunction* name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: An expression statement cannot begin with the keyword function to avoid ambiguity with a function* declaration. The function keyword only begins an expression when it appears in a context that cannot accept statements.

\n

Parameters

\n
\nname Optional\n

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

\nparamN Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements which comprise the body of the function.

Description

\n

A function* expression is very similar to, and has almost the same syntax as, a function* declaration. The main difference between a function* expression and a function* declaration is the function name, which can be omitted in function* expressions to create anonymous functions. A function* expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to create an ad-hoc iterable iterator object. See also the chapter about functions for more information.

Examples

\n

Using function*

\n
\n

The following example defines an unnamed generator function and assigns it to x. The function yields the square of its argument:

\n

js

\n
const x = function* (y) {\n  yield y * y;\n};\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
function*491226No361049492636105.01.04.0.0
trailing_comma587952No451058585243107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function*\n

\n
\n", + "operators/async_function": "

async function expression

\n

The async function keywords can be used to define an async function inside an expression.

You can also define async functions using the async function declaration or the arrow syntax.

\n
\n

Syntax

\n
\n
\n

js

\n
async function (param0) {\n  statements\n}\nasync function (param0, param1) {\n  statements\n}\nasync function (param0, param1, /* …, */ paramN) {\n  statements\n}\n\nasync function name(param0) {\n  statements\n}\nasync function name(param0, param1) {\n  statements\n}\nasync function name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: An expression statement cannot begin with the keywords async function to avoid ambiguity with an async function declaration. The async function keywords only begin an expression when they appear in a context that cannot accept statements.

\n

Parameters

\n
\nname Optional\n

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

\nparamN Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements which comprise the body of the function.

Description

\n

An async function expression is very similar to, and has almost the same syntax as, an async function declaration. The main difference between an async function expression and an async function declaration is the function name, which can be omitted in async function expressions to create anonymous functions. An async function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to mimic top-level await. See also the chapter about functions for more information.

Examples

\n

Simple example

\n
\n

js

\n
function resolveAfter2Seconds(x) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve(x);\n    }, 2000);\n  });\n}\n\n// async function expression assigned to a variable\nconst add = async function (x) {\n  const a = await resolveAfter2Seconds(20);\n  const b = await resolveAfter2Seconds(30);\n  return x + a + b;\n};\n\nadd(10).then((v) => {\n  console.log(v); // prints 60 after 4 seconds.\n});\n\n// async function expression used as an IIFE\n(async function (x) {\n  const p1 = resolveAfter2Seconds(20);\n  const p2 = resolveAfter2Seconds(30);\n  return x + (await p1) + (await p2);\n})(10).then((v) => {\n  console.log(v); // prints 60 after 2 seconds.\n});\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
async_function551552No4210.15555524210.36.01.07.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function\n

\n
\n", + "operators/async_function*": "

async function* expression

\n

The async function* keywords can be used to define an asynchronous generator function inside an expression.

You can also define async generator functions using the async function* declaration.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
async function* (param0) {\n  statements\n}\nasync function* (param0, param1) {\n  statements\n}\nasync function* (param0, param1, /* …, */ paramN) {\n  statements\n}\n\nasync function* name(param0) {\n  statements\n}\nasync function* name(param0, param1) {\n  statements\n}\nasync function* name(param0, param1, /* …, */ paramN) {\n  statements\n}\n
\n

Note: An expression statement cannot begin with the keywords async function to avoid ambiguity with an async function* declaration. The async function keywords only begin an expression when they appear in a context that cannot accept statements.

\n

Parameters

\n
\nname Optional\n

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

\nparamN Optional\n

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

\nstatements Optional\n

The statements which comprise the body of the function.

Description

\n

An async function* expression is very similar to, and has almost the same syntax as, an async function* declaration. The main difference between an async function* expression and an async function* declaration is the function name, which can be omitted in async function* expressions to create anonymous functions. An async function* expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to create an ad-hoc async iterable object. See also the chapter about functions for more information.

Examples

\n

Using async function*

\n
\n

The following example defines an unnamed asynchronous generator function and assigns it to x. The function yields the square of its argument:

\n

js

\n
const x = async function* (y) {\n  yield Promise.resolve(y * y);\n};\nx(6)\n  .next()\n  .then((res) => console.log(res.value)); // 36\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-generator-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
async_function*637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function*\n

\n
\n", + "template_literals": "

Template literals (Template strings)

\n

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom tag function to perform whatever operations you want on the different parts of the template literal.

\n
\n

Syntax

\n
\n

js

\n
`string text`\n\n`string text line 1\n string text line 2`\n\n`string text ${expression} string text`\n\ntagFunction`string text ${expression} string text`\n
\n

Parameters

\n
string text

The string text that will become part of the template literal. Almost all characters are allowed literally, including line breaks and other whitespace characters. However, invalid escape sequences will cause a syntax error, unless a tag function is used.

expression

An expression to be inserted in the current position, whose value is converted to a string or passed to tagFunction.

tagFunction

If specified, it will be called with the template strings array and substitution expressions, and the return value becomes the value of the template literal. See tagged templates.

Description

\n
\n

Template literals are enclosed by backtick (`) characters instead of double or single quotes.

Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression}. The strings and placeholders get passed to a function — either a default function, or a function you supply. The default function (when you don't supply your own) just performs string interpolation to do substitution of the placeholders and then concatenate the parts into a single string.

To supply a function of your own, precede the template literal with a function name; the result is called a tagged template. In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal.

To escape a backtick in a template literal, put a backslash (\\) before the backtick.

\n

js

\n
`\\`` === \"`\"; // true\n
\n

Dollar signs can be escaped as well to prevent interpolation.

\n

js

\n
`\\${1}` === \"${1}\"; // true\n
\n
\n

Multi-line strings

\n
\n

Any newline characters inserted in the source are part of the template literal.

Using normal strings, you would have to use the following syntax in order to get multi-line strings:

\n

js

\n
console.log(\"string text line 1\\n\" + \"string text line 2\");\n// \"string text line 1\n// string text line 2\"\n
\n

Using template literals, you can do the same with this:

\n

js

\n
console.log(`string text line 1\nstring text line 2`);\n// \"string text line 1\n// string text line 2\"\n
\n
\n

String interpolation

\n
\n

Without template literals, when you want to combine output from expressions with strings, you'd concatenate them using the addition operator +:

\n

js

\n
const a = 5;\nconst b = 10;\nconsole.log(\"Fifteen is \" + (a + b) + \" and\\nnot \" + (2 * a + b) + \".\");\n// \"Fifteen is 15 and\n// not 20.\"\n
\n

That can be hard to read – especially when you have multiple expressions.

With template literals, you can avoid the concatenation operator — and improve the readability of your code — by using placeholders of the form ${expression} to perform substitutions for embedded expressions:

\n

js

\n
const a = 5;\nconst b = 10;\nconsole.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);\n// \"Fifteen is 15 and\n// not 20.\"\n
\n

Note that there's a mild difference between the two syntaxes. Template literals coerce their expressions directly to strings, while addition coerces its operands to primitives first. For more information, see the reference page for the + operator.

\n

Nesting templates

\n
\n

In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backtick-delimited template, it is simple to allow inner backticks by using them inside an ${expression} placeholder within the template.

For example, without template literals, if you wanted to return a certain value based on a particular condition, you could do something like the following:

\n

js

\n
let classes = \"header\";\nclasses += isLargeScreen()\n  ? \"\"\n  : item.isCollapsed\n  ? \" icon-expander\"\n  : \" icon-collapser\";\n
\n

With a template literal but without nesting, you could do this:

\n

js

\n
const classes = `header ${\n  isLargeScreen() ? \"\" : item.isCollapsed ? \"icon-expander\" : \"icon-collapser\"\n}`;\n
\n

With nesting of template literals, you can do this:

\n

js

\n
const classes = `header ${\n  isLargeScreen() ? \"\" : `icon-${item.isCollapsed ? \"expander\" : \"collapser\"}`\n}`;\n
\n
\n

Tagged templates

\n
\n

A more advanced form of template literals are tagged templates.

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something completely different, as described in one of the following examples.)

The name of the function used for the tag can be whatever you want.

\n

js

\n
const person = \"Mike\";\nconst age = 28;\n\nfunction myTag(strings, personExp, ageExp) {\n  const str0 = strings[0]; // \"That \"\n  const str1 = strings[1]; // \" is a \"\n  const str2 = strings[2]; // \".\"\n\n  const ageStr = ageExp > 99 ? \"centenarian\" : \"youngster\";\n\n  // We can even return a string built using a template literal\n  return `${str0}${personExp}${str1}${ageStr}${str2}`;\n}\n\nconst output = myTag`That ${person} is a ${age}.`;\n\nconsole.log(output);\n// That Mike is a youngster.\n
\n

The tag does not have to be a plain identifier. You can use any expression with precedence greater than 16, which includes property access, function call, new expression, or even another tagged template literal.

\n

js

\n
console.log`Hello`; // [ 'Hello' ]\nconsole.log.bind(1, 2)`Hello`; // 2 [ 'Hello' ]\nnew Function(\"console.log(arguments)\")`Hello`; // [Arguments] { '0': [ 'Hello' ] }\n\nfunction recursive(strings, ...values) {\n  console.log(strings, values);\n  return recursive;\n}\nrecursive`Hello``World`;\n// [ 'Hello' ] []\n// [ 'World' ] []\n
\n

While technically permitted by the syntax, untagged template literals are strings and will throw a TypeError when chained.

\n

js

\n
console.log(`Hello``World`); // TypeError: \"Hello\" is not a function\n
\n

The only exception is optional chaining, which will throw a syntax error.

\n

js

\n
console.log?.`Hello`; // SyntaxError: Invalid tagged template on optional chain\nconsole?.log`Hello`; // SyntaxError: Invalid tagged template on optional chain\n
\n

Note that these two expressions are still parsable. This means they would not be subject to automatic semicolon insertion, which will only insert semicolons to fix code that's otherwise unparsable.

\n

js

\n
// Still a syntax error\nconst a = console?.log\n`Hello`\n
\n

Tag functions don't even need to return a string!

\n

js

\n
function template(strings, ...keys) {\n  return (...values) => {\n    const dict = values[values.length - 1] || {};\n    const result = [strings[0]];\n    keys.forEach((key, i) => {\n      const value = Number.isInteger(key) ? values[key] : dict[key];\n      result.push(value, strings[i + 1]);\n    });\n    return result.join(\"\");\n  };\n}\n\nconst t1Closure = template`${0}${1}${0}!`;\n// const t1Closure = template([\"\",\"\",\"\",\"!\"],0,1,0);\nt1Closure(\"Y\", \"A\"); // \"YAY!\"\n\nconst t2Closure = template`${0}${\"foo\"}!`;\n// const t2Closure = template([\"\",\" \",\"!\"],0,\"foo\");\nt2Closure(\"Hello\", { foo: \"World\" }); // \"Hello World!\"\n\nconst t3Closure = template`I'm ${\"name\"}. I'm almost ${\"age\"} years old.`;\n// const t3Closure = template([\"I'm \", \". I'm almost \", \" years old.\"], \"name\", \"age\");\nt3Closure(\"foo\", { name: \"MDN\", age: 30 }); // \"I'm MDN. I'm almost 30 years old.\"\nt3Closure({ name: \"MDN\", age: 30 }); // \"I'm MDN. I'm almost 30 years old.\"\n
\n

The first argument received by the tag function is an array of strings. For any template literal, its length is equal to the number of substitutions (occurrences of ${…}) plus one, and is therefore always non-empty.

For any particular tagged template literal expression, the tag function will always be called with the exact same literal array, no matter how many times the literal is evaluated.

\n

js

\n
const callHistory = [];\n\nfunction tag(strings, ...values) {\n  callHistory.push(strings);\n  // Return a freshly made object\n  return {};\n}\n\nfunction evaluateLiteral() {\n  return tag`Hello, ${\"world\"}!`;\n}\n\nconsole.log(evaluateLiteral() === evaluateLiteral()); // false; each time `tag` is called, it returns a new object\nconsole.log(callHistory[0] === callHistory[1]); // true; all evaluations of the same tagged literal would pass in the same strings array\n
\n

This allows the tag to cache the result based on the identity of its first argument. To further ensure the array value's stability, the first argument and its raw property are both frozen, so you can't mutate them in any way.

\n

Raw strings

\n
\n

The special raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing escape sequences.

\n

js

\n
function tag(strings) {\n  console.log(strings.raw[0]);\n}\n\ntag`string text line 1 \\n string text line 2`;\n// Logs \"string text line 1 \\n string text line 2\" ,\n// including the two characters '\\' and 'n'\n
\n

In addition, the String.raw() method exists to create raw strings just like the default template function and string concatenation would create.

\n

js

\n
const str = String.raw`Hi\\n${2 + 3}!`;\n// \"Hi\\\\n5!\"\n\nstr.length;\n// 6\n\nArray.from(str).join(\",\");\n// \"H,i,\\\\,n,5,!\"\n
\n

String.raw functions like an \"identity\" tag if the literal doesn't contain any escape sequences. In case you want an actual identity tag that always works as if the literal is untagged, you can make a custom function that passes the \"cooked\" (i.e. escape sequences are processed) literal array to String.raw, pretending they are raw strings.

\n

js

\n
const identity = (strings, ...values) =>\n  String.raw({ raw: strings }, ...values);\nconsole.log(identity`Hi\\n${2 + 3}!`);\n// Hi\n// 5!\n
\n

This is useful for many tools which give special treatment to literals tagged by a particular name.

\n

js

\n
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);\n// Some formatters will format this literal's content as HTML\nconst doc = html`<!doctype html>\n  <html lang=\"en-US\">\n    <head>\n      <title>Hello</title>\n    </head>\n    <body>\n      <h1>Hello world!</h1>\n    </body>\n  </html>`;\n
\n
\n

Tagged templates and escape sequences

\n
\n

In normal template literals, the escape sequences in string literals are all allowed. Any other non-well-formed escape sequence is a syntax error. This includes:

Note: \\ followed by other characters, while they may be useless since nothing is escaped, are not syntax errors.

However, this is problematic for tagged templates, which, in addition to the \"cooked\" literal, also have access to the raw literals (escape sequences are preserved as-is).

Tagged templates should allow the embedding of languages (for example DSLs, or LaTeX), where other escapes sequences are common. Therefore, the syntax restriction of well-formed escape sequences is removed from tagged templates.

\n

js

\n
latex`\\unicode`;\n// Throws in older ECMAScript versions (ES2016 and earlier)\n// SyntaxError: malformed Unicode character escape sequence\n
\n

However, illegal escape sequences must still be represented in the \"cooked\" representation. They will show up as undefined element in the \"cooked\" array:

\n

js

\n
function latex(str) {\n  return { cooked: str[0], raw: str.raw[0] };\n}\n\nlatex`\\unicode`;\n\n// { cooked: undefined, raw: \"\\\\unicode\" }\n
\n

Note that the escape-sequence restriction is only dropped from tagged templates, but not from untagged template literals:

\n

js

\n
const bad = `bad escape sequence: \\unicode`;\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-template-literals
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Template_literals411234No2894141342894.01.04.0.0
template_literal_revision627953No491162625346118.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\n

\n
\n", + "operators/grouping": "

Grouping operator ( )

The ( ) operator controls the precedence of evaluation in expressions. It also acts as a container for arbitrary expressions in certain syntactic constructs, where ambiguity or syntax errors would otherwise occur.

\n

Try it

\n

Syntax

\n
\n

js

\n
(expression)\n
\n

Parameters

\n
expression

Any expression to be evaluated, including comma-joined expressions.

Description

\n

The grouping operator consists of a pair of parentheses around an expression that groups the contents. The operator overrides the normal operator precedence, so that operators with lower precedence (as low as the comma operator) can be evaluated before an operator with higher precedence.

Examples

\n

Using the grouping operator

\n
\n

Evaluating addition and subtraction before multiplication and division.

\n

js

\n
const a = 1;\nconst b = 2;\nconst c = 3;\n\n// default precedence\na + b * c; // 7\n// evaluated by default like this\na + (b * c); // 7\n\n// now overriding precedence\n// addition before multiplication\n(a + b) * c; // 9\n\n// which is equivalent to\na * c + b * c; // 9\n
\n

Notice in these examples that the order in which the operators evaluate has changed, but the order in which the operands evaluate has not. For example, in this code, the function invocations a(), b(), and c() are evaluated left-to-right (the normal order of evaluation) before the operator order is considered.

\n

js

\n
a() * (b() + c());\n
\n

The function a will be called before the function b, which will be called before the function c. For more on operator precedence, see its reference page.

\n

Using the grouping operator to eliminate parsing ambiguity

\n
\n

An expression statement cannot start with the keyword function, because the parser would see it as the start of a function declaration. This means the following IIFE syntax is invalid:

\n

js

\n
function () {\n  // code\n}();\n
\n

The grouping operator can be used to eliminate this ambiguity, since when the parser sees the left parenthesis, it knows that what follows must be an expression instead of a declaration.

\n

js

\n
(function () {\n  // code\n})();\n
\n

You may also use the void operator to eliminate ambiguity.

In an arrow function expression body (one that directly returns an expression without the keyword return), the grouping operator can be used to return an object literal expression, because otherwise the left curly brace would be interpreted as the start of the function body.

\n

js

\n
const f = () => ({ a: 1 });\n
\n

If a property is accessed on a number literal, the property accessor dot . may be ambiguous with a decimal point, unless the number already has a decimal point. You can wrap integer literals in parentheses to eliminate this ambiguity.

\n

js

\n
(1).toString(); // \"1\"\n
\n
\n

Grouping operator and automatic semicolon insertion

\n
\n

The grouping operator can mitigate automatic semicolon insertion (ASI) pitfalls. For example, the return keyword and the returned expression cannot have a line break in between:

\n

js

\n
function sum(a, b) {\n  return\n    a + b;\n}\n
\n

This code will return undefined, because a semicolon is inserted directly after the return keyword, which causes the function to return immediately without evaluating a + b. In case the returned expression is long and you want to keep it well-formatted, you may use the grouping operator to signify that the return keyword is followed by an expression and prevent semicolon insertion:

\n

js

\n
function sum(a, b) {\n  return (\n    a + b\n  );\n}\n
\n

However, grouping may also introduce ASI hazards. When a line starts with a left parenthesis and the previous line ends with an expression, the parser will not insert a semicolon before the line break, because it could be the middle of a function call. For example:

\n

js

\n
const a = 1\n(1).toString()\n
\n

This code would be parsed as:

\n

js

\n
const a = 1(1).toString();\n
\n

Which throws \"TypeError: 1 is not a function\". If your coding style does not use semicolons, remember that when a line starts with a left parenthesis, prefix it with a semicolon. This practice is recommended by several formatters and/or style guides, including Prettier and standard.

\n

js

\n
const a = 1\n;(1).toString()\n
\n

For more advice on working with ASI, see its reference section.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-grouping-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Grouping11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping\n

\n
\n", + "operators/property_accessors": "

Property accessors

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

\n

Try it

\n

Syntax

\n
\n

js

\n
object.propertyName\nobject[expression]\n
\n

Description

\n
\n

One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.

There are two ways to access properties: dot notation and bracket notation.

\n

Dot notation

\n
\n

In the object.propertyName syntax, the propertyName must be a valid JavaScript identifier which can also be a reserved word. For example, object.$1 is valid, while object.1 is not.

\n

js

\n
const variable = object.propertyName;\nobject.propertyName = value;\n
\n
\n

js

\n
const object = {};\nobject.$1 = \"foo\";\nconsole.log(object.$1); // 'foo'\n
\n
\n

js

\n
const object = {};\nobject.1 = 'bar'; // SyntaxError\nconsole.log(object.1); // SyntaxError\n
\n

Here, the method named createElement is retrieved from document and is called.

\n

js

\n
document.createElement(\"pre\");\n
\n

If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.

\n

js

\n
77 .toExponential();\n// or\n77\n.toExponential();\n// or\n(77).toExponential();\n// or\n77..toExponential();\n// or\n77.0.toExponential();\n// because 77. === 77.0, no ambiguity\n
\n
\n

Bracket notation

\n
\n

In the object[expression] syntax, the expression should evaluate to a string or Symbol that represents the property's name. So, it can be any string literal, for example, including '1foo', '!bar!', or even ' ' (a space).

\n

js

\n
const variable = object[propertyName];\nobject[propertyName] = value;\n
\n

This does the exact same thing as the previous example.

\n

js

\n
document[\"createElement\"](\"pre\");\n
\n

A space before bracket notation is allowed.

\n

js

\n
document [\"createElement\"](\"pre\");\n
\n

Passing expressions that evaluate to property name will do the same thing as directly passing the property name.

\n

js

\n
const key = \"name\";\nconst getKey = () => \"name\";\nconst Obj = { name: \"Michel\" };\n\nObj[\"name\"]; // returns \"Michel\"\nObj[key]; // evaluates to Obj[\"name\"], and returns \"Michel\"\nObj[getKey()]; // evaluates to Obj[\"name\"], and returns \"Michel\"\n
\n

However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.

\n

Property names

\n
\n

Each property name is a string or a Symbol. Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'.

\n

js

\n
const object = {};\nobject[\"1\"] = \"value\";\nconsole.log(object[1]);\n
\n

This also outputs 'value', since both foo and bar are converted to the same string (\"[object Object]\").

\n

js

\n
const foo = { uniqueProp: 1 };\nconst bar = { uniqueProp: 2 };\nconst object = {};\nobject[foo] = \"value\";\nconsole.log(object[bar]);\n
\n
\n

Method binding

\n
\n

It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function instance as its value).

A method is not bound to the object that it is a property of. Specifically, this is not fixed in a method and does not necessarily refer to the object containing the method. Instead, this is \"passed\" by the function call. See the reference for this.

\n

Examples

\n

Bracket notation vs. eval()

\n
\n

JavaScript novices often make the mistake of using eval() where the bracket notation can be used instead.

For example, the following syntax is often seen in many scripts.

\n

js

\n
const x = eval(`document.forms.form_name.elements.${strFormControl}.value`);\n
\n

eval() is slow and should be avoided whenever possible. Also, strFormControl would have to hold an identifier, which is not required for names and ids of form controls. It is better to use bracket notation instead:

\n

js

\n
const x = document.forms.form_name.elements[strFormControl].value;\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-property-accessors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Property_accessors11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors\n

\n
\n", + "operators/this": "

this

\n

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. The Function.prototype.bind() method can set the value of a function's this regardless of how it's called, and arrow functions don't provide their own this binding (it retains the this value of the enclosing lexical context).

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
this\n
\n

Value

\n

In non–strict mode, this is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.

Description

\n

The value of this depends on in which context it appears: function, class, or global.

Function context

\n
\n

Inside a function, the value of this depends on how the function is called. Think about this as a hidden parameter of a function — just like the parameters declared in the function definition, this is a binding that the language creates for you when the function body is evaluated.

For a typical function, the value of this is the object that the function is accessed on. In other words, if the function call is in the form obj.f(), then this refers to obj. For example:

\n

js

\n
function getThis() {\n  return this;\n}\n\nconst obj1 = { name: \"obj1\" };\nconst obj2 = { name: \"obj2\" };\n\nobj1.getThis = getThis;\nobj2.getThis = getThis;\n\nconsole.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }\nconsole.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }\n
\n

Note how the function is the same, but based on how it's invoked, the value of this is different. This is analogous to how function parameters work.

The value of this is not the object that has the function as an own property, but the object that is used to call the function. You can prove this by calling a method of an object up in the prototype chain.

\n

js

\n
const obj3 = {\n  __proto__: obj1,\n  name: \"obj3\",\n};\n\nconsole.log(obj3.getThis()); // { name: 'obj3' }\n
\n

The value of this always changes based on how a function is called, even when the function was defined on an object at creation:

\n

js

\n
const obj4 = {\n  name: \"obj4\",\n  getThis() {\n    return this;\n  },\n};\n\nconst obj5 = { name: \"obj5\" };\n\nobj5.getThis = obj4.getThis;\nconsole.log(obj5.getThis()); // { name: 'obj5', getThis: [Function: getThis] }\n
\n

If the value that the method is accessed on is a primitive, this will be a primitive value as well — but only if the function is in strict mode.

\n

js

\n
function getThisStrict() {\n  \"use strict\"; // Enter strict mode\n  return this;\n}\n\n// Only for demonstration — you should not mutate built-in prototypes\nNumber.prototype.getThisStrict = getThisStrict;\nconsole.log(typeof (1).getThisStrict()); // \"number\"\n
\n

If the function is called without being accessed on anything, this will be undefined — but only if the function is in strict mode.

\n

js

\n
console.log(typeof getThisStrict()); // \"undefined\"\n
\n

In non-strict mode, a special process called this substitution ensures that the value of this is always an object. This means:

\n

js

\n
function getThis() {\n  return this;\n}\n\n// Only for demonstration — you should not mutate built-in prototypes\nNumber.prototype.getThis = getThis;\nconsole.log(typeof (1).getThis()); // \"object\"\nconsole.log(getThis() === globalThis); // true\n
\n

In typical function calls, this is implicitly passed like a parameter through the function's prefix (the part before the dot). You can also explicitly set the value of this using the Function.prototype.call(), Function.prototype.apply(), or Reflect.apply() methods. Using Function.prototype.bind(), you can create a new function with a specific value of this that doesn't change regardless of how the function is called. When using these methods, the this substitution rules above still apply if the function is non-strict.

Callbacks

When a function is passed as a callback, the value of this depends on how the callback is called, which is determined by the implementor of the API. Callbacks are typically called with a this value of undefined (calling it directly without attaching it to any object), which means if the function is non–strict, the value of this is the global object (globalThis). This is the case for iterative array methods, the Promise() constructor, etc.

\n

js

\n
function logThis() {\n  \"use strict\";\n  console.log(this);\n}\n\n[1, 2, 3].forEach(logThis); // undefined, undefined, undefined\n
\n

Some APIs allow you to set a this value for invocations of the callback. For example, all iterative array methods and related ones like Set.prototype.forEach() accept an optional thisArg parameter.

\n

js

\n
[1, 2, 3].forEach(logThis, { name: \"obj\" });\n// { name: 'obj' }, { name: 'obj' }, { name: 'obj' }\n
\n

Occasionally, a callback is called with a this value other than undefined. For example, the reviver parameter of JSON.parse() and the replacer parameter of JSON.stringify() are both called with this set to the object that the property being parsed/serialized belongs to.

Arrow functions

In arrow functions, this retains the value of the enclosing lexical context's this. In other words, when evaluating an arrow function's body, the language does not create a new this binding.

For example, in global code, this is always globalThis regardless of strictness, because of the global context binding:

\n

js

\n
const globalObject = this;\nconst foo = () => this;\nconsole.log(foo() === globalObject); // true\n
\n

Arrow functions create a closure over the this value of its surrounding scope, which means arrow functions behave as if they are \"auto-bound\" — no matter how it's invoked, this is bound to what it was when the function was created (in the example above, the global object). The same applies to arrow functions created inside other functions: their this remains that of the enclosing lexical context. See example below.

Furthermore, when invoking arrow functions using call(), bind(), or apply(), the thisArg parameter is ignored. You can still pass other arguments using these methods, though.

\n

js

\n
const obj = { name: \"obj\" };\n\n// Attempt to set this using call\nconsole.log(foo.call(obj) === globalObject); // true\n\n// Attempt to set this using bind\nconst boundFoo = foo.bind(obj);\nconsole.log(boundFoo() === globalObject); // true\n
\n

Constructors

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed, no matter which object the constructor function is accessed on. The value of this becomes the value of the new expression unless the constructor returns another non–primitive value.

\n

js

\n
function C() {\n  this.a = 37;\n}\n\nlet o = new C();\nconsole.log(o.a); // 37\n\nfunction C2() {\n  this.a = 37;\n  return { a: 38 };\n}\n\no = new C2();\nconsole.log(o.a); // 38\n
\n

In the second example (C2), because an object was returned during construction, the new object that this was bound to gets discarded. (This essentially makes the statement this.a = 37; dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)

super

When a function is invoked in the super.method() form, the this inside the method function is the same value as the this value around the super.method() call, and is generally not equal to the object that super refers to. This is because super.method is not an object member access like the ones above — it's a special syntax with different binding rules. For examples, see the super reference.

\n

Class context

\n
\n

A class can be split into two contexts: static and instance. Constructors, methods, and instance field initializers (public or private) belong to the instance context. Static methods, static field initializers, and static initialization blocks belong to the static context. The this value is different in each context.

Class constructors are always called with new, so their behavior is the same as function constructors: the this value is the new instance being created. Class methods behave like methods in object literals — the this value is the object that the method was accessed on. If the method is not transferred to another object, this is generally an instance of the class.

Static methods are not properties of this. They are properties of the class itself. Therefore, they are generally accessed on the class, and this is the value of the class (or a subclass). Static initialization blocks are also evaluated with this set to the current class.

Field initializers are also evaluated in the context of the class. Instance fields are evaluated with this set to the instance being constructed. Static fields are evaluated with this set to the current class. This is why arrow functions in field initializers are bound to the instance for instance fields and to the class for static fields.

\n

js

\n
class C {\n  instanceField = this;\n  static staticField = this;\n}\n\nconst c = new C();\nconsole.log(c.instanceField === c); // true\nconsole.log(C.staticField === C); // true\n
\n

Derived class constructors

Unlike base class constructors, derived constructors have no initial this binding. Calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where Base is the base class:

\n

js

\n
this = new Base();\n
\n

Warning: Referring to this before calling super() will throw an error.

Derived classes must not return before calling super(), unless the constructor returns an object (so the this value is overridden) or the class has no constructor at all.

\n

js

\n
class Base {}\nclass Good extends Base {}\nclass AlsoGood extends Base {\n  constructor() {\n    return { a: 5 };\n  }\n}\nclass Bad extends Base {\n  constructor() {}\n}\n\nnew Good();\nnew AlsoGood();\nnew Bad(); // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor\n
\n
\n

Global context

\n
\n

In the global execution context (outside of any functions or classes; may be inside blocks or arrow functions defined in the global scope), the this value depends on what execution context the script runs in. Like callbacks, the this value is determined by the runtime environment (the caller).

At the top level of a script, this refers to globalThis whether in strict mode or not. This is generally the same as the global object — for example, if the source is put inside an HTML <script> element and executed as a script, this === window.

Note: globalThis is generally the same concept as the global object (i.e. adding properties to globalThis makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for globalThis that's unrelated to the global object.

\n

js

\n
// In web browsers, the window object is also the global object:\nconsole.log(this === window); // true\n\nthis.b = \"MDN\";\nconsole.log(window.b); // \"MDN\"\nconsole.log(b); // \"MDN\"\n
\n

If the source is loaded as a module (for HTML, this means adding type=\"module\" to the <script> tag), this is always undefined at the top level.

If the source is executed with eval(), this is the same as the enclosing context for direct eval, or globalThis (as if it's run in a separate global script) for indirect eval.

\n

js

\n
function test() {\n  // Direct eval\n  console.log(eval(\"this\") === this);\n  // Indirect eval, non-strict\n  console.log(eval?.(\"this\") === globalThis);\n  // Indirect eval, strict\n  console.log(eval?.(\"'use strict'; this\") === globalThis);\n}\n\ntest.call({ name: \"obj\" }); // Logs 3 \"true\"\n
\n

Note that some source code, while looking like the global scope, is actually wrapped in a function when executed. For example, Node.js CommonJS modules are wrapped in a function and executed with the this value set to module.exports. Event handler attributes are executed with this set to the element they are attached to.

Object literals don't create a this scope — only functions (methods) defined within the object do. Using this in an object literal inherits the value from the surrounding scope.

\n

js

\n
const obj = {\n  a: this,\n};\n\nconsole.log(obj.a === window); // true\n
\n
\n

Examples

\n

this in function contexts

\n
\n

The value of the this parameter depends on how the function is called, not on how it's defined.

\n

js

\n
// An object can be passed as the first argument to 'call'\n// or 'apply' and 'this' will be bound to it.\nconst obj = { a: \"Custom\" };\n\n// Variables declared with var become properties of 'globalThis'.\nvar a = \"Global\";\n\nfunction whatsThis() {\n  return this.a; // 'this' depends on how the function is called\n}\n\nwhatsThis(); // 'Global'; the 'this' parameter defaults to 'globalThis' in non–strict mode\nobj.whatsThis = whatsThis;\nobj.whatsThis(); // 'Custom'; the 'this' parameter is bound to obj\n
\n

Using call() and apply(), you can pass the value of this as if it's an explicit parameter.

\n

js

\n
function add(c, d) {\n  return this.a + this.b + c + d;\n}\n\nconst o = { a: 1, b: 3 };\n\n// The first argument is bound to the implicit 'this' parameter; the remaining\n// arguments are bound to the named parameters.\nadd.call(o, 5, 7); // 16\n\n// The first argument is bound to the implicit 'this' parameter; the second\n// argument is an array whose members are bound to the named parameters.\nadd.apply(o, [10, 20]); // 34\n
\n
\n

this and object conversion

\n
\n

In non–strict mode, if a function is called with a this value that's not an object, the this value is substituted with an object. null and undefined become globalThis. Primitives like 7 or 'foo' are converted to an object using the related constructor, so the primitive number 7 is converted to a Number wrapper class and the string 'foo' to a String wrapper class.

\n

js

\n
function bar() {\n  console.log(Object.prototype.toString.call(this));\n}\n\nbar.call(7); // [object Number]\nbar.call(\"foo\"); // [object String]\nbar.call(undefined); // [object Window]\n
\n
\n

The bind() method

\n
\n

Calling f.bind(someObject) creates a new function with the same body and scope as f, but the value of this is permanently bound to the first argument of bind, regardless of how the function is being called.

\n

js

\n
function f() {\n  return this.a;\n}\n\nconst g = f.bind({ a: \"azerty\" });\nconsole.log(g()); // azerty\n\nconst h = g.bind({ a: \"yoo\" }); // bind only works once!\nconsole.log(h()); // azerty\n\nconst o = { a: 37, f, g, h };\nconsole.log(o.a, o.f(), o.g(), o.h()); // 37 37 azerty azerty\n
\n
\n

this in arrow functions

\n
\n

Arrow functions create closures over the this value of the enclosing execution context. In the following example, we create obj with a method getThisGetter that returns a function that returns the value of this. The returned function is created as an arrow function, so its this is permanently bound to the this of its enclosing function. The value of this inside getThisGetter can be set in the call, which in turn sets the return value of the returned function. We will assume that getThisGetter is a non-strict function, which means it's contained in a non-strict script and not further nested in a class or strict function.

\n

js

\n
const obj = {\n  getThisGetter() {\n    const getter = () => this;\n    return getter;\n  },\n};\n
\n

We can call getThisGetter as a method of obj, which binds this to obj inside its body. The returned function is assigned to a variable fn. Now, when calling fn, the value of this returned is still the one set by the call to getThisGetter, which is obj. If the returned function was not an arrow function, such calls would cause the this value to be globalThis, because getThisGetter is non-strict.

\n

js

\n
const fn = obj.getThisGetter();\nconsole.log(fn() === obj); // true\n
\n

But be careful if you unbind the method of obj without calling it, because getThisGetter is still a method that has a varying this value. Calling fn2()() in the following example returns globalThis, because it follows the this from fn2(), which is globalThis since it's called without being attached to any object.

\n

js

\n
const fn2 = obj.getThisGetter;\nconsole.log(fn2()() === globalThis); // true in non-strict mode\n
\n

This behavior is very useful when defining callbacks. Usually, each function expression creates its own this binding, which shadows the this value of the upper scope. Now, you can define functions as arrow functions if you don't care about the this value, and only create this bindings where you do (e.g. in class methods). See example with setTimeout().

\n

this with a getter or setter

\n
\n

this in getters and setters is based on which object the property is accessed on, not which object the property is defined on. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

\n

js

\n
function sum() {\n  return this.a + this.b + this.c;\n}\n\nconst o = {\n  a: 1,\n  b: 2,\n  c: 3,\n  get average() {\n    return (this.a + this.b + this.c) / 3;\n  },\n};\n\nObject.defineProperty(o, \"sum\", {\n  get: sum,\n  enumerable: true,\n  configurable: true,\n});\n\nconsole.log(o.average, o.sum); // 2 6\n
\n
\n

this in DOM event handlers

\n
\n

When a function is used as an event handler, its this parameter is bound to the DOM element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener()).

\n

js

\n
// When called as a listener, turns the related element blue\nfunction bluify(e) {\n  // Always true\n  console.log(this === e.currentTarget);\n  // true when currentTarget and target are the same object\n  console.log(this === e.target);\n  this.style.backgroundColor = \"#A5D9F3\";\n}\n\n// Get a list of every element in the document\nconst elements = document.getElementsByTagName(\"*\");\n\n// Add bluify as a click listener so when the\n// element is clicked on, it turns blue\nfor (const element of elements) {\n  element.addEventListener(\"click\", bluify, false);\n}\n
\n
\n

this in inline event handlers

\n
\n

When the code is called from an inline event handler attribute, its this is bound to the DOM element on which the listener is placed:

\n

html

\n
<button onclick=\"alert(this.tagName.toLowerCase());\">Show this</button>\n
\n

The above alert shows button. Note, however, that only the outer scope has its this bound this way:

\n

html

\n
<button onclick=\"alert((function () { return this; })());\">\n  Show inner this\n</button>\n
\n

In this case, the this parameter of the inner function is bound to globalThis (i.e. the default object in non–strict mode where this isn't passed in the call).

\n

Bound methods in classes

\n
\n

Just like with regular functions, the value of this within methods depends on how they are called. Sometimes it is useful to override this behavior so that this within classes always refers to the class instance. To achieve this, bind the class methods in the constructor:

\n

js

\n
class Car {\n  constructor() {\n    // Bind sayBye but not sayHi to show the difference\n    this.sayBye = this.sayBye.bind(this);\n  }\n\n  sayHi() {\n    console.log(`Hello from ${this.name}`);\n  }\n\n  sayBye() {\n    console.log(`Bye from ${this.name}`);\n  }\n\n  get name() {\n    return \"Ferrari\";\n  }\n}\n\nclass Bird {\n  get name() {\n    return \"Tweety\";\n  }\n}\n\nconst car = new Car();\nconst bird = new Bird();\n\n// The value of 'this' in methods depends on their caller\ncar.sayHi(); // Hello from Ferrari\nbird.sayHi = car.sayHi;\nbird.sayHi(); // Hello from Tweety\n\n// For bound methods, 'this' doesn't depend on the caller\nbird.sayBye = car.sayBye;\nbird.sayBye(); // Bye from Ferrari\n
\n

Note: Classes are always in strict mode. Calling methods with an undefined this will throw an error if the method tries to access properties on this.

\n

js

\n
const carSayHi = car.sayHi;\ncarSayHi(); // TypeError because the 'sayHi' method tries to access 'this.name', but 'this' is undefined in strict mode.\n
\n

Note, however, that auto-bound methods suffer from the same problem as using arrow functions for class properties: each instance of the class will have its own copy of the method, which increases memory usage. Only use it where absolutely necessary. You can also mimic the implementation of Intl.NumberFormat.prototype.format(): define the property as a getter that returns a bound function when accessed and saves it, so that the function is only created once and only created when necessary.

\n

this in with statements

\n
\n

Although with statements are deprecated and not available in strict mode, they still serve as an exception to the normal this binding rules. If a function is called within a with statement and that function is a property of the scope object, the this value is bound to the scope object, as if the obj1. prefix exists.

\n

js

\n
const obj1 = {\n  foo() {\n    return this;\n  },\n};\n\nwith (obj1) {\n  console.log(foo() === obj1); // true\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-this-keyword
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
this112149.514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this\n

\n
\n", + "lexical_grammar": "

Lexical grammar

This page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters — in order for the interpreter to understand it, the string has to be parsed to a more structured representation. The initial step of parsing is called lexical analysis, in which the text gets scanned from left to right and is converted into a sequence of individual, atomic input elements. Some input elements are insignificant to the interpreter, and will be stripped after this step — they include white space and comments. The others, including identifiers, keywords, literals, and punctuators (mostly operators), will be used for further syntax analysis. Line terminators and multiline comments are also syntactically insignificant, but they guide the process for automatic semicolons insertion to make certain invalid token sequences become valid.

\n

Format-control characters

\n
\n

Format-control characters have no visual representation but are used to control the interpretation of the text.

Code point Name Abbreviation Description
U+200C Zero width non-joiner <ZWNJ> Placed between characters to prevent being connected into ligatures in certain languages (Wikipedia).
U+200D Zero width joiner <ZWJ> Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages (Wikipedia).
U+FEFF Byte order mark <BOM> Used at the start of the script to mark it as Unicode and the text's byte order (Wikipedia).

In JavaScript source text, <ZWNJ> and <ZWJ> are treated as identifier parts, while <BOM> (also called a zero-width no-break space <ZWNBSP> when not at the start of text) is treated as white space.

\n

White space

\n
\n

White space characters improve the readability of source text and separate tokens from each other. These characters are usually unnecessary for the functionality of the code. Minification tools are often used to remove whitespace in order to reduce the amount of data that needs to be transferred.

Code point Name Abbreviation Description Escape sequence
U+0009 Character tabulation <TAB> Horizontal tabulation \\t
U+000B Line tabulation <VT> Vertical tabulation \\v
U+000C Form feed <FF> Page breaking control character (Wikipedia). \\f
U+0020 Space <SP> Normal space
U+00A0 No-break space <NBSP> Normal space, but no point at which a line may break
U+FEFF Zero-width no-break space <ZWNBSP> When not at the start of a script, the BOM marker is a normal whitespace character.
Others Other Unicode space characters <USP> Characters in the \"Space_Separator\" general category

Note: Of those characters with the \"White_Space\" property but are not in the \"Space_Separator\" general category, U+0009, U+000B, and U+000C are still treated as white space in JavaScript; U+0085 NEXT LINE has no special role; others become the set of line terminators.

Note: Changes to the Unicode standard used by the JavaScript engine may affect programs' behavior. For example, ES2016 upgraded the reference Unicode standard from 5.1 to 8.0.0, which caused U+180E MONGOLIAN VOWEL SEPARATOR to be moved from the \"Space_Separator\" category to the \"Format (Cf)\" category, and made it a non-whitespace. Subsequently, the result of \"\\u180E\".trim().length changed from 0 to 1.

\n

Line terminators

\n
\n

In addition to white space characters, line terminator characters are used to improve the readability of the source text. However, in some cases, line terminators can influence the execution of JavaScript code as there are a few places where they are forbidden. Line terminators also affect the process of automatic semicolon insertion.

Outside the context of lexical grammar, white space and line terminators are often conflated. For example, String.prototype.trim() removes all white space and line terminators from the beginning and end of a string. The \\s character class escape in regular expressions matches all white space and line terminators.

Only the following Unicode code points are treated as line terminators in ECMAScript, other line breaking characters are treated as white space (for example, Next Line, NEL, U+0085 is considered as white space).

Code point Name Abbreviation Description Escape sequence
U+000A Line Feed <LF> New line character in UNIX systems. \\n
U+000D Carriage Return <CR> New line character in Commodore and early Mac systems. \\r
U+2028 Line Separator <LS> Wikipedia
U+2029 Paragraph Separator <PS> Wikipedia
\n

Comments

\n
\n

Comments are used to add hints, notes, suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool.

JavaScript has two long-standing ways to add comments to code: line comments and block comments. In addition, there's a special hashbang comment syntax.

\n

Line comments

\n
\n

The first way is the // comment; this makes all text following it on the same line into a comment. For example:

\n

js

\n
function comment() {\n  // This is a one line JavaScript comment\n  console.log(\"Hello world!\");\n}\ncomment();\n
\n
\n

Block comments

\n
\n

The second way is the /* */ style, which is much more flexible.

For example, you can use it on a single line:

\n

js

\n
function comment() {\n  /* This is a one line JavaScript comment */\n  console.log(\"Hello world!\");\n}\ncomment();\n
\n

You can also make multiple-line comments, like this:

\n

js

\n
function comment() {\n  /* This comment spans multiple lines. Notice\n     that we don't need to end the comment until we're done. */\n  console.log(\"Hello world!\");\n}\ncomment();\n
\n

You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:

\n

js

\n
function comment(x) {\n  console.log(\"Hello \" + x /* insert the value of x */ + \" !\");\n}\ncomment(\"world\");\n
\n

In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:

\n

js

\n
function comment() {\n  /* console.log(\"Hello world!\"); */\n}\ncomment();\n
\n

In this case, the console.log() call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.

Block comments that contain at least one line terminator behave like line terminators in automatic semicolon insertion.

\n

Hashbang comments

\n
\n

There's a special third comment syntax, the hashbang comment. A hashbang comment behaves exactly like a single line-only (//) comment, except that it begins with #! and is only valid at the absolute start of a script or module. Note also that no whitespace of any kind is permitted before the #!. The comment consists of all the characters after #! up to the end of the first line; only one such comment is permitted.

Hashbang comments in JavaScript resemble shebangs in Unix which provide the path to a specific JavaScript interpreter that you want to use to execute the script. Before the hashbang comment became standardized, it had already been de-facto implemented in non-browser hosts like Node.js, where it was stripped from the source text before being passed to the engine. An example is as follows:

\n

js

\n
#!/usr/bin/env node\n\nconsole.log(\"Hello world\");\n
\n

The JavaScript interpreter will treat it as a normal comment — it only has semantic meaning to the shell if the script is directly run in a shell.

Warning: If you want scripts to be runnable directly in a shell environment, encode them in UTF-8 without a BOM. Although a BOM will not cause any problems for code running in a browser — because it's stripped during UTF-8 decoding, before the source text is analyzed — a Unix/Linux shell will not recognize the hashbang if it's preceded by a BOM character.

You must only use the #! comment style to specify a JavaScript interpreter. In all other cases just use a // comment (or multiline comment).

\n

Identifiers

\n
\n

An identifier is used to link a value with a name. Identifiers can be used in various places:

\n

js

\n
const decl = 1; // Variable declaration (may also be `let` or `var`)\nfunction fn() {} // Function declaration\nconst obj = { key: \"value\" }; // Object keys\n// Class declaration\nclass C {\n  #priv = \"value\"; // Private property\n}\nlbl: console.log(1); // Label\n
\n

In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (_), and dollar signs ($). Identifiers are not allowed to start with numbers. However, JavaScript identifiers are not only limited to ASCII — many Unicode code points are allowed as well. Namely, any character in the ID_Start category can start an identifier, while any character in the ID_Continue category can appear after the first character.

Note: If, for some reason, you need to parse some JavaScript source yourself, do not assume all identifiers follow the pattern /[A-Za-z_$][\\w$]*/ (i.e. ASCII-only)! The range of identifiers can be described by the regex /[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/u (excluding unicode escape sequences).

In addition, JavaScript allows using Unicode escape sequences in the form of \\u0000 or \\u{000000} in identifiers, which encode the same string value as the actual Unicode characters. For example, 你好 and \\u4f60\\u597d are the same identifiers:

\n

js

\n
const 你好 = \"Hello\";\nconsole.log(\\u4f60\\u597d); // Hello\n
\n

Not all places accept the full range of identifiers. Certain syntaxes, such as function declarations, function expressions, and variable declarations require using identifiers names that are not reserved words.

\n

js

\n
function import() {} // Illegal: import is a reserved word.\n
\n

Most notably, private properties and object properties allow reserved words.

\n

js

\n
const obj = { import: \"value\" }; // Legal despite `import` being reserved\nclass C {\n  #import = \"value\";\n}\n
\n
\n

Keywords

\n
\n

Keywords are tokens that look like identifiers but have special meanings in JavaScript. For example, the keyword async before a function declaration indicates that the function is asynchronous.

Some keywords are reserved, meaning that they cannot be used as an identifier for variable declarations, function declarations, etc. They are often called reserved words. A list of these reserved words is provided below. Not all keywords are reserved — for example, async can be used as an identifier anywhere. Some keywords are only contextually reserved — for example, await is only reserved within the body of an async function, and let is only reserved in strict mode code, or const and let declarations.

Identifiers are always compared by string value, so escape sequences are interpreted. For example, this is still a syntax error:

\n

js

\n
const els\\u{65} = 1;\n// `els\\u{65}` encodes the same identifier as `else`\n
\n
\n

Reserved words

\n
\n

These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.

The following are only reserved when they are found in strict mode code:

The following are only reserved when they are found in module code or async function bodies:

\n

Future reserved words

\n
\n

The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.

These are always reserved:

The following are only reserved when they are found in strict mode code:

Future reserved words in older standards

The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).

\n

Identifiers with special meanings

\n
\n

A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:

\n

Literals

\n

Note: This section discusses literals that are atomic tokens. Object literals and array literals are expressions that consist of a series of tokens.

Null literal

\n
\n

See also null for more information.

\n

js

\n
null\n
\n
\n

Boolean literal

\n
\n

See also boolean type for more information.

\n

js

\n
true\nfalse\n
\n
\n

Numeric literals

\n
\n

The Number and BigInt types use numeric literals.

Decimal

\n

js

\n
1234567890\n42\n
\n

Decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with 0, whether interpreted as octal or decimal, cause a syntax error in strict mode — so, use the 0o prefix instead.

\n

js

\n
0888 // 888 parsed as decimal\n0777 // parsed as octal, 511 in decimal\n
\n
Exponential

The decimal exponential literal is specified by the following format: beN; where b is a base number (integer or floating), followed by an E or e character (which serves as separator or exponent indicator) and N, which is exponent or power number – a signed integer.

\n

js

\n
0e-5   // 0\n0e+5   // 0\n5e1    // 50\n175e-2 // 1.75\n1e3    // 1000\n1e-3   // 0.001\n1E3    // 1000\n
\n

Binary

Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"B\" (0b or 0B). Any character after the 0b that is not 0 or 1 will terminate the literal sequence.

\n

js

\n
0b10000000000000000000000000000000 // 2147483648\n0b01111111100000000000000000000000 // 2139095040\n0B00000000011111111111111111111111 // 8388607\n
\n

Octal

Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"O\" (0o or 0O). Any character after the 0o that is outside the range (01234567) will terminate the literal sequence.

\n

js

\n
0O755 // 493\n0o644 // 420\n
\n

Hexadecimal

Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"X\" (0x or 0X). Any character after the 0x that is outside the range (0123456789ABCDEF) will terminate the literal sequence.

\n

js

\n
0xFFFFFFFFFFFFFFFFF // 295147905179352830000\n0x123456789ABCDEF   // 81985529216486900\n0XA                 // 10\n
\n

BigInt literal

The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending n to the end of an integer.

\n

js

\n
123456789123456789n     // 123456789123456789\n0o777777777777n         // 68719476735\n0x123456789ABCDEFn      // 81985529216486895\n0b11101001010101010101n // 955733\n
\n

BigInt literals cannot start with 0 to avoid confusion with legacy octal literals.

\n

js

\n
0755n; // SyntaxError: invalid BigInt syntax\n
\n

For octal BigInt numbers, always use zero followed by the letter \"o\" (uppercase or lowercase):

\n

js

\n
0o755n;\n
\n

For more information about BigInt, see also JavaScript data structures.

Numeric separators

To improve readability for numeric literals, underscores (_, U+005F) can be used as separators:

\n

js

\n
1_000_000_000_000\n1_050.95\n0b1010_0001_1000_0101\n0o2_2_5_6\n0xA0_B0_C0\n1_000_000_000_000_000_000_000n\n
\n

Note these limitations:

\n

js

\n
// More than one underscore in a row is not allowed\n100__000; // SyntaxError\n\n// Not allowed at the end of numeric literals\n100_; // SyntaxError\n\n// Can not be used after leading 0\n0_1; // SyntaxError\n
\n
\n

String literals

\n
\n

A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these code points:

Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.

\n

js

\n
'foo'\n\"bar\"\n
\n

The following subsections describe various escape sequences (\\ followed by one or more characters) available in string literals. Any escape sequence not listed below becomes an \"identity escape\" that becomes the code point itself. For example, \\z is the same as z. There's a deprecated octal escape sequence syntax described in the Deprecated and obsolete features page. Many of these escape sequences are also valid in regular expressions — see Character escape.

Escape sequences

Special characters can be encoded using escape sequences:

Escape sequence Unicode code point
\\0 null character (U+0000 NULL)
\\' single quote (U+0027 APOSTROPHE)
\\\" double quote (U+0022 QUOTATION MARK)
\\\\ backslash (U+005C REVERSE SOLIDUS)
\\n newline (U+000A LINE FEED; LF)
\\r carriage return (U+000D CARRIAGE RETURN; CR)
\\v vertical tab (U+000B LINE TABULATION)
\\t tab (U+0009 CHARACTER TABULATION)
\\b backspace (U+0008 BACKSPACE)
\\f form feed (U+000C FORM FEED)
\n\\ followed by a line terminator\n empty string

The last escape sequence, \\ followed by a line terminator, is useful for splitting a string literal across multiple lines without changing its meaning.

\n

js

\n
const longString =\n  \"This is a very long string which needs \\\nto wrap across multiple lines because \\\notherwise my code is unreadable.\";\n
\n

Make sure there is no space or any other character after the backslash (except for a line break), otherwise it will not work. If the next line is indented, the extra spaces will also be present in the string's value.

You can also use the + operator to append multiple strings together, like this:

\n

js

\n
const longString =\n  \"This is a very long string which needs \" +\n  \"to wrap across multiple lines because \" +\n  \"otherwise my code is unreadable.\";\n
\n

Both of the above methods result in identical strings.

Hexadecimal escape sequences

Hexadecimal escape sequences consist of \\x followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.

\n

js

\n
\"\\xA9\"; // \"©\"\n
\n

Unicode escape sequences

A Unicode escape sequence consists of exactly four hexadecimal digits following \\u. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.

See also String.fromCharCode() and String.prototype.charCodeAt().

\n

js

\n
\"\\u00A9\"; // \"©\" (U+A9)\n
\n

Unicode code point escapes

A Unicode code point escape consists of \\u{, followed by a code point in hexadecimal base, followed by }. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair.

See also String.fromCodePoint() and String.prototype.codePointAt().

\n

js

\n
\"\\u{2F804}\"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)\n\n// the same character represented as a surrogate pair\n\"\\uD87E\\uDC04\";\n
\n
\n

Regular expression literals

\n
\n

Regular expression literals are enclosed by two forward slashes (/). The lexer consumes all characters up to the next unescaped forward slash or the end of the line, unless the forward slash appears within a character class ([]). Some characters (namely, those that are identifier parts) can appear after the closing slash, denoting flags.

The lexical grammar is very lenient: not all regular expression literals that get identified as one token are valid regular expressions.

See also RegExp for more information.

\n

js

\n
/ab+c/g\n/[/]/\n
\n

A regular expression literal cannot start with two forward slashes (//), because that would be a line comment. To specify an empty regular expression, use /(?:)/.

\n

Template literals

\n
\n

One template literal consists of several tokens: `xxx${ (template head), }xxx${ (template middle), and }xxx` (template tail) are individual tokens, while any expression may come between them.

See also template literals for more information.

\n

js

\n
`string text`\n\n`string text line 1\n string text line 2`\n\n`string text ${expression} string text`\n\ntag`string text ${expression} string text`\n
\n
\n

Automatic semicolon insertion

\n
\n

Some JavaScript statements' syntax definitions require semicolons (;) at the end. They include:

However, to make the language more approachable and convenient, JavaScript is able to automatically insert semicolons when consuming the token stream, so that some invalid token sequences can be \"fixed\" to valid syntax. This step happens after the program text has been parsed to tokens according to the lexical grammar. There are three cases when semicolons are automatically inserted:

1. When a token not allowed by the grammar is encountered, and it's separated from the previous token by at least one line terminator (including a block comment that includes at least one line terminator), or the token is \"}\", then a semicolon is inserted before the token.

\n

js

\n
{ 1\n2 } 3\n\n// is transformed by ASI into:\n\n{ 1\n;2 ;} 3;\n\n// Which is valid grammar encoding three statements,\n// each consisting of a number literal\n
\n

The ending \")\" of do...while is taken care of as a special case by this rule as well.

\n

js

\n
do {\n  // ...\n} while (condition) /* ; */ // ASI here\nconst a = 1\n
\n

However, semicolons are not inserted if the semicolon would then become the separator in the for statement's head.

\n

js

\n
for (\n  let a = 1 // No ASI here\n  a < 10 // No ASI here\n  a++\n) {}\n
\n

Semicolons are also never inserted as empty statements. For example, in the code below, if a semicolon is inserted after \")\", then the code would be valid, with an empty statement as the if body and the const declaration being a separate statement. However, because automatically inserted semicolons cannot become empty statements, this causes a declaration to become the body of the if statement, which is not valid.

\n

js

\n
if (Math.random() > 0.5)\nconst x = 1 // SyntaxError: Unexpected token 'const'\n
\n

2. When the end of the input stream of tokens is reached, and the parser is unable to parse the single input stream as a complete program, a semicolon is inserted at the end.

\n

js

\n
const a = 1 /* ; */ // ASI here\n
\n

This rule is a complement to the previous rule, specifically for the case where there's no \"offending token\" but the end of input stream.

3. When the grammar forbids line terminators in some place but a line terminator is found, a semicolon is inserted. These places include:

Here ++ is not treated as a postfix operator applying to variable b, because a line terminator occurs between b and ++.

\n

js

\n
a = b\n++c\n\n// is transformed by ASI into\n\na = b;\n++c;\n
\n

Here, the return statement returns undefined, and the a + b becomes an unreachable statement.

\n

js

\n
return\na + b\n\n// is transformed by ASI into\n\nreturn;\na + b;\n
\n

Note that ASI would only be triggered if a line break separates tokens that would otherwise produce invalid syntax. If the next token can be parsed as part of a valid structure, semicolons would not be inserted. For example:

\n

js

\n
const a = 1\n(1).toString()\n\nconst b = 1\n[1, 2, 3].forEach(console.log)\n
\n

Because () can be seen as a function call, it would usually not trigger ASI. Similarly, [] may be a member access. The code above is equivalent to:

\n

js

\n
const a = 1(1).toString();\n\nconst b = 1[1, 2, 3].forEach(console.log);\n
\n

This happens to be valid syntax. 1[1, 2, 3] is a property accessor with a comma-joined expression. Therefore, you would get errors like \"1 is not a function\" and \"Cannot read properties of undefined (reading 'forEach')\" when running the code.

Within classes, class fields and generator methods can be a pitfall as well.

\n

js

\n
class A {\n  a = 1\n  *gen() {}\n}\n
\n

It is seen as:

\n

js

\n
class A {\n  a = 1 * gen() {}\n}\n
\n

And therefore will be a syntax error around {.

There are the following rules-of-thumb for dealing with ASI, if you want to enforce semicolon-less style:

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
array_literals11214414.418410.111.01.00.10.0
binary_numeric_literals411225No2894141252894.01.04.0.0
boolean_literals11213314.418410.111.01.00.10.0
decimal_numeric_literals11213314.418410.111.01.00.10.0
hashbang_comments747967No6213.17474675313.411.01.00.10.0
hexadecimal_escape_sequences11214414.418410.111.01.00.10.0
hexadecimal_numeric_literals11213314.418410.111.01.00.10.0
null_literal11213314.418410.111.01.00.10.0
numeric_separators757970No6213757579No1311.01.212.5.0
octal_numeric_literals411225No2894141252894.01.04.0.0
regular_expression_literals11214514.418410.111.01.00.10.0
shorthand_object_literals431233No3094343333094.01.04.0.0
string_literals11213314.418410.111.01.00.10.0
template_literals411234No2894141342894.01.04.0.0
trailing_commas112199.514.418410.111.01.00.10.0
unicode_escape_sequences11214414.418410.111.01.00.10.0
unicode_point_escapes441240No3194444403294.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar\n

\n
\n", + "operators/optional_chaining": "

Optional chaining (?.)

The ?. operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

\n

Try it

\n

Syntax

\n
\n

js

\n
obj.val?.prop\nobj.val?.[expr]\nobj.func?.(args)\n
\n

Description

\n
\n

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

\n

js

\n
const nestedProp = obj.first && obj.first.second;\n
\n

The value of obj.first is confirmed to be non-null (and non-undefined) before accessing the value of obj.first.second. This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first.

This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined, such as 0, it would still short-circuit and make nestedProp become 0, which may not be desirable.

With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second:

\n

js

\n
const nestedProp = obj.first?.second;\n
\n

By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. If obj.first is null or undefined, the expression automatically short-circuits, returning undefined.

This is equivalent to the following, except that the temporary variable is in fact not created:

\n

js

\n
const temp = obj.first;\nconst nestedProp =\n  temp === null || temp === undefined ? undefined : temp.second;\n
\n

Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined.

\n

js

\n
undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined\n
\n
\n

Optional chaining with function calls

\n
\n

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

\n

js

\n
const result = someInterface.customMethod?.();\n
\n

However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception \"someInterface.customMethod is not a function\".

Note: If someInterface itself is null or undefined, a TypeError exception will still be raised (\"someInterface is null\"). If you expect that someInterface itself may be null or undefined, you have to use ?. at this position as well: someInterface?.customMethod?.().

eval?.() is the shortest way to enter indirect eval mode.

\n

Optional chaining with expressions

\n
\n

You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name:

\n

js

\n
const nestedProp = obj?.[\"prop\" + \"Name\"];\n
\n

This is particularly useful for arrays, since array indices must be accessed with square brackets.

\n

js

\n
function printMagicIndex(arr) {\n  console.log(arr?.[42]);\n}\n\nprintMagicIndex([0, 1, 2, 3, 4, 5]); // undefined\nprintMagicIndex(); // undefined; if not using ?., this would throw\n
\n
\n

Optional chaining not valid on the left-hand side of an assignment

\n
\n

It is invalid to try to assign to the result of an optional chaining expression:

\n

js

\n
const object = {};\nobject?.property = 1; // SyntaxError: Invalid left-hand side in assignment\n
\n
\n

Short-circuiting

\n
\n

When using optional chaining with expressions, if the left operand is null or undefined, the expression will not be evaluated. For instance:

\n

js

\n
const potentiallyNullObj = null;\nlet x = 0;\nconst prop = potentiallyNullObj?.[x++];\n\nconsole.log(x); // 0 as x was not incremented\n
\n

Subsequent property accesses will not be evaluated either.

\n

js

\n
const potentiallyNullObj = null;\nconst prop = potentiallyNullObj?.a.b;\n// This does not throw, because evaluation has already stopped at\n// the first optional chain\n
\n

This is equivalent to:

\n

js

\n
const potentiallyNullObj = null;\nconst prop =\n  potentiallyNullObj === null || potentiallyNullObj === undefined\n    ? undefined\n    : potentiallyNullObj.a.b;\n
\n

However, this short-circuiting behavior only happens along one continuous \"chain\" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated.

\n

js

\n
const potentiallyNullObj = null;\nconst prop = (potentiallyNullObj?.a).b;\n// TypeError: Cannot read properties of undefined (reading 'b')\n
\n

This is equivalent to:

\n

js

\n
const potentiallyNullObj = null;\nconst temp = potentiallyNullObj?.a;\nconst prop = temp.b;\n
\n

Except the temp variable isn't created.

\n

Examples

\n

Basic example

\n
\n

This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined.

\n

js

\n
const myMap = new Map();\nmyMap.set(\"foo\", { name: \"baz\", desc: \"inga\" });\n\nconst nameBar = myMap.get(\"bar\")?.name;\n
\n
\n

Dealing with optional callbacks or event handlers

\n
\n

If you use callbacks or fetch methods from an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?., you can avoid this extra test:

\n

js

\n
// Code written without optional chaining\nfunction doSomething(onContent, onError) {\n  try {\n    // Do something with the data\n  } catch (err) {\n    // Testing if onError really exists\n    if (onError) {\n      onError(err.message);\n    }\n  }\n}\n
\n
\n

js

\n
// Using optional chaining with function calls\nfunction doSomething(onContent, onError) {\n  try {\n    // Do something with the data\n  } catch (err) {\n    onError?.(err.message); // No exception if onError is undefined\n  }\n}\n
\n
\n

Stacking the optional chaining operator

\n
\n

With nested structures, it is possible to use optional chaining multiple times:

\n

js

\n
const customer = {\n  name: \"Carl\",\n  details: {\n    age: 82,\n    location: \"Paradise Falls\", // Detailed address is unknown\n  },\n};\nconst customerCity = customer.details?.address?.city;\n\n// This also works with optional chaining function call\nconst customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined\n
\n
\n

Combining with the nullish coalescing operator

\n
\n

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

\n

js

\n
function printCustomerCity(customer) {\n  const customerCity = customer?.city ?? \"Unknown city\";\n  console.log(customerCity);\n}\n\nprintCustomerCity({\n  name: \"Nathan\",\n  city: \"Paris\",\n}); // \"Paris\"\nprintCustomerCity({\n  name: \"Carl\",\n  details: { age: 82 },\n}); // \"Unknown city\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-OptionalExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Optional_chaining808074No6713.18080795713.413.01.014.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\n

\n
\n", + "operators/new": "

new

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

\n

Try it

\n

Syntax

\n
\n

js

\n
new constructor\nnew constructor()\nnew constructor(arg1)\nnew constructor(arg1, arg2)\nnew constructor(arg1, arg2, /* …, */ argN)\n
\n

Parameters

\n
constructor

A class or function that specifies the type of the object instance.

\narg1, arg2, …, argN\n

A list of values that the constructor will be called with. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.

Description

\n
\n

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things:

  1. Creates a blank, plain JavaScript object. For convenience, let's call it newInstance.
  2. Points newInstance's [[Prototype]] to the constructor function's prototype property, if the prototype is an Object. Otherwise, newInstance stays as a plain object with Object.prototype as its [[Prototype]].

    Note: Properties/objects added to the constructor function's prototype property are therefore accessible to all instances created from the constructor function.

  3. Executes the constructor function with the given arguments, binding newInstance as the this context (i.e. all references to this in the constructor function now refer to newInstance).
  4. If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, newInstance is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)

Classes can only be instantiated with the new operator — attempting to call a class without new will throw a TypeError.

Creating an object with a user-defined constructor function requires two steps:

  1. Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object Foo might look like this:
    \n

    js

    \n
    function Foo(bar1, bar2) {\n  this.bar1 = bar1;\n  this.bar2 = bar2;\n}\n
    \n
  2. Create an instance of the object with new.
    \n

    js

    \n
    const myFoo = new Foo(\"Bar 1\", 2021);\n
    \n

Note: An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object instance. For example, the statement car1.color = \"black\" adds a property color to car1, and assigns it a value of \"black\".

However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor's prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value \"original color\" to all objects of type Car, and then overwrites that value with the string \"black\" only in the instance object car1. For more information, see prototype.

\n

js

\n
function Car() {}\nconst car1 = new Car();\nconst car2 = new Car();\n\nconsole.log(car1.color); // undefined\n\nCar.prototype.color = \"original color\";\nconsole.log(car1.color); // 'original color'\n\ncar1.color = \"black\";\nconsole.log(car1.color); // 'black'\n\nconsole.log(Object.getPrototypeOf(car1).color); // 'original color'\nconsole.log(Object.getPrototypeOf(car2).color); // 'original color'\nconsole.log(car1.color); // 'black'\nconsole.log(car2.color); // 'original color'\n
\n

Note: While the constructor function can be invoked like any regular function (i.e. without the new operator), in this case a new object is not created and the value of this is also different.

A function can know whether it is invoked with new by checking new.target. new.target is only undefined when the function is invoked without new. For example, you can have a function that behaves differently when it's called versus when it's constructed:

\n

js

\n
function Car(color) {\n  if (!new.target) {\n    // Called as function.\n    return `${color} car`;\n  }\n  // Called with new.\n  this.color = color;\n}\n\nconst a = Car(\"red\"); // a is \"red car\"\nconst b = new Car(\"red\"); // b is `Car { color: \"red\" }`\n
\n

Prior to ES6, which introduced classes, most JavaScript built-ins are both callable and constructible, although many of them exhibit different behaviors. To name a few:

After ES6, the language is stricter about which are constructors and which are functions. For example:

\n

Examples

\n

Object type and object instance

\n
\n

Suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

\n

js

\n
function Car(make, model, year) {\n  this.make = make;\n  this.model = model;\n  this.year = year;\n}\n
\n

Now you can create an object called myCar as follows:

\n

js

\n
const myCar = new Car(\"Eagle\", \"Talon TSi\", 1993);\n
\n

This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string \"Eagle\", myCar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example:

\n

js

\n
const kensCar = new Car(\"Nissan\", \"300ZX\", 1992);\n
\n
\n

Object property that is itself another object

\n
\n

Suppose you define an object called Person as follows:

\n

js

\n
function Person(name, age, sex) {\n  this.name = name;\n  this.age = age;\n  this.sex = sex;\n}\n
\n

And then instantiate two new Person objects as follows:

\n

js

\n
const rand = new Person(\"Rand McNally\", 33, \"M\");\nconst ken = new Person(\"Ken Jones\", 39, \"M\");\n
\n

Then you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

\n

js

\n
function Car(make, model, year, owner) {\n  this.make = make;\n  this.model = model;\n  this.year = year;\n  this.owner = owner;\n}\n
\n

To instantiate the new objects, you then use the following:

\n

js

\n
const car1 = new Car(\"Eagle\", \"Talon TSi\", 1993, rand);\nconst car2 = new Car(\"Nissan\", \"300ZX\", 1992, ken);\n
\n

Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2, you can access the following property:

\n

js

\n
car2.owner.name;\n
\n
\n

Using new with classes

\n
\n

js

\n
class Person {\n  constructor(name) {\n    this.name = name;\n  }\n  greet() {\n    console.log(`Hello, my name is ${this.name}`);\n  }\n}\n\nconst p = new Person(\"Caroline\");\np.greet(); // Hello, my name is Caroline\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-new-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
new11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new\n

\n
\n", + "operators/new.target": "

new.target

The new.target meta-property lets you detect whether a function or constructor was called using the new operator. In constructors and functions invoked using the new operator, new.target returns a reference to the constructor or function that new was called upon. In normal function calls, new.target is undefined.

\n

Try it

\n

Syntax

\n
\n

js

\n
new.target\n
\n

Value

\n
\n

new.target is guaranteed to be a constructable function value or undefined.

\n

Description

\n
\n

The new.target syntax consists of the keyword new, a dot, and the identifier target. Because new is a reserved word, not an identifier, this is not a property accessor, but a special expression syntax.

The new.target meta-property is available in all function/class bodies; using new.target outside of functions or classes is a syntax error.

\n

Examples

\n

new.target in function calls

\n
\n

In normal function calls (as opposed to constructor function calls), new.target is undefined. This lets you detect whether a function was called with new as a constructor.

\n

js

\n
function Foo() {\n  if (!new.target) {\n    throw new Error(\"Foo() must be called with new\");\n  }\n  console.log(\"Foo instantiated with new\");\n}\n\nnew Foo(); // Logs \"Foo instantiated with new\"\nFoo(); // Throws \"Foo() must be called with new\"\n
\n
\n

new.target in constructors

\n
\n

In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and was delegated from a child constructor. new.target points to the class that new was called upon. For example, when b was initialized using new B(), the name of B was printed; and similarly, in case of a, the name of class A was printed.

\n

js

\n
class A {\n  constructor() {\n    console.log(new.target.name);\n  }\n}\n\nclass B extends A {\n  constructor() {\n    super();\n  }\n}\n\nconst a = new A(); // Logs \"A\"\nconst b = new B(); // Logs \"B\"\n
\n
\n

new.target using Reflect.construct()

\n
\n

Before Reflect.construct() or classes, it was common to implement inheritance by passing the value of this, and letting the base constructor mutate it.

\n

js

\n
function Base() {\n  this.name = \"Base\";\n}\n\nfunction Extended() {\n  // Only way to make the Base() constructor work on the existing\n  // `this` value instead of a new object that `new` creates.\n  Base.call(this);\n  this.otherProperty = \"Extended\";\n}\n\nObject.setPrototypeOf(Extended.prototype, Base.prototype);\nObject.setPrototypeOf(Extended, Base);\n\nconsole.log(new Extended()); // Extended { name: 'Base', otherProperty: 'Extended' }\n
\n

However, call() and apply() actually call the function instead of constructing it, so new.target has value undefined. This means that if Base() checks whether it's constructed with new, an error will be thrown, or it may behave in other unexpected ways. For example, you can't extend Map this way, because the Map() constructor cannot be called without new.

All built-in constructors directly construct the entire prototype chain of the new instance by reading new.target.prototype. So to make sure that (1) Base is constructed with new, and (2) new.target points to the subclass instead of Base itself, we need to use Reflect.construct().

\n

js

\n
function BetterMap(entries) {\n  // Call the base class constructor, but setting `new.target` to the subclass,\n  // so that the instance created has the correct prototype chain.\n  return Reflect.construct(Map, [entries], BetterMap);\n}\n\nBetterMap.prototype.upsert = function (key, actions) {\n  if (this.has(key)) {\n    this.set(key, actions.update(this.get(key)));\n  } else {\n    this.set(key, actions.insert());\n  }\n};\n\nObject.setPrototypeOf(BetterMap.prototype, Map.prototype);\nObject.setPrototypeOf(BetterMap, Map);\n\nconst map = new BetterMap([[\"a\", 1]]);\nmap.upsert(\"a\", {\n  update: (value) => value + 1,\n  insert: () => 1,\n});\nconsole.log(map.get(\"a\")); // 2\n
\n

Note: In fact, due to the lack of Reflect.construct(), it is not possible to properly subclass built-ins (like Error subclassing) when transpiling to pre-ES6 code.

However, if you are writing ES6 code, prefer using classes and extends instead, as it's more readable and less error-prone.

\n

js

\n
class BetterMap extends Map {\n  // The constructor is omitted because it's just the default one\n\n  upsert(key, actions) {\n    if (this.has(key)) {\n      this.set(key, actions.update(this.get(key)));\n    } else {\n      this.set(key, actions.insert());\n    }\n  }\n}\n\nconst map = new BetterMap([[\"a\", 1]]);\nmap.upsert(\"a\", {\n  update: (value) => value + 1,\n  insert: () => 1,\n});\nconsole.log(map.get(\"a\")); // 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-built-in-function-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
new.target461341No331146464133115.01.05.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target\n

\n
\n", + "operators/import.meta": "

import.meta

The import.meta meta-property exposes context-specific metadata to a JavaScript module. It contains information about the module, such as the module's URL.

\n

Syntax

\n
\n

js

\n
import.meta\n
\n

Value

\n
\n

The import.meta object is created by the host environment, as an extensible null-prototype object where all properties are writable, configurable, and enumerable. The spec doesn't specify any properties to be defined on it, but hosts usually implement the following properties:

url

The full URL to the module, includes query parameters and/or hash (following the ? or #). In browsers, this is either the URL from which the script was obtained (for external scripts), or the URL of the containing document (for inline scripts). In Node.js, this is the file path (including the file:// protocol).

resolve

Resolves a module specifier to a URL using the current module's URL as base.

\n

Description

\n
\n

The import.meta syntax consists of the keyword import, a dot, and the identifier meta. Because import is a reserved word, not an identifier, this is not a property accessor, but a special expression syntax.

The import.meta meta-property is available in JavaScript modules; using import.meta outside of a module (including direct eval() within a module) is a syntax error.

\n

Examples

\n

Passing query parameters

\n
\n

Using query parameters in the import specifier allows module-specific argument passing, which may be complementary to reading parameters from the application-wide window.location (or on Node.js, through process.argv). For example, with the following HTML:

\n

html

\n
<script type=\"module\">\n  import \"./index.mjs?someURLInfo=5\";\n</script>\n
\n

The index.mjs module is able to retrieve the someURLInfo parameter through import.meta:

\n

js

\n
// index.mjs\nnew URL(import.meta.url).searchParams.get(\"someURLInfo\"); // 5\n
\n

The same applies when a module imports another:

\n

js

\n
// index.mjs\nimport \"./index2.mjs?someURLInfo=5\";\n\n// index2.mjs\nnew URL(import.meta.url).searchParams.get(\"someURLInfo\"); // 5\n
\n

The ES module implementation in Node.js supports resolving module specifiers containing query parameters (or the hash), as in the latter example. However, you cannot use queries or hashes when the module is specified through the CLI command (like node index.mjs?someURLInfo=5), because the CLI entrypoint uses a more CommonJS-like resolution mode, treating the path as a file path rather than a URL. To pass parameters to the entrypoint module, use CLI arguments and read them through process.argv instead (like node index.mjs --someURLInfo=5).

\n

Resolving a file relative to the current one

\n
\n

In Node.js CommonJS modules, there's a __dirname variable that contains the absolute path to the folder containing current module, which is useful for resolving relative paths. However, ES modules cannot have contextual variables except for import.meta. Therefore, to resolve a relative file you can use import.meta.url. Note that this uses URLs rather than filesystem paths.

Before (CommonJS):

\n

js

\n
const fs = require(\"fs/promises\");\nconst path = require(\"path\");\n\nconst filePath = path.join(__dirname, \"someFile.txt\");\nfs.readFile(filePath, \"utf8\").then(console.log);\n
\n

After (ES modules):

\n

js

\n
import fs from \"node:fs/promises\";\n\nconst fileURL = new URL(\"./someFile.txt\", import.meta.url);\nfs.readFile(fileURL, \"utf8\").then(console.log);\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# prod-ImportMeta
HTML Standard
# hostgetimportmetaproperties
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
import.meta647962No5111.164646247129.01.010.4.0
resolve105105106No9116.41051051067216.420.01.24
20.6.0Returns a URL object instead of a string.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta\n

\n
\n", + "operators/super": "

super

\n

The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals. The super(...args) expression is valid in class constructors.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
super([arguments]) // calls the parent constructor.\nsuper.propertyOnParent\nsuper[expression]\n
\n

Description

\n
\n

The super keyword can be used in two ways: as a \"function call\" (super(...args)), or as a \"property lookup\" (super.prop and super[expr]).

Note: super is a keyword and these are special syntactic constructs. super is not a variable that points to the prototype object. Attempting to read super itself is a SyntaxError.

\n

js

\n
const child = {\n  myParent() {\n    console.log(super); // SyntaxError: 'super' keyword unexpected here\n  },\n};\n
\n

In the constructor body of a derived class (with extends), the super keyword may appear as a \"function call\" (super(...args)), which must be called before the this keyword is used, and before the constructor returns. It calls the parent class's constructor and binds the parent class's public fields, after which the derived class's constructor can further access and modify this.

The \"property lookup\" form can be used to access methods and properties of an object literal's or class's [[Prototype]]. Within a class's body, the reference of super can be either the superclass's constructor itself, or the constructor's prototype, depending on whether the execution context is instance creation or class initialization. See the Examples section for more details.

Note that the reference of super is determined by the class or object literal super was declared in, not the object the method is called on. Therefore, unbinding or re-binding a method doesn't change the reference of super in it (although they do change the reference of this). You can see super as a variable in the class or object literal scope, which the methods create a closure over. (But also beware that it's not actually a variable, as explained above.)

When setting properties through super, the property is set on this instead.

\n

Examples

\n

Using super in classes

\n
\n

This code snippet is taken from the classes sample (live demo). Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square.

\n

js

\n
class Rectangle {\n  constructor(height, width) {\n    this.name = \"Rectangle\";\n    this.height = height;\n    this.width = width;\n  }\n  sayName() {\n    console.log(`Hi, I am a ${this.name}.`);\n  }\n  get area() {\n    return this.height * this.width;\n  }\n  set area(value) {\n    this._area = value;\n  }\n}\n\nclass Square extends Rectangle {\n  constructor(length) {\n    // Here, it calls the parent class's constructor with lengths\n    // provided for the Rectangle's width and height\n    super(length, length);\n\n    // Note: In derived classes, super() must be called before you\n    // can use 'this'. Moving this to the top causes a ReferenceError.\n    this.name = \"Square\";\n  }\n}\n
\n
\n

Super-calling static methods

\n
\n

You are also able to call super on static methods.

\n

js

\n
class Rectangle {\n  static logNbSides() {\n    return \"I have 4 sides\";\n  }\n}\n\nclass Square extends Rectangle {\n  static logDescription() {\n    return `${super.logNbSides()} which are all equal`;\n  }\n}\nSquare.logDescription(); // 'I have 4 sides which are all equal'\n
\n
\n

Accessing super in class field declaration

\n
\n

super can also be accessed during class field initialization. The reference of super depends on whether the current field is an instance field or a static field.

\n

js

\n
class Base {\n  static baseStaticField = 90;\n  baseMethod() {\n    return 10;\n  }\n}\n\nclass Extended extends Base {\n  extendedField = super.baseMethod(); // 10\n  static extendedStaticField = super.baseStaticField; // 90\n}\n
\n

Note that instance fields are set on the instance instead of the constructor's prototype, so you can't use super to access the instance field of a superclass.

\n

js

\n
class Base {\n  baseField = 10;\n}\n\nclass Extended extends Base {\n  extendedField = super.baseField; // undefined\n}\n
\n

Here, extendedField is undefined instead of 10, because baseField is defined as an own property of the Base instance, instead of Base.prototype. super, in this context, only looks up properties on Base.prototype, because that's the [[Prototype]] of Extended.prototype.

\n

Deleting super properties will throw an error

\n
\n

You cannot use the delete operator and super.prop or super[expr] to delete a parent class' property — it will throw a ReferenceError.

\n

js

\n
class Base {\n  foo() {}\n}\nclass Derived extends Base {\n  delete() {\n    delete super.foo; // this is bad\n  }\n}\n\nnew Derived().delete(); // ReferenceError: invalid delete involving 'super'.\n
\n
\n

Using super.prop in object literals

\n
\n

Super can also be used in the object initializer notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of Object.setPrototypeOf() with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1.

\n

js

\n
const obj1 = {\n  method1() {\n    console.log(\"method 1\");\n  },\n};\n\nconst obj2 = {\n  method2() {\n    super.method1();\n  },\n};\n\nObject.setPrototypeOf(obj2, obj1);\nobj2.method2(); // Logs \"method 1\"\n
\n
\n

Methods that read super.prop do not behave differently when bound to other objects

\n
\n

Accessing super.x behaves like Reflect.get(Object.getPrototypeOf(objectLiteral), \"x\", this), which means the property is always seeked on the object literal/class declaration's prototype, and unbinding and re-binding a method won't change the reference of super.

\n

js

\n
class Base {\n  baseGetX() {\n    return 1;\n  }\n}\nclass Extended extends Base {\n  getX() {\n    return super.baseGetX();\n  }\n}\n\nconst e = new Extended();\nconsole.log(e.getX()); // 1\nconst { getX } = e;\nconsole.log(getX()); // 1\n
\n

The same happens in object literals.

\n

js

\n
const parent1 = { prop: 1 };\nconst parent2 = { prop: 2 };\n\nconst child = {\n  myParent() {\n    console.log(super.prop);\n  },\n};\n\nObject.setPrototypeOf(child, parent1);\nchild.myParent(); // Logs \"1\"\n\nconst myParent = child.myParent;\nmyParent(); // Still logs \"1\"\n\nconst anotherChild = { __proto__: parent2, myParent };\nanotherChild.myParent(); // Still logs \"1\"\n
\n

Only resetting the entire inheritance chain will change the reference of super.

\n

js

\n
class Base {\n  baseGetX() {\n    return 1;\n  }\n  static staticBaseGetX() {\n    return 3;\n  }\n}\nclass AnotherBase {\n  baseGetX() {\n    return 2;\n  }\n  static staticBaseGetX() {\n    return 4;\n  }\n}\nclass Extended extends Base {\n  getX() {\n    return super.baseGetX();\n  }\n  static staticGetX() {\n    return super.staticBaseGetX();\n  }\n}\n\nconst e = new Extended();\n// Reset instance inheritance\nObject.setPrototypeOf(Extended.prototype, AnotherBase.prototype);\nconsole.log(e.getX()); // Logs \"2\" instead of \"1\", because the prototype chain has changed\nconsole.log(Extended.staticGetX()); // Still logs \"3\", because we haven't modified the static part yet\n// Reset static inheritance\nObject.setPrototypeOf(Extended, AnotherBase);\nconsole.log(Extended.staticGetX()); // Now logs \"4\"\n
\n
\n

Calling methods from super

\n
\n

When calling super.prop as a function, the this value inside the prop function is the current this, not the object that super points to. For example, the super.getName() call logs \"Extended\", despite the code looking like it's equivalent to Base.getName().

\n

js

\n
class Base {\n  static getName() {\n    console.log(this.name);\n  }\n}\n\nclass Extended extends Base {\n  static getName() {\n    super.getName();\n  }\n}\n\nExtended.getName(); // Logs \"Extended\"\n
\n

This is especially important when interacting with static private properties.

\n

Setting super.prop sets the property on this instead

\n
\n

Setting properties of super, such as super.x = 1, behaves like Reflect.set(Object.getPrototypeOf(objectLiteral), \"x\", 1, this). This is one of the cases where understanding super as simply \"reference of the prototype object\" falls short, because it actually sets the property on this instead.

\n

js

\n
class A {}\nclass B extends A {\n  setX() {\n    super.x = 1;\n  }\n}\n\nconst b = new B();\nb.setX();\nconsole.log(b); // B { x: 1 }\nconsole.log(Object.hasOwn(b, \"x\")); // true\n
\n

super.x = 1 will look for the property descriptor of x on A.prototype (and invoke the setters defined there), but the this value will be set to this, which is b in this context. You can read Reflect.set for more details on the case when target and receiver differ.

This means that while methods that get super.prop are usually not susceptible to changes in the this context, those that set super.prop are.

\n

js

\n
/* Reusing same declarations as above */\n\nconst b2 = new B();\nb2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'\n
\n

However, super.x = 1 still consults the property descriptor of the prototype object, which means you cannot rewrite non-writable properties, and setters will be invoked.

\n

js

\n
class X {\n  constructor() {\n    // Create a non-writable property\n    Object.defineProperty(this, \"prop\", {\n      configurable: true,\n      writable: false,\n      value: 1,\n    });\n  }\n}\n\nclass Y extends X {\n  constructor() {\n    super();\n  }\n  foo() {\n    super.prop = 2; // Cannot overwrite the value.\n  }\n}\n\nconst y = new Y();\ny.foo(); // TypeError: \"prop\" is read-only\nconsole.log(y.prop); // 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-super-keyword
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
super421345No2974242452974.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super\n

\n
\n", + "operators/import": "

import()

\n

The import() syntax, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.

Unlike the declaration-style counterpart, dynamic imports are only evaluated when needed, and permit greater syntactic flexibility.

\n
\n

Syntax

\n
\n
\n

js

\n
import(moduleName)\n
\n

The import() call is a syntax that closely resembles a function call, but import itself is a keyword, not a function. You cannot alias it like const myImport = import, which will throw a SyntaxError.

\n

Parameters

\n
moduleName

The module to import from. The evaluation of the specifier is host-specified, but always follows the same algorithm as static import declarations.

Return value

\n
\n

Returns a promise which fulfills to a module namespace object: an object containing all exports from moduleName.

The evaluation of import() never synchronously throws an error. moduleName is coerced to a string, and if coercion throws, the promise is rejected with the thrown error.

\n

Description

\n
\n

The import declaration syntax (import something from \"somewhere\") is static and will always result in the imported module being evaluated at load time. Dynamic imports allow one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand. The following are some reasons why you might need to use dynamic import:

Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking.

If your file is not run as a module (if it's referenced in an HTML file, the script tag must have type=\"module\"), you will not be able to use static import declarations, but the asynchronous dynamic import syntax will always be available, allowing you to import modules into non-module environments.

Dynamic module import is not permitted in all execution contexts. For example, import() can be used in the main thread, a shared worker, or a dedicated worker, but will throw if called within a service worker or a worklet.

\n

Module namespace object

\n
\n

A module namespace object is an object that describes all exports from a module. It is a static object that is created when the module is evaluated. There are two ways to access the module namespace object of a module: through a namespace import (import * as name from moduleName), or through the fulfillment value of a dynamic import.

The module namespace object is a sealed object with null prototype. This means all string keys of the object correspond to the exports of the module and there are never extra keys. All keys are enumerable in lexicographic order (i.e. the default behavior of Array.prototype.sort()), with the default export available as a key called default. In addition, the module namespace object has a @@toStringTag property with the value \"Module\", used in Object.prototype.toString().

The string properties are non-configurable and writable when you use Object.getOwnPropertyDescriptors() to get their descriptors. However, they are effectively read-only, because you cannot re-assign a property to a new value. This behavior mirrors the fact that static imports create \"live bindings\" — the values can be re-assigned by the module exporting them, but not by the module importing them. The writability of the properties reflects the possibility of the values changing, because non-configurable and non-writable properties must be constant. For example, you can re-assign the exported value of a variable, and the new value can be observed in the module namespace object.

Each module specifier corresponds to a unique module namespace object, so the following is generally true:

\n

js

\n
import * as mod from \"/my-module.js\";\n\nimport(\"/my-module.js\").then((mod2) => {\n  console.log(mod === mod2); // true\n});\n
\n

Except in one curious case: because a promise never fulfills to a thenable, if the my-module.js module exports a function called then(), that function will automatically get called when the dynamic import's promise is fulfilled, as part of the promise resolution process.

\n

js

\n
// my-module.js\nexport function then(resolve) {\n  console.log(\"then() called\");\n  resolve(1);\n}\n
\n
\n

js

\n
// main.js\nimport * as mod from \"/my-module.js\";\n\nimport(\"/my-module.js\").then((mod2) => {\n  // Logs \"then() called\"\n  console.log(mod === mod2); // false\n});\n
\n

Warning: Do not export a function called then() from a module. This will cause the module to behave differently when imported dynamically than when imported statically.

\n

Examples

\n

Import a module for its side effects only

\n
\n
\n

js

\n
(async () => {\n  if (somethingIsTrue) {\n    // import module for side effects\n    await import(\"/modules/my-module.js\");\n  }\n})();\n
\n

If your project uses packages that export ESM, you can also import them for side effects only. This will run the code in the package entry point file (and any files it imports) only.

\n

Importing defaults

\n
\n

You need to destructure and rename the \"default\" key from the returned object.

\n

js

\n
(async () => {\n  if (somethingIsTrue) {\n    const {\n      default: myDefault,\n      foo,\n      bar,\n    } = await import(\"/modules/my-module.js\");\n  }\n})();\n
\n
\n

Importing on-demand in response to user action

\n
\n

This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The import() function also supports await.

\n

js

\n
const main = document.querySelector(\"main\");\nfor (const link of document.querySelectorAll(\"nav > a\")) {\n  link.addEventListener(\"click\", (e) => {\n    e.preventDefault();\n\n    import(\"/modules/my-module.js\")\n      .then((module) => {\n        module.loadPageInto(main);\n      })\n      .catch((err) => {\n        main.textContent = err.message;\n      });\n  });\n}\n
\n
\n

Importing different modules based on environment

\n
\n

In processes such as server-side rendering, you may need to load different logic on server or in browser because they interact with different globals or modules (for example, browser code has access to web APIs like document and navigator, while server code has access to the server file system). You can do so through a conditional dynamic import.

\n

js

\n
let myModule;\n\nif (typeof window === \"undefined\") {\n  myModule = await import(\"module-used-on-server\");\n} else {\n  myModule = await import(\"module-used-in-browser\");\n}\n
\n
\n

Importing modules with a non-literal specifier

\n
\n

Dynamic imports allow any expression as the module specifier, not necessarily string literals.

Here, we load 10 modules, /modules/module-0.js, /modules/module-1.js, etc., concurrently, and call the load functions that each one exports.

\n

js

\n
Promise.all(\n  Array.from({ length: 10 }).map((_, index) =>\n    import(`/modules/module-${index}.js`),\n  ),\n).then((modules) => modules.forEach((module) => module.load()));\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-import-calls
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
import637967No5011.16363674611.38.0
1.0Bundled Deno applications (using `deno compile`) do not support dynamic imports
13.2.0Dynamic import can be used in either CommonJS or ES module files, to import either CommonJS or ES module files. See Node's ECMAScript Modules documentation for more details.
options_parameter9191NoNoNo159191NoNo1516.01.1717.5.016.15.0–17.0.0
16.14.0–16.15.0The second parameter no longer throws a parser error, but the --experimental-json-modules flag is still needed to load JSON modules.
\n
worker_support8080114No67158080114571513.01.0No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import\n

\n
\n", + "operators/increment": "

Increment (++)

The ++ operator increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.

\n

Try it

\n

Syntax

\n
\n

js

\n
x++\n++x\n
\n

Description

\n
\n

The ++ operator is overloaded for two types of operands: number and BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt increment if the operand becomes a BigInt; otherwise, it performs number increment.

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.

If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

The increment operator can only be applied on operands that are references (variables and object properties; i.e. valid assignment targets). ++x itself evaluates to a value, not a reference, so you cannot chain multiple increment operators together.

\n

js

\n
++(++x); // SyntaxError: Invalid left-hand side expression in prefix operation\n
\n
\n

Examples

\n

Postfix increment

\n
\n

js

\n
let x = 3;\nconst y = x++;\n// x is 4; y is 3\n\nlet x2 = 3n;\nconst y2 = x2++;\n// x2 is 4n; y2 is 3n\n
\n

Prefix increment

\n
\n

js

\n
let x = 3;\nconst y = ++x;\n// x is 4; y is 4\n\nlet x2 = 3n;\nconst y2 = ++x2;\n// x2 is 4n; y2 is 4n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-postfix-increment-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Increment21213344.418410.13.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment\n

\n
\n", + "operators/decrement": "

Decrement (--)

The -- operator decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.

\n

Try it

\n

Syntax

\n
\n

js

\n
x--\n--x\n
\n

Description

\n
\n

The -- operator is overloaded for two types of operands: number and BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt decrement if the operand becomes a BigInt; otherwise, it performs number decrement.

If used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.

If used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.

The decrement operator can only be applied on operands that are references (variables and object properties; i.e. valid assignment targets). --x itself evaluates to a value, not a reference, so you cannot chain multiple decrement operators together.

\n

js

\n
--(--x); // SyntaxError: Invalid left-hand side expression in prefix operation\n
\n
\n

Examples

\n

Postfix decrement

\n
\n

js

\n
let x = 3;\nconst y = x--;\n// x is 2; y is 3\n\nlet x2 = 3n;\nconst y2 = x2--;\n// x2 is 2n; y2 is 3n\n
\n

Prefix decrement

\n
\n

js

\n
let x = 3;\nconst y = --x;\n// x is 2; y = 2\n\nlet x2 = 3n;\nconst y2 = --x2;\n// x2 is 2n; y2 is 2n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-postfix-decrement-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Decrement21213344.418410.13.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Decrement\n

\n
\n", + "operators/delete": "

delete

The delete operator removes a property from an object. If the property's value is an object and there are no more references to the object, the object held by that property is eventually released automatically.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
delete object.property\ndelete object[property]\n
\n

Note: The syntax allows a wider range of expressions following the delete operator, but only the above forms lead to meaningful behaviors.

\n

Parameters

\n
object

The name of an object, or an expression evaluating to an object.

property

The property to delete.

Return value

\n

true for all cases except when the property is an own non-configurable property, in which case false is returned in non-strict mode.

Exceptions

\n
TypeError

Thrown in strict mode if the property is an own non-configurable property.

ReferenceError

Thrown if object is super.

Description

\n
\n

The delete operator has the same precedence as other unary operators like typeof. Therefore, it accepts any expression formed by higher-precedence operators. However, the following forms lead to early syntax errors in strict mode:

\n

js

\n
delete identifier;\ndelete object.#privateProperty;\n
\n

Because classes are automatically in strict mode, and private properties can only be legally referenced in class bodies, this means private properties can never be deleted. While delete identifier may work if identifier refers to a configurable property of the global object, you should avoid this form and prefix it with globalThis instead.

While other expressions are accepted, they don't lead to meaningful behaviors:

\n

js

\n
delete console.log(1);\n// Logs 1, returns true, but nothing deleted\n
\n

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. See the memory management page for more details.

It is important to consider the following scenarios:

\n

Examples

\n

Using delete

\n
\n

Note: The following example uses non-strict-mode only features, like implicitly creating global variables and deleting identifiers, which are forbidden in strict mode.

\n

js

\n
// Creates the property empCount on the global scope.\n// Since we are using var, this is marked as non-configurable.\nvar empCount = 43;\n\n// Creates the property EmployeeDetails on the global scope.\n// Since it was defined without \"var\", it is marked configurable.\nEmployeeDetails = {\n  name: \"xyz\",\n  age: 5,\n  designation: \"Developer\",\n};\n\n// delete can be used to remove properties from objects.\ndelete EmployeeDetails.name; // returns true\n\n// Even when the property does not exist, delete returns \"true\".\ndelete EmployeeDetails.salary; // returns true\n\n// EmployeeDetails is a property of the global scope.\ndelete EmployeeDetails; // returns true\n\n// On the contrary, empCount is not configurable\n// since var was used.\ndelete empCount; // returns false\n\n// delete also does not affect built-in static properties\n// that are non-configurable.\ndelete Math.PI; // returns false\n\nfunction f() {\n  var z = 44;\n\n  // delete doesn't affect local variable names\n  delete z; // returns false\n}\n
\n
\n

delete and the prototype chain

\n
\n

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

\n

js

\n
function Foo() {\n  this.bar = 10;\n}\n\nFoo.prototype.bar = 42;\n\nconst foo = new Foo();\n\n// foo.bar is associated with the\n// own property.\nconsole.log(foo.bar); // 10\n\n// Delete the own property within the\n// foo object.\ndelete foo.bar; // returns true\n\n// foo.bar is still available in the\n// prototype chain.\nconsole.log(foo.bar); // 42\n\n// Delete the property on the prototype.\ndelete Foo.prototype.bar; // returns true\n\n// The \"bar\" property can no longer be\n// inherited from Foo since it has been\n// deleted.\nconsole.log(foo.bar); // undefined\n
\n
\n

Deleting array elements

\n
\n

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

\n

js

\n
const trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ndelete trees[3];\nconsole.log(3 in trees); // false\n
\n

This creates a sparse array with an empty slot. If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

\n

js

\n
const trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ntrees[3] = undefined;\nconsole.log(3 in trees); // true\n
\n

If instead, you want to remove an array element by changing the contents of the array, use the splice() method. In the following example, trees[3] is removed from the array completely using splice():

\n

js

\n
const trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ntrees.splice(3, 1);\nconsole.log(trees); // [\"redwood\", \"bay\", \"cedar\", \"maple\"]\n
\n
\n

Deleting non-configurable properties

\n
\n

When a property is marked as non-configurable, delete won't have any effect, and will return false. In strict mode, this will raise a TypeError.

\n

js

\n
const Employee = {};\nObject.defineProperty(Employee, \"name\", { configurable: false });\n\nconsole.log(delete Employee.name); // returns false\n
\n

var creates non-configurable properties that cannot be deleted with the delete operator:

\n

js

\n
// Since \"nameOther\" is added using with the\n// var keyword, it is marked as non-configurable\nvar nameOther = \"XYZ\";\n\n// We can access this global property using:\nObject.getOwnPropertyDescriptor(globalThis, \"nameOther\");\n// {\n//   value: \"XYZ\",\n//   writable: true,\n//   enumerable: true,\n//   configurable: false\n// }\n\ndelete globalThis.nameOther; // return false\n
\n

In strict mode, this would raise an exception.

\n

Deleting global properties

\n
\n

If a global property is configurable (for example, via direct property assignment), it can be deleted, and subsequent references to them as global variables will produce a ReferenceError.

\n

js

\n
globalThis.globalVar = 1;\nconsole.log(globalVar); // 1\n// In non-strict mode, you can use `delete globalVar` as well\ndelete globalThis.globalVar;\nconsole.log(globalVar); // ReferenceError: globalVar is not defined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-delete-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
delete11214914.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\n

\n
\n", + "operators/void": "

void operator

The void operator evaluates the given expression and then returns undefined.

\n

Try it

\n

Syntax

\n
\n

js

\n
void expression\n
\n

Description

\n
\n

This operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired.

The void operator is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0). In these cases, the global variable undefined can be used.

It should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator:

\n

js

\n
void 2 === \"2\"; // (void 2) === '2', returns false\nvoid (2 === \"2\"); // void (2 === '2'), returns undefined\n
\n
\n

Examples

\n

Immediately Invoked Function Expressions

\n
\n

When using an immediately-invoked function expression, the function keyword cannot be at the immediate start of the statement, because that would be parsed as a function declaration, and would generate a syntax error when the parentheses representing invocation is reached — if the function is unnamed, it would immediately be a syntax error if the function is parsed as a declaration.

\n

js

\n
function iife() {\n  console.log(\"Executed!\");\n}(); // SyntaxError: Unexpected token ')'\n\nfunction () {\n  console.log(\"Executed!\");\n}(); // SyntaxError: Function statements require a function name\n
\n

In order for the function to be parsed as an expression, the function keyword has to appear at a position that only accepts expressions, not statements. This can be achieved be prefixing the keyword with a unary operator, which only accepts expressions as operands. Function invocation has higher precedence than unary operators, so it will be executed first. Its return value (which is almost always undefined) will be passed to the unary operator and then immediately discarded.

Of all the unary operators, void offers the best semantic, because it clearly signals that the return value of the function invocation should be discarded.

\n

js

\n
void function () {\n  console.log(\"Executed!\");\n}();\n\n// Logs \"Executed!\"\n
\n

This is a bit longer than wrapping the function expression in parentheses, which has the same effect of forcing the function keyword to be parsed as the start of an expression instead of a statement.

\n

js

\n
(function () {\n  console.log(\"Executed!\");\n})();\n
\n
\n

JavaScript URIs

\n
\n

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined. For example:

\n

html

\n
<a href=\"javascript:void(0);\">Click here to do nothing</a>\n\n<a href=\"javascript:void(document.body.style.backgroundColor='green');\">\n  Click here for green background\n</a>\n
\n

Note: javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.

\n

Non-leaking Arrow Functions

\n
\n

Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.

\n

js

\n
button.onclick = () => void doSomething();\n
\n

This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-void-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
void1121543.14.418410.131.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\n

\n
\n", + "operators/typeof": "

typeof

The typeof operator returns a string indicating the type of the operand's value.

\n

Try it

\n

Syntax

\n
\n

js

\n
typeof operand\n
\n

Parameters

\n
operand

An expression representing the object or primitive whose type is to be returned.

Description

\n
\n

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

Type Result
Undefined \"undefined\"
Null \n\"object\" (reason)
Boolean \"boolean\"
Number \"number\"
BigInt \"bigint\"
String \"string\"
Symbol \"symbol\"
\nFunction (implements [[Call]] in ECMA-262 terms; classes are functions as well) \"function\"
Any other object \"object\"

This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed.

\n

Examples

\n

Basic usage

\n
\n

js

\n
// Numbers\ntypeof 37 === \"number\";\ntypeof 3.14 === \"number\";\ntypeof 42 === \"number\";\ntypeof Math.LN2 === \"number\";\ntypeof Infinity === \"number\";\ntypeof NaN === \"number\"; // Despite being \"Not-A-Number\"\ntypeof Number(\"1\") === \"number\"; // Number tries to parse things into numbers\ntypeof Number(\"shoe\") === \"number\"; // including values that cannot be type coerced to a number\n\ntypeof 42n === \"bigint\";\n\n// Strings\ntypeof \"\" === \"string\";\ntypeof \"bla\" === \"string\";\ntypeof `template literal` === \"string\";\ntypeof \"1\" === \"string\"; // note that a number within a string is still typeof string\ntypeof typeof 1 === \"string\"; // typeof always returns a string\ntypeof String(1) === \"string\"; // String converts anything into a string, safer than toString\n\n// Booleans\ntypeof true === \"boolean\";\ntypeof false === \"boolean\";\ntypeof Boolean(1) === \"boolean\"; // Boolean() will convert values based on if they're truthy or falsy\ntypeof !!1 === \"boolean\"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()\n\n// Symbols\ntypeof Symbol() === \"symbol\";\ntypeof Symbol(\"foo\") === \"symbol\";\ntypeof Symbol.iterator === \"symbol\";\n\n// Undefined\ntypeof undefined === \"undefined\";\ntypeof declaredButUndefinedVariable === \"undefined\";\ntypeof undeclaredVariable === \"undefined\";\n\n// Objects\ntypeof { a: 1 } === \"object\";\n\n// use Array.isArray or Object.prototype.toString.call\n// to differentiate regular objects from arrays\ntypeof [1, 2, 4] === \"object\";\n\ntypeof new Date() === \"object\";\ntypeof /regex/ === \"object\";\n\n// The following are confusing, dangerous, and wasteful. Avoid them.\ntypeof new Boolean(true) === \"object\";\ntypeof new Number(1) === \"object\";\ntypeof new String(\"abc\") === \"object\";\n\n// Functions\ntypeof function () {} === \"function\";\ntypeof class C {} === \"function\";\ntypeof Math.sin === \"function\";\n
\n

typeof null

\n
\n
\n

js

\n
// This stands since the beginning of JavaScript\ntypeof null === \"object\";\n
\n

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value \"object\". (reference)

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === \"null\".

\n

Using new operator

\n
\n

All constructor functions called with new will return non-primitives (\"object\" or \"function\"). Most return objects, with the notable exception being Function, which returns a function.

\n

js

\n
const str = new String(\"String\");\nconst num = new Number(100);\n\ntypeof str; // \"object\"\ntypeof num; // \"object\"\n\nconst func = new Function();\n\ntypeof func; // \"function\"\n
\n
\n

Need for parentheses in syntax

\n
\n

The typeof operator has higher precedence than binary operators like addition (+). Therefore, parentheses are needed to evaluate the type of an addition result.

\n

js

\n
// Parentheses can be used for determining the data type of expressions.\nconst someData = 99;\n\ntypeof someData + \" Wisen\"; // \"number Wisen\"\ntypeof (someData + \" Wisen\"); // \"string\"\n
\n
\n

Interaction with undeclared and uninitialized variables

\n
\n

typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return \"undefined\" instead of throwing an error.

\n

js

\n
typeof undeclaredVariable; // \"undefined\"\n
\n

However, using typeof on lexical declarations (let const, and class) in the same block before the place of declaration will throw a ReferenceError. Block scoped variables are in a temporal dead zone from the start of the block until the initialization is processed, during which it will throw an error if accessed.

\n

js

\n
typeof newLetVariable; // ReferenceError\ntypeof newConstVariable; // ReferenceError\ntypeof newClass; // ReferenceError\n\nlet newLetVariable;\nconst newConstVariable = \"hello\";\nclass newClass {}\n
\n
\n

Exceptional behavior of document.all

\n
\n

All current browsers expose a non-standard host object document.all with type undefined.

\n

js

\n
typeof document.all === \"undefined\";\n
\n

Although document.all is also falsy and loosely equal to undefined, it is not undefined. The case of document.all having type \"undefined\" is classified in the web standards as a \"willful violation\" of the original ECMAScript standard for web compatibility.

\n

Custom method that gets a more specific type

\n
\n

typeof is very useful, but it's not as versatile as might be required. For example, typeof [] is \"object\", as well as typeof new Date(), typeof /abc/, etc.

For greater specificity in checking types, here we present a custom type(value) function, which mostly mimics the behavior of typeof, but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.

\n

js

\n
function type(value) {\n  if (value === null) {\n    return \"null\";\n  }\n  const baseType = typeof value;\n  // Primitive types\n  if (![\"object\", \"function\"].includes(baseType)) {\n    return baseType;\n  }\n\n  // Symbol.toStringTag often specifies the \"display name\" of the\n  // object's class. It's used in Object.prototype.toString().\n  const tag = value[Symbol.toStringTag];\n  if (typeof tag === \"string\") {\n    return tag;\n  }\n\n  // If it's a function whose source code starts with the \"class\" keyword\n  if (\n    baseType === \"function\" &&\n    Function.prototype.toString.call(value).startsWith(\"class\")\n  ) {\n    return \"class\";\n  }\n\n  // The name of the constructor; for example `Array`, `GeneratorFunction`,\n  // `Number`, `String`, `Boolean` or `MyCustomClass`\n  const className = value.constructor.name;\n  if (typeof className === \"string\" && className !== \"\") {\n    return className;\n  }\n\n  // At this point there's no robust way to get the type of value,\n  // so we use the base implementation.\n  return baseType;\n}\n
\n

For checking potentially non-existent variables that would otherwise throw a ReferenceError, use typeof nonExistentVar === \"undefined\" because this behavior cannot be mimicked with custom code.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typeof-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
typeof11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\n

\n
\n", + "operators/unary_plus": "

Unary plus (+)

The + operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

\n

Try it

\n

Syntax

\n
\n

js

\n
+x\n
\n

Description

\n
\n

Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

Unary plus does the exact same steps as normal number coercion used by most built-in methods expecting numbers. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN. Unlike other arithmetic operators, which work with both numbers and BigInts, using the + operator on BigInt values throws a TypeError.

\n

Examples

\n

Usage with numbers

\n
\n

js

\n
const x = 1;\nconst y = -1;\n\nconsole.log(+x);\n// 1\nconsole.log(+y);\n// -1\n
\n

Usage with non-numbers

\n
\n

js

\n
+true  // 1\n+false // 0\n+null  // 0\n+[]    // 0\n+function (val) { return val; } // NaN\n+1n    // throws TypeError: Cannot convert BigInt value to number\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-unary-plus-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Unary_plus11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus\n

\n
\n", + "operators/unary_negation": "

Unary negation (-)

The - operator precedes its operand and negates it.

\n

Try it

\n

Syntax

\n
\n

js

\n
-x\n
\n

Description

\n

The - operator is overloaded for two types of operands: number and BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt negation if the operand becomes a BigInt; otherwise, it performs number negation.

Examples

\n

Negating numbers

\n
\n

js

\n
const x = 3;\nconst y = -x;\n// y is -3; x is 3\n
\n

Negating non-numbers

\n
\n

The unary negation operator can convert a non-number into a number.

\n

js

\n
const x = \"4\";\nconst y = -x;\n\n// y is -4\n
\n

BigInts can be negated using the unary negation operator.

\n

js

\n
const x = 4n;\nconst y = -x;\n\n// y is -4n\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-unary-minus-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Unary_negation11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation\n

\n
\n", + "operators/bitwise_not": "

Bitwise NOT (~)

The ~ operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bit of the operand is 0, and a 0 otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
~x\n
\n

Description

\n
\n

The ~ operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces the operand to a numeric value and tests the type of it. It performs BigInt NOT if the operand becomes a BigInt; otherwise, it converts the operand to a 32-bit integer and performs number bitwise NOT.

The operator operates on the operands' bit representations in two's complement. The operator is applied to each bit, and the result is constructed bitwise.

The truth table for the NOT operation is:

x NOT x
0 1
1 0
 9 (base 10) = 00000000000000000000000000001001 (base 2)\n               --------------------------------\n~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)\n

Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Bitwise NOTing any 32-bit integer x yields -(x + 1). For example, ~-5 yields 4.

Bitwise NOTing any number x twice returns x converted to a 32-bit integer. Do not use ~~x to truncate numbers to integers; use Math.trunc() instead. Due to using 32-bit representation for numbers, both ~-1 and ~4294967295 (232 - 1) result in 0.

\n

Examples

\n

Using bitwise NOT

\n
\n

js

\n
~0; // -1\n~-1; // 0\n~1; // -2\n\n~0n; // -1n\n~4294967295n; // -4294967296n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bitwise-not-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_NOT11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT\n

\n
\n", + "operators/logical_not": "

Logical NOT (!)

The ! (logical complement, negation) operator takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.

\n

Try it

\n

Syntax

\n
\n

js

\n
!x\n
\n

Description

\n
\n

Returns false if its single operand can be converted to true; otherwise, returns true.

If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

Examples of expressions that can be converted to false are:

Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator (!!) or the Boolean constructor.

\n

Examples

\n

Using NOT

\n
\n

The following code shows examples of the ! (logical NOT) operator.

\n

js

\n
!true; // !t returns false\n!false; // !f returns true\n!\"\"; // !f returns true\n!\"Cat\"; // !t returns false\n
\n
\n

Double NOT (!!)

\n
\n

It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the \"truthyness\" or \"falsyness\" of the value (see truthy and falsy).

The same conversion can be done through the Boolean() function.

\n

js

\n
!!true; // !!truthy returns true\n!!{}; // !!truthy returns true: any object is truthy...\n!!new Boolean(false); // ...even Boolean objects with a false .valueOf()!\n!!false; // !!falsy returns false\n!!\"\"; // !!falsy returns false\n!!Boolean(false); // !!falsy returns false\n
\n
\n

Converting between NOTs

\n
\n

The following operation involving booleans:

\n

js

\n
!!bCondition\n
\n

is always equal to:

\n

js

\n
bCondition\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-logical-not-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Logical_NOT11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT\n

\n
\n", + "operators/await": "

await

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.

\n

Syntax

\n
\n

js

\n
await expression\n
\n

Parameters

\n
expression

A Promise, a thenable object, or any value to wait for.

Return value

\n

The fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value.

Exceptions

\n

Throws the rejection reason if the promise or thenable object is rejected.

Description

\n
\n

await is usually used to unwrap promises by passing a Promise as the expression. Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the await expression becomes that of the fulfilled promise.

If the promise is rejected, the await expression throws the rejected value. The function containing the await expression will appear in the stack trace of the error. Otherwise, if the rejected promise is not awaited or is immediately returned, the caller function will not appear in the stack trace.

The expression is resolved in the same way as Promise.resolve(): it's always converted to a native Promise and then awaited. If the expression is a:

Even when the used promise is already fulfilled, the async function's execution still pauses until the next tick. In the meantime, the caller of the async function resumes execution. See example below.

Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.

\n

Examples

\n

Awaiting a promise to be fulfilled

\n
\n

If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

\n

js

\n
function resolveAfter2Seconds(x) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve(x);\n    }, 2000);\n  });\n}\n\nasync function f1() {\n  const x = await resolveAfter2Seconds(10);\n  console.log(x); // 10\n}\n\nf1();\n
\n
\n

Thenable objects

\n
\n

Thenable objects are resolved just the same as actual Promise objects.

\n

js

\n
async function f() {\n  const thenable = {\n    then(resolve, _reject) {\n      resolve(\"resolved!\");\n    },\n  };\n  console.log(await thenable); // \"resolved!\"\n}\n\nf();\n
\n

They can also be rejected:

\n

js

\n
async function f() {\n  const thenable = {\n    then(resolve, reject) {\n      reject(new Error(\"rejected!\"));\n    },\n  };\n  await thenable; // Throws Error: rejected!\n}\n\nf();\n
\n
\n

Conversion to promise

\n
\n

If the value is not a Promise, await converts the value to a resolved Promise, and waits for it. The awaited value's identity doesn't change as long as it doesn't have a then property that's callable.

\n

js

\n
async function f3() {\n  const y = await 20;\n  console.log(y); // 20\n\n  const obj = {};\n  console.log((await obj) === obj); // true\n}\n\nf3();\n
\n
\n

Handling rejected promises

\n
\n

If the Promise is rejected, the rejected value is thrown.

\n

js

\n
async function f4() {\n  try {\n    const z = await Promise.reject(30);\n  } catch (e) {\n    console.error(e); // 30\n  }\n}\n\nf4();\n
\n

You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.

\n

js

\n
const response = await promisedFunction().catch((err) => {\n  console.error(err);\n  return \"default response\";\n});\n// response will be \"default response\" if the promise is rejected\n
\n

This is built on the assumption that promisedFunction() never synchronously throws an error, but always returns a rejected promise. This is the case for most properly-designed promise-based functions, which usually look like:

\n

js

\n
function promisedFunction() {\n  // Immediately return a promise to minimize chance of an error being thrown\n  return new Promise((resolve, reject) => {\n    // do something async\n  });\n}\n
\n

However, if promisedFunction() does throw an error synchronously, the error won't be caught by the catch() handler. In this case, the try...catch statement is necessary.

\n

Top level await

\n
\n

You can use the await keyword on its own (outside of an async function) at the top level of a module. This means that modules with child modules that use await will wait for the child modules to execute before they themselves run, all while not blocking other child modules from loading.

Here is an example of a simple module using the Fetch API and specifying await within the export statement. Any modules that include this will wait for the fetch to resolve before running any code.

\n

js

\n
// fetch request\nconst colors = fetch(\"../data/colors.json\").then((response) => response.json());\n\nexport default await colors;\n
\n
\n

Control flow effects of await

\n
\n

When an await is encountered in code (either in an async function or in a module), the awaited expression is executed, while all code that depends on the expression's value is paused and pushed into the microtask queue. The main thread is then freed for the next task in the event loop. This happens even if the awaited value is an already-resolved promise or not a promise. For example, consider the following code:

\n

js

\n
async function foo(name) {\n  console.log(name, \"start\");\n  console.log(name, \"middle\");\n  console.log(name, \"end\");\n}\n\nfoo(\"First\");\nfoo(\"Second\");\n\n// First start\n// First middle\n// First end\n// Second start\n// Second middle\n// Second end\n
\n

In this case, the two async functions are synchronous in effect, because they don't contain any await expression. The three statements happen in the same tick. In promise terms, the function corresponds to:

\n

js

\n
function foo(name) {\n  return new Promise((resolve) => {\n    console.log(name, \"start\");\n    console.log(name, \"middle\");\n    console.log(name, \"end\");\n    resolve();\n  });\n}\n
\n

However, as soon as there's one await, the function becomes asynchronous, and execution of following statements is deferred to the next tick.

\n

js

\n
async function foo(name) {\n  console.log(name, \"start\");\n  await console.log(name, \"middle\");\n  console.log(name, \"end\");\n}\n\nfoo(\"First\");\nfoo(\"Second\");\n\n// First start\n// First middle\n// Second start\n// Second middle\n// First end\n// Second end\n
\n

This corresponds to:

\n

js

\n
function foo(name) {\n  return new Promise((resolve) => {\n    console.log(name, \"start\");\n    resolve(console.log(name, \"middle\"));\n  }).then(() => {\n    console.log(name, \"end\");\n  });\n}\n
\n

While the extra then() handler is not necessary, and the handler can be merged with the executor passed to the constructor, the then() handler's existence means the code will take one extra tick to complete. The same happens for await. Therefore, make sure to use await only when necessary (to unwrap promises into their values).

Other microtasks can execute before the async function resumes. This example uses queueMicrotask() to demonstrate how the microtask queue is processed when each await expression is encountered.

\n

js

\n
let i = 0;\n\nqueueMicrotask(function test() {\n  i++;\n  console.log(\"microtask\", i);\n  if (i < 3) {\n    queueMicrotask(test);\n  }\n});\n\n(async () => {\n  console.log(\"async function start\");\n  for (let i = 1; i < 3; i++) {\n    await null;\n    console.log(\"async function resume\", i);\n  }\n  await null;\n  console.log(\"async function end\");\n})();\n\nqueueMicrotask(() => {\n  console.log(\"queueMicrotask() after calling async function\");\n});\n\nconsole.log(\"script sync part end\");\n\n// Logs:\n// async function start\n// script sync part end\n// microtask 1\n// async function resume 1\n// queueMicrotask() after calling async function\n// microtask 2\n// async function resume 2\n// microtask 3\n// async function end\n
\n

In this example, the test() function is always called before the async function resumes, so the microtasks they each schedule are always executed in an intertwined fashion. On the other hand, because both await and queueMicrotask() schedule microtasks, the order of execution is always based on the order of scheduling. This is why the \"queueMicrotask() after calling async function\" log happens after the async function resumes for the first time.

\n

Improving stack trace

\n
\n

Sometimes, the await is omitted when a promise is directly returned from an async function.

\n

js

\n
async function noAwait() {\n  // Some actions...\n\n  return /* await */ lastAsyncTask();\n}\n
\n

However, consider the case where lastAsyncTask asynchronously throws an error.

\n

js

\n
async function lastAsyncTask() {\n  await null;\n  throw new Error(\"failed\");\n}\n\nasync function noAwait() {\n  return lastAsyncTask();\n}\n\nnoAwait();\n\n// Error: failed\n//    at lastAsyncTask\n
\n

Only lastAsyncTask appears in the stack trace, because the promise is rejected after it has already been returned from noAwait — in some sense, the promise is unrelated to noAwait. To improve the stack trace, you can use await to unwrap the promise, so that the exception gets thrown into the current function. The exception will then be immediately wrapped into a new rejected promise, but during error creation, the caller will appear in the stack trace.

\n

js

\n
async function lastAsyncTask() {\n  await null;\n  throw new Error(\"failed\");\n}\n\nasync function withAwait() {\n  return await lastAsyncTask();\n}\n\nwithAwait();\n\n// Error: failed\n//    at lastAsyncTask\n//    at async withAwait\n
\n

However, there's a little performance penalty coming with return await because the promise has to be unwrapped and wrapped again.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
await551452No4210.15555524210.36.01.07.6.0
top_level898989No7515898989631515.01.0
14.8.0Not supported in CommonJS modules.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await\n

\n
\n", + "operators/exponentiation": "

Exponentiation (**)

The ** operator returns the result of raising the first operand to the power of the second operand. It is equivalent to Math.pow(), except it also accepts BigInts as operands.

\n

Try it

\n

Syntax

\n
\n

js

\n
x ** y\n
\n

Description

\n
\n

The ** operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt exponentiation if both operands become BigInts; otherwise, it performs number exponentiation. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

For both numbers and BigInts, 0 raised to a positive power returns 0, and 0 raised to a power of 0 returns 1. For numbers, 0 raised to a negative number returns Infinity, while -0 raised to a negative number returns -Infinity.

NaN ** 0 (and the equivalent Math.pow(NaN, 0)) is the only case where NaN doesn't propagate through mathematical operations — it returns 1 despite the operand being NaN. In addition, the behavior where base is 1 and exponent is non-finite (±Infinity or NaN) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns NaN to preserve backward compatibility with its original behavior.

For BigInt exponentiation, a RangeError is thrown if the exponent y is negative. This is because any negative exponent would likely result in a value between 0 and 1 (unless the base is 1, -1, or 0), which is rounded to zero, and is likely a developer mistake.

The exponentiation operator is right-associative: a ** b ** c is equal to a ** (b ** c).

In most languages, such as PHP, Python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. For example, in Bash, the ** operator is defined to have a lower precedence than unary operators.

In JavaScript, it is impossible to write an ambiguous exponentiation expression. That is, you cannot put a unary operator (with precedence 14, including +/-/~/!/++/--/delete/void/typeof/await) immediately before the base number; doing so will cause a SyntaxError.

For example, -2 ** 2 is 4 in Bash, but is -4 in other languages (such as Python). This is invalid in JavaScript, as the operation is ambiguous. You have to parenthesize either side — for example, as -(2 ** 2) — to make the intention unambiguous.

Note that some programming languages use the caret symbol ^ for exponentiation, but JavaScript uses that symbol for the bitwise XOR operator.

\n

Examples

\n

Basic exponentiation

\n
\n

js

\n
2 ** 3; // 8\n3 ** 2; // 9\n3 ** 2.5; // 15.588457268119896\n10 ** -1; // 0.1\n2 ** 1024; // Infinity\nNaN ** 2; // NaN\nNaN ** 0; // 1\n1 ** Infinity; // NaN\n\n2n ** 3n; // 8n\n2n ** 1024n; // A very large number, but not Infinity\n\n2n ** 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n// To do exponentiation with a BigInt and a non-BigInt, convert either operand\n2n ** BigInt(2); // 4n\nNumber(2n) ** 2; // 4\n
\n

Associativity

\n
\n

js

\n
2 ** 3 ** 2; // 512\n2 ** (3 ** 2); // 512\n(2 ** 3) ** 2; // 64\n
\n

Usage with unary operators

\n
\n

To invert the sign of the result of an exponentiation expression:

\n

js

\n
-(2 ** 2); // -4\n
\n

To force the base of an exponentiation expression to be a negative number:

\n

js

\n
(-2) ** 2; // 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-exp-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Exponentiation521452No3910.15152524110.36.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation\n

\n
\n", + "operators/multiplication": "

Multiplication (*)

The * operator produces the product of the operands.

\n

Try it

\n

Syntax

\n
\n

js

\n
x * y\n
\n

Description

\n

The * operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt multiplication if both operands become BigInts; otherwise, it performs number multiplication. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

Examples

\n

Multiplication using numbers

\n
\n

js

\n
2 * 2; // 4\n-2 * 2; // -4\n
\n

Multiplication with Infinity

\n
\n

js

\n
Infinity * 0; // NaN\nInfinity * Infinity; // Infinity\n
\n

Multiplication with non-numbers

\n
\n

js

\n
\"foo\" * 2; // NaN\n\"2\" * 2; // 4\n
\n

Multiplication using BigInts

\n
\n

js

\n
2n * 2n; // 4n\n-2n * 2n; // -4n\n\n2n * 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n// To multiply a BigInt with a non-BigInt, convert either operand\n2n * BigInt(2); // 4n\nNumber(2n) * 2; // 4\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-multiplicative-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Multiplication11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication\n

\n
\n", + "operators/division": "

Division (/)

The / operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

\n

Try it

\n

Syntax

\n
\n

js

\n
x / y\n
\n

Description

\n
\n

The / operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt division if both operands become BigInts; otherwise, it performs number division. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

For BigInt division, the result is the quotient of the two operands truncated towards zero, and the remainder is discarded. A RangeError is thrown if the divisor y is 0n. This is because number division by zero returns Infinity or -Infinity, but BigInt has no concept of infinity.

\n

Examples

\n

Basic division

\n
\n

js

\n
1 / 2; // 0.5\n\nMath.floor(3 / 2); // 1\n\n1.0 / 2.0; // 0.5\n\n1n / 2n; // 0n\n5n / 3n; // 1n\n-1n / 3n; // 0n\n1n / -3n; // 0n\n\n2n / 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n// To do division with a BigInt and a non-BigInt, convert either operand\n2n / BigInt(2); // 1n\nNumber(2n) / 2; // 1\n
\n

Division by zero

\n
\n

js

\n
2.0 / 0; // Infinity\n\n2.0 / 0.0; // Infinity, because 0.0 === 0\n\n2.0 / -0.0; // -Infinity\n\n2n / 0n; // RangeError: Division by zero\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-multiplicative-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Division11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division\n

\n
\n", + "operators/remainder": "

Remainder (%)

The % operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

\n

Try it

\n

Syntax

\n
\n

js

\n
x % y\n
\n

Description

\n
\n

The % operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt remainder if both operands become BigInts; otherwise, it performs number remainder. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

For the operation n % d, n is called the dividend and d is called the divisor. The operation returns NaN if one of the operands is NaN, n is ±Infinity, or if d is ±0. Otherwise, if d is ±Infinity or if n is ±0, the dividend n is returned.

When both operands are non-zero and finite, the remainder r is calculated as r := n - d * q where q is the integer such that r has the same sign as the dividend n while being as close to 0 as possible.

Note that while in most languages, '%' is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. Modulo is defined as k := n - d * q where q is the integer such that k has the same sign as the divisor d while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the divisor, while the remainder has the same sign as the dividend, which can make them differ by one unit of d. To obtain a modulo in JavaScript, in place of n % d, use ((n % d) + d) % d. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators (<<, >>, etc.), making the offset always a positive value.

For BigInt division, a RangeError is thrown if the divisor y is 0n. This is because number remainder by zero returns NaN, but BigInt has no concept of NaN.

\n

Examples

\n

Remainder with positive dividend

\n
\n

js

\n
13 % 5; // 3\n1 % -2; // 1\n1 % 2; // 1\n2 % 3; // 2\n5.5 % 2; // 1.5\n\n3n % 2n; // 1n\n
\n

Remainder with negative dividend

\n
\n

js

\n
-13 % 5; // -3\n-1 % 2; // -1\n-4 % 2; // -0\n\n-3n % 2n; // -1n\n
\n

Remainder with NaN

\n
\n

js

\n
NaN % 2; // NaN\n
\n

Remainder with Infinity

\n
\n

js

\n
Infinity % 2; // NaN\nInfinity % 0; // NaN\nInfinity % Infinity; // NaN\n2 % Infinity; // 2\n0 % Infinity; // 0\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-multiplicative-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Remainder11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder\n

\n
\n", + "operators/addition": "

Addition (+)

The + operator produces the sum of numeric operands or string concatenation.

\n

Try it

\n

Syntax

\n
\n

js

\n
x + y\n
\n

Description

\n
\n

The + operator is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it first coerces both operands to primitives. Then, the two operands' types are tested:

String concatenation is often thought to be equivalent with template literals or String.prototype.concat(), but they are not. Addition coerces the expression to a primitive, which calls valueOf() in priority; on the other hand, template literals and concat() coerce the expression to a string, which calls toString() in priority. If the expression has a @@toPrimitive method, string concatenation calls it with \"default\" as hint, while template literals use \"string\". This is important for objects that have different string and primitive representations — such as Temporal, whose valueOf() method throws.

\n

js

\n
const t = Temporal.Now.instant();\n\"\" + t; // Throws TypeError\n`${t}`; // '2022-07-31T04:48:56.113918308Z'\n\"\".concat(t); // '2022-07-31T04:48:56.113918308Z'\n
\n

You are advised to not use \"\" + x to perform string coercion.

\n

Examples

\n

Number addition

\n
\n

js

\n
// Number + Number -> addition\n1 + 2; // 3\n\n// Boolean + Number -> addition\ntrue + 1; // 2\n\n// Boolean + Boolean -> addition\nfalse + false; // 0\n
\n

BigInt addition

\n
\n

js

\n
// BigInt + BigInt -> addition\n1n + 2n; // 3n\n\n// BigInt + Number -> throws TypeError\n1n + 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n\n// To add a BigInt to a non-BigInt, convert either operand\n1n + BigInt(2); // 3n\nNumber(1n) + 2; // 3\n
\n

String concatenation

\n
\n

js

\n
// String + String -> concatenation\n\"foo\" + \"bar\"; // \"foobar\"\n\n// Number + String -> concatenation\n5 + \"foo\"; // \"5foo\"\n\n// String + Boolean -> concatenation\n\"foo\" + false; // \"foofalse\"\n\n// String + Number -> concatenation\n\"2\" + 2; // \"22\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-addition-operator-plus
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Addition11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition\n

\n
\n", + "operators/subtraction": "

Subtraction (-)

The - operator subtracts the two operands, producing their difference.

\n

Try it

\n

Syntax

\n
\n

js

\n
x - y\n
\n

Description

\n

The - operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt subtraction if both operands become BigInts; otherwise, it performs number subtraction. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

Examples

\n

Subtraction with numbers

\n
\n

js

\n
// Number - Number -> subtraction\n5 - 3; // 2\n\n// Number - Number -> subtraction\n3 - 5; // -2\n
\n

Subtraction with non-numbers

\n
\n

js

\n
// String - Number -> subtraction\n\"foo\" - 3; // NaN; \"foo\" is converted to the number NaN\n\n// Number - String -> subtraction\n5 - \"3\"; // 2; \"3\" is converted to the number 3\n
\n

Subtraction with BigInts

\n
\n
\n

js

\n
// BigInt - BigInt -> subtraction\n2n - 1n; // 1n\n
\n

You cannot mix BigInt and number operands in subtraction.

\n

js

\n
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-subtraction-operator-minus
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Subtraction11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction\n

\n
\n", + "operators/less_than": "

Less than (<)

The < operator returns true if the left operand is less than the right operand, and false otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
x < y\n
\n

Description

\n
\n

The operands are compared with multiple rounds of coercion, which can be summarized as follows:

Other operators, including >, >=, and <=, use the same algorithm as <. There are two cases where all four operators return false:

For all other cases, the four operators have the following relationships:

\n

js

\n
x < y === !(x >= y);\nx <= y === !(x > y);\nx > y === y < x;\nx >= y === y <= x;\n
\n

Note: One observable difference between < and > is the order of coercion, especially if the coercion to primitive has side effects. All comparison operators coerce the left operand before the right operand.

\n

Examples

\n

String to string comparison

\n
\n

js

\n
\"a\" < \"b\"; // true\n\"a\" < \"a\"; // false\n\"a\" < \"3\"; // false\n
\n

String to number comparison

\n
\n

js

\n
\"5\" < 3; // false\n\"3\" < 3; // false\n\"3\" < 5; // true\n\n\"hello\" < 5; // false\n5 < \"hello\"; // false\n\n\"5\" < 3n; // false\n\"3\" < 5n; // true\n
\n

Number to Number comparison

\n
\n

js

\n
5 < 3; // false\n3 < 3; // false\n3 < 5; // true\n
\n

Number to BigInt comparison

\n
\n

js

\n
5n < 3; // false\n3 < 5n; // true\n
\n

Comparing Boolean, null, undefined, NaN

\n
\n

js

\n
true < false; // false\nfalse < true; // true\n\n0 < true; // true\ntrue < 1; // false\n\nnull < 0; // false\nnull < 1; // true\n\nundefined < 3; // false\n3 < undefined; // false\n\n3 < NaN; // false\nNaN < 3; // false\n
\n

Comparison with side effects

\n
\n

Comparisons always coerce their operands to primitives. This means the same object may end up having different values within one comparison expression. For example, you may have two values that are both greater than and less than the other.

\n

js

\n
class Mystery {\n  static #coercionCount = -1;\n  valueOf() {\n    Mystery.#coercionCount++;\n    // The left operand is coerced first, so this will return 0\n    // Then it returns 1 for the right operand\n    return Mystery.#coercionCount % 2;\n  }\n}\n\nconst l = new Mystery();\nconst r = new Mystery();\nconsole.log(l < r && r < l);\n// true\n
\n

Warning: This can be a source of confusion. If your objects provide custom primitive conversion logic, make sure it is idempotent: multiple coercions should return the same value.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Less_than11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than\n

\n
\n", + "operators/greater_than": "

Greater than (>)

The > operator returns true if the left operand is greater than the right operand, and false otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
x > y\n
\n

Description

\n

The operands are compared using the same algorithm as the Less than operator, except the two operands are swapped. x > y is generally equivalent to y < x, except that x > y coerces x to a primitive before y, while y < x coerces y to a primitive before x. Because coercion may have side effects, the order of the operands may matter.

Examples

\n

String to string comparison

\n
\n

js

\n
\"a\" > \"b\"; // false\n\"a\" > \"a\"; // false\n\"a\" > \"3\"; // true\n
\n

String to number comparison

\n
\n

js

\n
\"5\" > 3; // true\n\"3\" > 3; // false\n\"3\" > 5; // false\n\n\"hello\" > 5; // false\n5 > \"hello\"; // false\n\n\"5\" > 3n; // true\n\"3\" > 5n; // false\n
\n

Number to Number comparison

\n
\n

js

\n
5 > 3; // true\n3 > 3; // false\n3 > 5; // false\n
\n

Number to BigInt comparison

\n
\n

js

\n
5n > 3; // true\n3 > 5n; // false\n
\n

Comparing Boolean, null, undefined, NaN

\n
\n

js

\n
true > false; // true\nfalse > true; // false\n\ntrue > 0; // true\ntrue > 1; // false\n\nnull > 0; // false\n1 > null; // true\n\nundefined > 3; // false\n3 > undefined; // false\n\n3 > NaN; // false\nNaN > 3; // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Greater_than11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than\n

\n
\n", + "operators/less_than_or_equal": "

Less than or equal (<=)

The <= operator returns true if the left operand is less than or equal to the right operand, and false otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
x <= y\n
\n

Description

\n
\n

The operands are compared using the same algorithm as the Less than operator, with the operands swapped and the result negated. x <= y is generally equivalent to !(y < x), except for two cases where x <= y and x > y are both false:

In addition, x <= y coerces x to a primitive before y, while y < x coerces y to a primitive before x. Because coercion may have side effects, the order of the operands may matter.

x <= y is generally equivalent to x < y || x == y, except for a few cases:

\n

Examples

\n

String to string comparison

\n
\n

js

\n
\"a\" <= \"b\"; // true\n\"a\" <= \"a\"; // true\n\"a\" <= \"3\"; // false\n
\n

String to number comparison

\n
\n

js

\n
\"5\" <= 3; // false\n\"3\" <= 3; // true\n\"3\" <= 5; // true\n\n\"hello\" <= 5; // false\n5 <= \"hello\"; // false\n
\n

Number to Number comparison

\n
\n

js

\n
5 <= 3; // false\n3 <= 3; // true\n3 <= 5; // true\n
\n

Number to BigInt comparison

\n
\n

js

\n
5n <= 3; // false\n3 <= 3n; // true\n3 <= 5n; // true\n
\n

Comparing Boolean, null, undefined, NaN

\n
\n

js

\n
true <= false; // false\ntrue <= true; // true\nfalse <= true; // true\n\ntrue <= 0; // false\ntrue <= 1; // true\n\nnull <= 0; // true\n1 <= null; // false\n\nundefined <= 3; // false\n3 <= undefined; // false\n\n3 <= NaN; // false\nNaN <= 3; // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Less_than_or_equal11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal\n

\n
\n", + "operators/greater_than_or_equal": "

Greater than or equal (>=)

The >= operator returns true if the left operand is greater than or equal to the right operand, and false otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
x >= y\n
\n

Description

\n
\n

The operands are compared using the same algorithm as the Less than operator, with the result negated. x >= y is generally equivalent to !(x < y), except for two cases where x >= y and x < y are both false:

x >= y is generally equivalent to x > y || x == y, except for a few cases:

\n

Examples

\n

String to string comparison

\n
\n

js

\n
\"a\" >= \"b\"; // false\n\"a\" >= \"a\"; // true\n\"a\" >= \"3\"; // true\n
\n

String to number comparison

\n
\n

js

\n
\"5\" >= 3; // true\n\"3\" >= 3; // true\n\"3\" >= 5; // false\n\n\"hello\" >= 5; // false\n5 >= \"hello\"; // false\n
\n

Number to Number comparison

\n
\n

js

\n
5 >= 3; // true\n3 >= 3; // true\n3 >= 5; // false\n
\n

Number to BigInt comparison

\n
\n

js

\n
5n >= 3; // true\n3 >= 3n; // true\n3 >= 5n; // false\n
\n

Comparing Boolean, null, undefined, NaN

\n
\n

js

\n
true >= false; // true\ntrue >= true; // true\nfalse >= true; // false\n\ntrue >= 0; // true\ntrue >= 1; // true\n\nnull >= 0; // true\n1 >= null; // true\n\nundefined >= 3; // false\n3 >= undefined; // false\n\n3 >= NaN; // false\nNaN >= 3; // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Greater_than_or_equal11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal\n

\n
\n", + "operators/instanceof": "

instanceof

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.hasInstance.

\n

Try it

\n

Syntax

\n
\n

js

\n
object instanceof constructor\n
\n

Parameters

\n
object

The object to test.

constructor

Constructor to test against.

Exceptions

\n
TypeError

Thrown if constructor is not an object. If constructor doesn't have a @@hasInstance method, it must also be a function.

Description

\n
\n

The instanceof operator tests the presence of constructor.prototype in object's prototype chain. This usually (though not always) means object was constructed with constructor.

\n

js

\n
// defining constructors\nfunction C() {}\nfunction D() {}\n\nconst o = new C();\n\n// true, because: Object.getPrototypeOf(o) === C.prototype\no instanceof C;\n\n// false, because D.prototype is nowhere in o's prototype chain\no instanceof D;\n\no instanceof Object; // true, because:\nC.prototype instanceof Object; // true\n\n// Re-assign `constructor.prototype`: you should\n// rarely do this in practice.\nC.prototype = {};\nconst o2 = new C();\n\no2 instanceof C; // true\n\n// false, because C.prototype is nowhere in\n// o's prototype chain anymore\no instanceof C;\n\nD.prototype = new C(); // add C to [[Prototype]] linkage of D\nconst o3 = new D();\no3 instanceof D; // true\no3 instanceof C; // true since C.prototype is now in o3's prototype chain\n
\n

Note that the value of an instanceof test can change if constructor.prototype is re-assigned after creating the object (which is usually discouraged). It can also be changed by changing object's prototype using Object.setPrototypeOf.

Classes behave in the same way, because classes also have the prototype property.

\n

js

\n
class A {}\nclass B extends A {}\n\nconst o1 = new A();\n// true, because Object.getPrototypeOf(o1) === A.prototype\no1 instanceof A;\n// false, because B.prototype is nowhere in o1's prototype chain\no1 instanceof B;\n\nconst o2 = new B();\n// true, because Object.getPrototypeOf(Object.getPrototypeOf(o2)) === A.prototype\no2 instanceof A;\n// true, because Object.getPrototypeOf(o2) === B.prototype\no2 instanceof B;\n
\n

For bound functions, instanceof looks up for the prototype property on the target function, since bound functions don't have prototype.

\n

js

\n
class Base {}\nconst BoundBase = Base.bind(null, 1, 2);\nconsole.log(new Base() instanceof BoundBase); // true\n
\n
\n

instanceof and @@hasInstance

\n
\n

If constructor has a Symbol.hasInstance method, the method will be called in priority, with object as its only argument and constructor as this.

\n

js

\n
// This class allows plain objects to be disguised as this class's instance,\n// as long as the object has a particular flag as its property.\nclass Forgeable {\n  static isInstanceFlag = Symbol(\"isInstanceFlag\");\n\n  static [Symbol.hasInstance](obj) {\n    return Forgeable.isInstanceFlag in obj;\n  }\n}\n\nconst obj = { [Forgeable.isInstanceFlag]: true };\nconsole.log(obj instanceof Forgeable); // true\n
\n

Because all functions inherit from Function.prototype by default, most of the time, the Function.prototype[@@hasInstance] method specifies the behavior of instanceof when the right-hand side is a function. See the Symbol.hasInstance page for the exact algorithm of instanceof.

\n

instanceof and multiple realms

\n
\n

JavaScript execution environments (windows, frames, etc.) are each in their own realm. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array.prototype and arrays in the current realm inherit from the former.

This may not make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is in fact an Array using Array.isArray(), neglecting which realm it comes from.

For example, to check if a Node is an SVGElement in a different context, you can use myNode instanceof myNode.ownerDocument.defaultView.SVGElement.

\n

Examples

\n

Using instanceof with String

\n
\n

The following example shows the behavior of instanceof with String objects.

\n

js

\n
const literalString = \"This is a literal string\";\nconst stringObject = new String(\"String created with constructor\");\n\nliteralString instanceof String; // false, string primitive is not a String\nstringObject instanceof String; // true\n\nliteralString instanceof Object; // false, string primitive is not an Object\nstringObject instanceof Object; // true\n\nstringObject instanceof Date; // false\n
\n
\n

Using instanceof with Date

\n
\n

The following example shows the behavior of instanceof with Date objects.

\n

js

\n
const myDate = new Date();\n\nmyDate instanceof Date; // true\nmyDate instanceof Object; // true\nmyDate instanceof String; // false\n
\n
\n

Objects created using Object.create()

\n
\n

The following example shows the behavior of instanceof with objects created using Object.create().

\n

js

\n
function Shape() {}\n\nfunction Rectangle() {\n  Shape.call(this); // call super constructor.\n}\n\nRectangle.prototype = Object.create(Shape.prototype);\n\nRectangle.prototype.constructor = Rectangle;\n\nconst rect = new Rectangle();\n\nrect instanceof Object; // true\nrect instanceof Shape; // true\nrect instanceof Rectangle; // true\nrect instanceof String; // false\n\nconst literalObject = {};\nconst nullObject = Object.create(null);\nnullObject.name = \"My object\";\n\nliteralObject instanceof Object; // true, every object literal has Object.prototype as prototype\n({}) instanceof Object; // true, same case as above\nnullObject instanceof Object; // false, prototype is end of prototype chain (null)\n
\n
\n

Demonstrating that mycar is of type Car and type Object

\n
\n

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

\n

js

\n
function Car(make, model, year) {\n  this.make = make;\n  this.model = model;\n  this.year = year;\n}\nconst mycar = new Car(\"Honda\", \"Accord\", 1998);\nconst a = mycar instanceof Car; // returns true\nconst b = mycar instanceof Object; // returns true\n
\n
\n

Not an instanceof

\n
\n

To test if an object is not an instanceof a specific constructor, you can do:

\n

js

\n
if (!(mycar instanceof Car)) {\n  // Do something, like:\n  // mycar = new Car(mycar)\n}\n
\n

This is really different from:

\n

js

\n
if (!mycar instanceof Car) {\n  // unreachable code\n}\n
\n

This will always be false. (!mycar will be evaluated before instanceof, so you always try to know if a boolean is an instance of Car).

\n

Overriding the behavior of instanceof

\n
\n

A common pitfall of using instanceof is believing that, if x instanceof C, then x was created using C as constructor. This is not true, because x could be directly assigned with C.prototype as its prototype. In this case, if your code reads private fields of C from x, it would still fail:

\n

js

\n
class C {\n  #value = \"foo\";\n  static getValue(x) {\n    return x.#value;\n  }\n}\n\nconst x = { __proto__: C.prototype };\n\nif (x instanceof C) {\n  console.log(C.getValue(x)); // TypeError: Cannot read private member #value from an object whose class did not declare it\n}\n
\n

To avoid this, you can override the behavior of instanceof by adding a Symbol.hasInstance method to C, so that it does a branded check with in:

\n

js

\n
class C {\n  #value = \"foo\";\n\n  static [Symbol.hasInstance](x) {\n    return #value in x;\n  }\n\n  static getValue(x) {\n    return x.#value;\n  }\n}\n\nconst x = { __proto__: C.prototype };\n\nif (x instanceof C) {\n  // Doesn't run, because x is not a C\n  console.log(C.getValue(x));\n}\n
\n

Note that you may want to limit this behavior to the current class; otherwise, it could lead to false positives for subclasses:

\n

js

\n
class D extends C {}\nconsole.log(new C() instanceof D); // true; because D inherits @@hasInstance from C\n
\n

You could do this by checking that this is the current constructor:

\n

js

\n
class C {\n  #value = \"foo\";\n\n  static [Symbol.hasInstance](x) {\n    return this === C && #value in x;\n  }\n}\n\nclass D extends C {}\nconsole.log(new C() instanceof D); // false\nconsole.log(new C() instanceof C); // true\nconsole.log({ __proto__: C.prototype } instanceof C); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
instanceof11215414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof\n

\n
\n", + "operators/in": "

in

The in operator returns true if the specified property is in the specified object or its prototype chain.

\n

Try it

\n

Syntax

\n
\n

js

\n
prop in object\n#prop in object\n
\n

Parameters

\n
prop

A string or symbol representing a property name (non-symbols will be coerced to strings). Can also be a private property identifier.

object

Object to check if it (or its prototype chain) contains the property with specified name (prop).

Exceptions

\n
TypeError

Thrown if object is not an object (i.e. a primitive).

Description

\n
\n

The in operator tests if a string or symbol property is present in an object or its prototype chain. If you want to check for only non-inherited properties, use Object.hasOwn() instead.

A property may be present in an object but have value undefined. Therefore, x in obj is not the same as obj.x !== undefined. To make in return false after a property is added, use the delete operator instead of setting that property's value to undefined.

You can also use the in operator to check whether a particular private class field or method has been defined in an object. The operator returns true if the property is defined, and false otherwise. This is known as a branded check, because it returns true if and only if the object was created with that class constructor, after which you can safely access other private properties as well.

This is a special syntax — the left-hand side of the in operator is a property identifier instead of an expression, but unquoted (because otherwise it's a string property, not a private property).

Because accessing private properties on objects unrelated to the current class throws a TypeError instead of returning undefined, this syntax allows you to shorten:

\n

js

\n
class C {\n  #x;\n  static isC(obj) {\n    try {\n      obj.#x;\n      return true;\n    } catch {\n      return false;\n    }\n  }\n}\n
\n

To:

\n

js

\n
class C {\n  #x;\n  static isC(obj) {\n    return #x in obj;\n  }\n}\n
\n

It also generally avoids the need for dealing with error handling just to access a private property that may be nonexistent.

However, the in operator still requires the private property to be declared beforehand in the enclosing class — otherwise, it would throw a SyntaxError (\"Private field '#x' must be declared in an enclosing class\"), the same one as when you try to access an undeclared private property.

\n

js

\n
class C {\n  foo() {\n    #x in this;\n  }\n}\n\nnew C().foo(); // SyntaxError: Private field '#x' must be declared in an enclosing class\n
\n
\n

Examples

\n

Basic usage

\n
\n

The following examples show some uses of the in operator.

\n

js

\n
// Arrays\nconst trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\n0 in trees; // returns true\n3 in trees; // returns true\n6 in trees; // returns false\n\"bay\" in trees; // returns false (you must specify the index number, not the value at that index)\n\"length\" in trees; // returns true (length is an Array property)\nSymbol.iterator in trees; // returns true\n\n// Predefined objects\n\"PI\" in Math; // returns true\n\n// Custom objects\nconst mycar = { make: \"Honda\", model: \"Accord\", year: 1998 };\n\"make\" in mycar; // returns true\n\"model\" in mycar; // returns true\n
\n

You must specify an object on the right side of the in operator. For example, you can specify a string created with the String constructor, but you cannot specify a string literal.

\n

js

\n
const color1 = new String(\"green\");\n\"length\" in color1; // returns true\n\nconst color2 = \"coral\";\n// generates an error (color2 is not a String object)\n\"length\" in color2;\n
\n
\n

Using the in operator with deleted or undefined properties

\n
\n

If you delete a property with the delete operator, the in operator returns false for that property.

\n

js

\n
const mycar = { make: \"Honda\", model: \"Accord\", year: 1998 };\ndelete mycar.make;\n\"make\" in mycar; // returns false\n\nconst trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ndelete trees[3];\n3 in trees; // returns false\n
\n

If you set a property to undefined but do not delete it, the in operator returns true for that property.

\n

js

\n
const mycar = { make: \"Honda\", model: \"Accord\", year: 1998 };\nmycar.make = undefined;\n\"make\" in mycar; // returns true\n
\n
\n

js

\n
const trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ntrees[3] = undefined;\n3 in trees; // returns true\n
\n

The in operator will return false for empty array slots, even if accessing it directly returns undefined.

\n

js

\n
const empties = new Array(3);\nempties[2]; // returns undefined\n2 in empties; // returns false\n
\n

To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array.

\n

js

\n
const empties = new Array(3).fill(undefined);\n2 in empties; // returns true\n
\n
\n

Inherited properties

\n
\n

The in operator returns true for properties in the prototype chain. This may be undesirable if you are using objects to store arbitrary key-value pairs.

\n

js

\n
const ages = { alice: 18, bob: 27 };\n\nfunction hasPerson(name) {\n  return name in ages;\n}\n\nhasPerson(\"hasOwnProperty\"); // true\n
\n

You can use Object.hasOwn() to check if the object has the key.

\n

js

\n
const ages = { alice: 18, bob: 27 };\n\nfunction hasPerson(name) {\n  return Object.hasOwn(ages, name);\n}\n\nhasPerson(\"hasOwnProperty\"); // false\n
\n

Alternatively, you should consider using a null prototype object or a Map for storing ages, to avoid other bugs.

\n

js

\n
const ages = new Map([\n  [\"alice\", 18],\n  [\"bob\", 27],\n]);\n\nfunction hasPerson(name) {\n  return ages.has(name);\n}\n\nhasPerson(\"hasOwnProperty\"); // false\n
\n
\n

Using the in operator to implement branded checks

\n
\n

The code fragment below demonstrates a static function that tells if an object was created with the Person constructor and therefore can perform other methods safely.

\n

js

\n
class Person {\n  #age;\n  constructor(age) {\n    this.#age = age;\n  }\n  static isPerson(o) {\n    return #age in o;\n  }\n  ageDifference(other) {\n    return this.#age - other.#age;\n  }\n}\n\nconst p1 = new Person(20);\nconst p2 = new Person(30);\nconsole.log(p1.ageDifference(p2)); // -10\nconsole.log(Person.isPerson(p1)); // true\n\nif (Person.isPerson(p1) && Person.isPerson(p2)) {\n  console.log(p1.ageDifference(p2)); // -10\n}\n
\n

It helps to prevent the following case:

\n

js

\n
const p2 = {};\n\np1.ageDifference(p2); // TypeError: Cannot read private member #age from an object whose class did not declare it\n
\n

Without the in operator, you would have to use a try...catch block to check if the object has the private property.

You can also implement this as a @@hasInstance method of the class, so that you can use the instanceof operator to perform the same check (which, by default, only checks for the existence of Person.prototype in the object's prototype chain).

\n

js

\n
class Person {\n  #age;\n  constructor(age) {\n    this.#age = age;\n  }\n  static [Symbol.hasInstance](o) {\n    // Testing `this` to prevent false-positives when\n    // calling `instanceof SubclassOfPerson`\n    return this === Person && #age in o;\n  }\n  ageDifference(other) {\n    return this.#age - other.#age;\n  }\n}\n\nconst p1 = new Person(20);\nconst p2 = new Person(30);\n\nif (p1 instanceof Person && p2 instanceof Person) {\n  console.log(p1.ageDifference(p2)); // -10\n}\n
\n

For more examples, see Private class features and the class guide.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-relational-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
in11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\n

\n
\n", + "operators/equality": "

Equality (==)

The == operator checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.

\n

Try it

\n

Syntax

\n
\n

js

\n
x == y\n
\n

Description

\n
\n

The equality operators (== and !=) provide the IsLooselyEqual semantic. This can be roughly summarized as follows:

  1. If the operands have the same type, they are compared as follows:
    • Object: return true only if both operands reference the same object.
    • String: return true only if both operands have the same characters in the same order.
    • Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false; so, NaN is never equal to NaN.
    • Boolean: return true only if operands are both true or both false.
    • BigInt: return true only if both operands have the same value.
    • Symbol: return true only if both operands reference the same symbol.
  2. If one of the operands is null or undefined, the other must also be null or undefined to return true. Otherwise return false.
  3. If one of the operands is an object and the other is a primitive, convert the object to a primitive.
  4. At this step, both operands are converted to primitives (one of String, Number, Boolean, Symbol, and BigInt). The rest of the conversion is done case-by-case.
    • If they are of the same type, compare them using step 1.
    • If one of the operands is a Symbol but the other is not, return false.
    • If one of the operands is a Boolean but the other is not, convert the boolean to a number: true is converted to 1, and false is converted to 0. Then compare the two operands loosely again.
    • Number to String: convert the string to a number. Conversion failure results in NaN, which will guarantee the equality to be false.
    • Number to BigInt: compare by their numeric value. If the number is ±Infinity or NaN, return false.
    • String to BigInt: convert the string to a BigInt using the same algorithm as the BigInt() constructor. If conversion fails, return false.

Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions).

The most notable difference between this operator and the strict equality (===) operator is that the strict equality operator does not attempt type conversion. Instead, the strict equality operator always considers operands of different types to be different. The strict equality operator essentially carries out only step 1, and then returns false for all other cases.

There's a \"willful violation\" of the above algorithm: if one of the operands is document.all, it is treated as if it's undefined. This means that document.all == null is true, but document.all === undefined && document.all === null is false.

\n

Examples

\n

Comparison with no type conversion

\n
\n

js

\n
1 == 1; // true\n\"hello\" == \"hello\"; // true\n
\n

Comparison with type conversion

\n
\n

js

\n
\"1\" == 1; // true\n1 == \"1\"; // true\n0 == false; // true\n0 == null; // false\n0 == undefined; // false\n0 == !!null; // true, look at Logical NOT operator\n0 == !!undefined; // true, look at Logical NOT operator\nnull == undefined; // true\n\nconst number1 = new Number(3);\nconst number2 = new Number(3);\nnumber1 == 3; // true\nnumber1 == number2; // false\n
\n

Comparison of objects

\n
\n

js

\n
const object1 = {\n  key: \"value\",\n};\n\nconst object2 = {\n  key: \"value\",\n};\n\nconsole.log(object1 == object2); // false\nconsole.log(object1 == object1); // true\n
\n

Comparing strings and String objects

\n
\n

Note that strings constructed using new String() are objects. If you compare one of these with a string literal, the String object will be converted to a string literal and the contents will be compared. However, if both operands are String objects, then they are compared as objects and must reference the same object for comparison to succeed:

\n

js

\n
const string1 = \"hello\";\nconst string2 = String(\"hello\");\nconst string3 = new String(\"hello\");\nconst string4 = new String(\"hello\");\n\nconsole.log(string1 == string2); // true\nconsole.log(string1 == string3); // true\nconsole.log(string2 == string3); // true\nconsole.log(string3 == string4); // false\nconsole.log(string4 == string4); // true\n
\n
\n

Comparing Dates and strings

\n
\n

js

\n
const d = new Date(\"1995-12-17T03:24:00\");\nconst s = d.toString(); // for example: \"Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)\"\nconsole.log(d == s); //true\n
\n

Comparing arrays and strings

\n
\n

js

\n
const a = [1, 2, 3];\nconst b = \"1,2,3\";\na == b; // true, `a` converts to string\n\nconst c = [true, 0.5, \"hey\"];\nconst d = c.toString(); // \"true,0.5,hey\"\nc == d; // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-equality-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Equality11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality\n

\n
\n", + "operators/inequality": "

Inequality (!=)

The != operator checks whether its two operands are not equal, returning a Boolean result. Unlike the strict inequality operator, it attempts to convert and compare operands that are of different types.

\n

Try it

\n

Syntax

\n
\n

js

\n
x != y\n
\n

Description

\n
\n

The inequality operator checks whether its operands are not equal. It is the negation of the equality operator so the following two lines will always give the same result:

\n

js

\n
x != y;\n\n!(x == y);\n
\n

For details of the comparison algorithm, see the page for the equality operator.

Like the equality operator, the inequality operator will attempt to convert and compare operands of different types:

\n

js

\n
3 != \"3\"; // false\n
\n

To prevent this, and require that different types are considered to be different, use the strict inequality operator instead:

\n

js

\n
3 !== \"3\"; // true\n
\n
\n

Examples

\n

Comparison with no type conversion

\n
\n

js

\n
1 != 2; // true\n\"hello\" != \"hola\"; // true\n\n1 != 1; // false\n\"hello\" != \"hello\"; // false\n
\n

Comparison with type conversion

\n
\n

js

\n
\"1\" != 1; // false\n1 != \"1\"; // false\n0 != false; // false\n0 != null; // true\n0 != undefined; // true\n0 != !!null; // false, look at Logical NOT operator\n0 != !!undefined; // false, look at Logical NOT operator\nnull != undefined; // false\n\nconst number1 = new Number(3);\nconst number2 = new Number(3);\nnumber1 != 3; // false\nnumber1 != number2; // true\n
\n

Comparison of objects

\n
\n

js

\n
const object1 = {\n  key: \"value\",\n};\n\nconst object2 = {\n  key: \"value\",\n};\n\nconsole.log(object1 != object2); // true\nconsole.log(object1 != object1); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-equality-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Inequality11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality\n

\n
\n", + "operators/strict_equality": "

Strict equality (===)

The === operator checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

\n

Try it

\n

Syntax

\n
\n

js

\n
x === y\n
\n

Description

\n
\n

The strict equality operators (=== and !==) provide the IsStrictlyEqual semantic.

The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing.

\n

Examples

\n

Comparing operands of the same type

\n
\n

js

\n
\"hello\" === \"hello\"; // true\n\"hello\" === \"hola\"; // false\n\n3 === 3; // true\n3 === 4; // false\n\ntrue === true; // true\ntrue === false; // false\n\nnull === null; // true\n
\n

Comparing operands of different types

\n
\n

js

\n
\"3\" === 3; // false\ntrue === 1; // false\nnull === undefined; // false\n3 === new Number(3); // false\n
\n

Comparing objects

\n
\n

js

\n
const object1 = {\n  key: \"value\",\n};\n\nconst object2 = {\n  key: \"value\",\n};\n\nconsole.log(object1 === object2); // false\nconsole.log(object1 === object1); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-equality-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Strict_equality11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\n

\n
\n", + "operators/strict_inequality": "

Strict inequality (!==)

The !== operator checks whether its two operands are not equal, returning a Boolean result. Unlike the inequality operator, the strict inequality operator always considers operands of different types to be different.

\n

Try it

\n

Syntax

\n
\n

js

\n
x !== y\n
\n

Description

\n
\n

The strict inequality operator checks whether its operands are not equal. It is the negation of the strict equality operator so the following two lines will always give the same result:

\n

js

\n
x !== y;\n\n!(x === y);\n
\n

For details of the comparison algorithm, see the page for the strict equality operator.

Like the strict equality operator, the strict inequality operator will always consider operands of different types to be different:

\n

js

\n
3 !== \"3\"; // true\n
\n
\n

Examples

\n

Comparing operands of the same type

\n
\n

js

\n
\"hello\" !== \"hello\"; // false\n\"hello\" !== \"hola\"; // true\n\n3 !== 3; // false\n3 !== 4; // true\n\ntrue !== true; // false\ntrue !== false; // true\n\nnull !== null; // false\n
\n

Comparing operands of different types

\n
\n

js

\n
\"3\" !== 3; // true\ntrue !== 1; // true\nnull !== undefined; // true\n
\n

Comparing objects

\n
\n

js

\n
const object1 = {\n  key: \"value\",\n};\n\nconst object2 = {\n  key: \"value\",\n};\n\nconsole.log(object1 !== object2); // true\nconsole.log(object1 !== object1); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-equality-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Strict_inequality11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\n

\n
\n", + "operators/left_shift": "

Left shift (<<)

The << operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.

\n

Try it

\n

Syntax

\n
\n

js

\n
x << y\n
\n

Description

\n
\n

The << operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt left shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number left shift. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the left operand's bit representation in two's complement. For example, 9 << 2 yields 36:

     9 (base 10): 00000000000000000000000000001001 (base 2)\n                  --------------------------------\n9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)\n

Bitwise a 32-bit integer x to the left by y bits yields x * 2 ** y. So for example, 9 << 3 is equivalent to 9 * (2 ** 3) = 9 * (8) = 72.

If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 << 32 is the same as 100 << 0 (and produces 100) because 32 modulo 32 is 0.

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Left shifting any number x by 0 returns x converted to a 32-bit integer. Do not use << 0 to truncate numbers to integers; use Math.trunc() instead.

\n

Examples

\n

Using left shift

\n
\n

js

\n
9 << 3; // 72\n\n// 9 * (2 ** 3) = 9 * (8) = 72\n\n9n << 3n; // 72n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-left-shift-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Left_shift11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift\n

\n
\n", + "operators/right_shift": "

Right shift (>>)

The >> operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and copies of the leftmost bit are shifted in from the left. This operation is also called \"sign-propagating right shift\" or \"arithmetic right shift\", because the sign of the resulting number is the same as the sign of the first operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x >> y\n
\n

Description

\n
\n

The >> operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt right shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number right shift. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name \"sign-propagating\".

The operator operates on the left operand's bit representation in two's complement. Consider the 32-bit binary representations of the decimal (base 10) numbers 9 and -9:

     9 (base 10): 00000000000000000000000000001001 (base 2)\n    -9 (base 10): 11111111111111111111111111110111 (base 2)\n

The binary representation under two's complement of the negative decimal (base 10) number -9 is formed by inverting all the bits of its opposite number, which is 9 and 00000000000000000000000000001001 in binary, and adding 1.

In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9, the leftmost bit of the binary representation is 0, and for the negative decimal number -9, the leftmost bit of the binary representation is 1.

Given those binary representations of the decimal (base 10) numbers 9, and -9:

9 >> 2 yields 2:

     9 (base 10): 00000000000000000000000000001001 (base 2)\n                  --------------------------------\n9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)\n

Notice how two rightmost bits, 01, have been shifted off, and two copies of the leftmost bit, 0 have been shifted in from the left.

-9 >> 2 yields -3:

     -9 (base 10): 11111111111111111111111111110111 (base 2)\n                   --------------------------------\n-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)\n

Notice how two rightmost bits, 11, have been shifted off. But as far as the leftmost bits: in this case, the leftmost bit is 1. So two copies of that leftmost 1 bit have been shifted in from the left — which preserves the negative sign.

The binary representation 11111111111111111111111111111101 is equal to the negative decimal (base 10) number -3, because all negative integers are stored as two's complements, and this one can be calculated by inverting all the bits of the binary representation of the positive decimal (base 10) number 3, which is 00000000000000000000000000000011, and then adding one.

If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 >> 32 is the same as 100 >> 0 (and produces 100) because 32 modulo 32 is 0.

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Right shifting any number x by 0 returns x converted to a 32-bit integer. Do not use >> 0 to truncate numbers to integers; use Math.trunc() instead.

\n

Examples

\n

Using right shift

\n
\n

js

\n
9 >> 2; // 2\n-9 >> 2; // -3\n\n9n >> 2n; // 2n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-signed-right-shift-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Right_shift11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift\n

\n
\n", + "operators/unsigned_right_shift": "

Unsigned right shift (>>>)

The >>> operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called \"zero-filling right shift\", because the sign bit becomes 0, so the resulting number is always positive. Unsigned right shift does not accept BigInt values.

\n

Try it

\n

Syntax

\n
\n

js

\n
x >>> y\n
\n

Description

\n
\n

Unlike other arithmetic and bitwise operators, the unsigned right shift operator does not accept BigInt values. This is because it fills the leftmost bits with zeroes, but conceptually, BigInts have an infinite number of leading sign bits, so there's no \"leftmost bit\" to fill with zeroes.

The operator operates on the left operand's bit representation in two's complement. Consider the 32-bit binary representations of the decimal (base 10) numbers 9 and -9:

     9 (base 10): 00000000000000000000000000001001 (base 2)\n    -9 (base 10): 11111111111111111111111111110111 (base 2)\n

The binary representation under two's complement of the negative decimal (base 10) number -9 is formed by inverting all the bits of its opposite number, which is 9 and 00000000000000000000000000001001 in binary, and adding 1.

In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9, the leftmost bit of the binary representation is 0, and for the negative decimal number -9, the leftmost bit of the binary representation is 1.

Given those binary representations of the decimal (base 10) numbers 9, and -9:

For the positive number 9, zero-fill right shift and sign-propagating right shift yield the same result: 9 >>> 2 yields 2, the same as 9 >> 2:

      9 (base 10): 00000000000000000000000000001001 (base 2)\n                   --------------------------------\n9 >>  2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)\n9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)\n

Notice how two rightmost bits, 01, have been shifted off, and two zeroes have been shifted in from the left.

However, notice what happens for -9: -9 >> 2 (sign-propagating right shift) yields -3, but -9 >>> 2 (zero-fill right shift) yields 1073741821:

      -9 (base 10): 11111111111111111111111111110111 (base 2)\n                    --------------------------------\n-9 >>  2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)\n-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)\n

Notice how two rightmost bits, 11, have been shifted off. For -9 >> 2 (sign-propagating right shift), two copies of the leftmost 1 bit have been shifted in from the left, which preserves the negative sign. On the other hand, for -9 >>> 2 (zero-fill right shift), zeroes have instead been shifted in from the left, so the negative sign of the number is not preserved, and the result is instead a (large) positive number.

If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 >>> 32 is the same as 100 >>> 0 (and produces 100) because 32 modulo 32 is 0.

\n

Examples

\n

Using unsigned right shift

\n
\n
\n

js

\n
9 >>> 2; // 2\n-9 >>> 2; // 1073741821\n
\n

Unsigned right shift doesn't work with BigInts.

\n

js

\n
9n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >> instead\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-unsigned-right-shift-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Unsigned_right_shift11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift\n

\n
\n", + "operators/bitwise_and": "

Bitwise AND (&)

The & operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of both operands are 1.

\n

Try it

\n

Syntax

\n
\n

js

\n
x & y\n
\n

Description

\n
\n

The & operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt AND if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise AND. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the operands' bit representations in two's complement. Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The truth table for the AND operation is:

x y x AND y
0 0 0
0 1 0
1 0 0
1 1 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)\n    14 (base 10) = 00000000000000000000000000001110 (base 2)\n                   --------------------------------\n14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)\n

Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Bitwise ANDing any number x with -1 returns x converted to a 32-bit integer. Do not use & -1 to truncate numbers to integers; use Math.trunc() instead.

\n

Examples

\n

Using bitwise AND

\n
\n

js

\n
// 9  (00000000000000000000000000001001)\n// 14 (00000000000000000000000000001110)\n\n14 & 9;\n// 8  (00000000000000000000000000001000)\n\n14n & 9n; // 8n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-BitwiseANDExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_AND11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND\n

\n
\n", + "operators/bitwise_or": "

Bitwise OR (|)

The | operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either or both operands are 1.

\n

Try it

\n

Syntax

\n
\n

js

\n
x | y\n
\n

Description

\n
\n

The | operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt OR if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise OR. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the operands' bit representations in two's complement. Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The truth table for the OR operation is:

x y x OR y
0 0 0
0 1 1
1 0 1
1 1 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)\n    14 (base 10) = 00000000000000000000000000001110 (base 2)\n                   --------------------------------\n14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)\n

Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Bitwise ORing any number x with 0 returns x converted to a 32-bit integer. Do not use | 0 to truncate numbers to integers; use Math.trunc() instead.

\n

Examples

\n

Using bitwise OR

\n
\n

js

\n
// 9  (00000000000000000000000000001001)\n// 14 (00000000000000000000000000001110)\n\n14 | 9;\n// 15 (00000000000000000000000000001111)\n\n14n | 9n; // 15n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-BitwiseORExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_OR11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR\n

\n
\n", + "operators/bitwise_xor": "

Bitwise XOR (^)

The ^ operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either but not both operands are 1.

\n

Try it

\n

Syntax

\n
\n

js

\n
x ^ y\n
\n

Description

\n
\n

The ^ operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt XOR if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise XOR. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the operands' bit representations in two's complement. Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The truth table for the XOR operation is:

x y x XOR y
0 0 0
0 1 1
1 0 1
1 1 0
     9 (base 10) = 00000000000000000000000000001001 (base 2)\n    14 (base 10) = 00000000000000000000000000001110 (base 2)\n                   --------------------------------\n14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)\n

Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001\nAfter:              10100000000000000110000000000001\n

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Bitwise XORing any number x with 0 returns x converted to a 32-bit integer. Do not use ^ 0 to truncate numbers to integers; use Math.trunc() instead.

\n

Examples

\n

Using bitwise XOR

\n
\n

js

\n
// 9  (00000000000000000000000000001001)\n// 14 (00000000000000000000000000001110)\n\n14 ^ 9;\n// 7  (00000000000000000000000000000111)\n\n14n ^ 9n; // 7n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-BitwiseXORExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_XOR11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR\n

\n
\n", + "operators/logical_and": "

Logical AND (&&)

\n

The && (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true. Otherwise it will be false.

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
x && y\n
\n

Description

\n
\n

Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

Examples of expressions that can be converted to false are:

The AND operator preserves non-Boolean values and returns them as they are:

\n

js

\n
result = \"\" && \"foo\"; // result is assigned \"\" (empty string)\nresult = 2 && 0; // result is assigned 0\nresult = \"foo\" && 4; // result is assigned 4\n
\n

Even though the && operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.

\n

Short-circuit evaluation

\n
\n

The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false, the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.

Consider the pseudocode below.

(some falsy expression) && expr\n

The expr part is never evaluated because the first operand (some falsy expression) is evaluated as falsy. If expr is a function, the function is never called. See the example below:

\n

js

\n
function A() {\n  console.log(\"called A\");\n  return false;\n}\nfunction B() {\n  console.log(\"called B\");\n  return true;\n}\n\nconsole.log(A() && B());\n// Logs \"called A\" to the console due to the call for function A,\n// && evaluates to false (function A returns false), then false is logged to the console;\n// the AND operator short-circuits here and ignores function B\n
\n
\n

Operator precedence

\n
\n

The AND operator has a higher precedence than the OR operator, meaning the && operator is executed before the || operator (see operator precedence).

\n

js

\n
true || false && false; // true\ntrue && (false || false); // false\n(2 === 3) || (4 < 0) && (1 === 1); // false\n
\n
\n

Examples

\n

Using AND

\n
\n

The following code shows examples of the && (logical AND) operator.

\n

js

\n
a1 = true && true; // t && t returns true\na2 = true && false; // t && f returns false\na3 = false && true; // f && t returns false\na4 = false && 3 === 4; // f && f returns false\na5 = \"Cat\" && \"Dog\"; // t && t returns \"Dog\"\na6 = false && \"Cat\"; // f && t returns false\na7 = \"Cat\" && false; // t && f returns false\na8 = \"\" && false; // f && f returns \"\"\na9 = false && \"\"; // f && f returns false\n
\n
\n

Conversion rules for booleans

\n
\n

Converting AND to OR

The following operation involving booleans:

\n

js

\n
bCondition1 && bCondition2\n
\n

is always equal to:

\n

js

\n
!(!bCondition1 || !bCondition2)\n
\n

Converting OR to AND

The following operation involving booleans:

\n

js

\n
bCondition1 || bCondition2\n
\n

is always equal to:

\n

js

\n
!(!bCondition1 && !bCondition2)\n
\n
\n

Removing nested parentheses

\n
\n

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.

The following composite operation involving booleans:

\n

js

\n
bCondition1 || (bCondition2 && bCondition3)\n
\n

is always equal to:

\n

js

\n
bCondition1 || bCondition2 && bCondition3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-LogicalANDExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Logical_AND11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND\n

\n
\n", + "operators/logical_or": "

Logical OR (||)

The || (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

\n

Try it

\n

Syntax

\n
\n

js

\n
x || y\n
\n

Description

\n
\n

If x can be converted to true, returns x; else, returns y.

If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

Examples of expressions that can be converted to false are:

Even though the || operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean() constructor.

\n

Short-circuit evaluation

\n
\n

The logical OR expression is evaluated left to right, it is tested for possible \"short-circuit\" evaluation using the following rule:

(some truthy expression) || expr is short-circuit evaluated to the truthy expression.

Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:

\n

js

\n
function A() {\n  console.log(\"called A\");\n  return false;\n}\nfunction B() {\n  console.log(\"called B\");\n  return true;\n}\n\nconsole.log(B() || A());\n// Logs \"called B\" due to the function call,\n// then logs true (which is the resulting value of the operator)\n
\n
\n

Operator precedence

\n
\n

The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).

\n

js

\n
true || false && false; // returns true, because && is executed first\n(true || false) && false; // returns false, because grouping has the highest precedence\n
\n
\n

Examples

\n

Using OR

\n
\n

The following code shows examples of the || (logical OR) operator.

\n

js

\n
true || true; // t || t returns true\nfalse || true; // f || t returns true\ntrue || false; // t || f returns true\nfalse || 3 === 4; // f || f returns false\n\"Cat\" || \"Dog\"; // t || t returns \"Cat\"\nfalse || \"Cat\"; // f || t returns \"Cat\"\n\"Cat\" || false; // t || f returns \"Cat\"\n\"\" || false; // f || f returns false\nfalse || \"\"; // f || f returns \"\"\nfalse || varObject; // f || object returns varObject\n
\n

Note: If you use this operator to provide a default value to some variable, be aware that any falsy value will not be used. If you only need to filter out null or undefined, consider using the nullish coalescing operator.

\n

Conversion rules for booleans

\n
\n

Converting AND to OR

The following operation involving booleans:

\n

js

\n
bCondition1 && bCondition2\n
\n

is always equal to:

\n

js

\n
!(!bCondition1 || !bCondition2)\n
\n

Converting OR to AND

The following operation involving booleans:

\n

js

\n
bCondition1 || bCondition2\n
\n

is always equal to:

\n

js

\n
!(!bCondition1 && !bCondition2)\n
\n
\n

Removing nested parentheses

\n
\n

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules.

The following composite operation involving booleans:

\n

js

\n
bCondition1 && (bCondition2 || bCondition3)\n
\n

is always equal to:

\n

js

\n
!(!bCondition1 || !bCondition2 && !bCondition3)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-LogicalORExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Logical_OR11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR\n

\n
\n", + "operators/nullish_coalescing": "

Nullish coalescing operator (??)

The ?? operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
leftExpr ?? rightExpr\n
\n

Description

\n
\n

The nullish coalescing operator can be seen as a special case of the logical OR (||) operator. The latter returns the right-hand side operand if the left operand is any falsy value, not only null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., '' or 0). See below for more examples.

The nullish coalescing operator has the fifth-lowest operator precedence, directly lower than || and directly higher than the conditional (ternary) operator.

It is not possible to combine both the AND (&&) and OR operators (||) directly with ??. A syntax error will be thrown in such cases.

\n

js

\n
null || undefined ?? \"foo\"; // raises a SyntaxError\ntrue && undefined ?? \"foo\"; // raises a SyntaxError\n
\n

Instead, provide parenthesis to explicitly indicate precedence:

\n

js

\n
(null || undefined) ?? \"foo\"; // returns \"foo\"\n
\n
\n

Examples

\n

Using the nullish coalescing operator

\n
\n

In this example, we will provide default values but keep values other than null or undefined.

\n

js

\n
const nullValue = null;\nconst emptyText = \"\"; // falsy\nconst someNumber = 42;\n\nconst valA = nullValue ?? \"default for A\";\nconst valB = emptyText ?? \"default for B\";\nconst valC = someNumber ?? 0;\n\nconsole.log(valA); // \"default for A\"\nconsole.log(valB); // \"\" (as the empty string is not null or undefined)\nconsole.log(valC); // 42\n
\n
\n

Assigning a default value to a variable

\n
\n

Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||):

\n

js

\n
let foo;\n\n// foo is never assigned any value so it is still undefined\nconst someDummyText = foo || \"Hello!\";\n
\n

However, due to || being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0, '', NaN, false, etc.) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values.

\n

js

\n
const count = 0;\nconst text = \"\";\n\nconst qty = count || 42;\nconst message = text || \"hi!\";\nconsole.log(qty); // 42 and not 0\nconsole.log(message); // \"hi!\" and not \"\"\n
\n

The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values):

\n

js

\n
const myText = \"\"; // An empty string (which is also a falsy value)\n\nconst notFalsyText = myText || \"Hello world\";\nconsole.log(notFalsyText); // Hello world\n\nconst preservingFalsy = myText ?? \"Hi neighborhood\";\nconsole.log(preservingFalsy); // '' (as myText is neither undefined nor null)\n
\n
\n

Short-circuiting

\n
\n

Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined.

\n

js

\n
function a() {\n  console.log(\"a was called\");\n  return undefined;\n}\nfunction b() {\n  console.log(\"b was called\");\n  return false;\n}\nfunction c() {\n  console.log(\"c was called\");\n  return \"foo\";\n}\n\nconsole.log(a() ?? c());\n// Logs \"a was called\" then \"c was called\" and then \"foo\"\n// as a() returned undefined so both expressions are evaluated\n\nconsole.log(b() ?? c());\n// Logs \"b was called\" then \"false\"\n// as b() returned false (and not null or undefined), the right\n// hand side expression was not evaluated\n
\n
\n

Relationship with the optional chaining operator (?.)

\n
\n

The nullish coalescing operator treats undefined and null as specific values. So does the optional chaining operator (?.), which is useful to access a property of an object which may be null or undefined. Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.

\n

js

\n
const foo = { someFooProp: \"hi\" };\n\nconsole.log(foo.someFooProp?.toUpperCase() ?? \"not available\"); // \"HI\"\nconsole.log(foo.someBarProp?.toUpperCase() ?? \"not available\"); // \"not available\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-CoalesceExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Nullish_coalescing808072No6713.18080795713.413.01.014.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing\n

\n
\n", + "operators/conditional_operator": "

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.

\n

Try it

\n

Syntax

\n
\n

js

\n
condition ? exprIfTrue : exprIfFalse\n
\n

Parameters

\n
condition

An expression whose value is used as a condition.

exprIfTrue

An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true).

exprIfFalse

An expression which is executed if the condition is falsy (that is, has a value which can be converted to false).

Description

\n

Besides false, possible falsy expressions are: null, NaN, 0, the empty string (\"\"), and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse.

Examples

\n

A simple example

\n
\n

js

\n
const age = 26;\nconst beverage = age >= 21 ? \"Beer\" : \"Juice\";\nconsole.log(beverage); // \"Beer\"\n
\n

Handling null values

\n
\n

One common usage is to handle a value that may be null:

\n

js

\n
const greeting = (person) => {\n  const name = person ? person.name : \"stranger\";\n  return `Howdy, ${name}`;\n};\n\nconsole.log(greeting({ name: \"Alice\" })); // \"Howdy, Alice\"\nconsole.log(greeting(null)); // \"Howdy, stranger\"\n
\n
\n

Conditional chains

\n
\n

The ternary operator is right-associative, which means it can be \"chained\" in the following way, similar to an if … else if … else if … else chain:

\n

js

\n
function example() {\n  return condition1 ? value1\n    : condition2 ? value2\n    : condition3 ? value3\n    : value4;\n}\n
\n

This is equivalent to the following if...else chain.

\n

js

\n
function example() {\n  if (condition1) {\n    return value1;\n  } else if (condition2) {\n    return value2;\n  } else if (condition3) {\n    return value3;\n  } else {\n    return value4;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-conditional-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Conditional_operator11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\n

\n
\n", + "operators/assignment": "

Assignment (=)

The = operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

\n

Try it

\n

Syntax

\n
\n

js

\n
x = y\n
\n

Parameters

\n
x

A valid assignment target, including an identifier or a property accessor. It can also be a destructuring assignment pattern.

y

An expression specifying the value to be assigned to x.

Return value

\n

The value of y.

Exceptions

\n
ReferenceError

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

TypeError

Thrown in strict mode if assigning to a property that is not modifiable.

Description

\n
\n

The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:

All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained together:

\n

js

\n
const x = y = 5;\n
\n

This is equivalent to:

\n

js

\n
const x = (y = 5);\n
\n

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5, and x is initialized with the value of the y = 5 expression, which is also 5. If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode, or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

\n

js

\n
const x = 5,\n  y = 5;\n
\n
\n

Examples

\n

Simple assignment and chaining

\n
\n

js

\n
let x = 5;\nlet y = 10;\nlet z = 25;\n\nx = y; // x is 10\nx = y = z; // x, y and z are all 25\n
\n

Value of assignment expressions

\n
\n

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

\n

js

\n
let x;\nconsole.log(x); // undefined\nconsole.log(x = 2); // 2\nconsole.log(x); // 2\n
\n
\n

Unqualified identifier assignment

\n
\n

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global..

Because the global object has a String property (Object.hasOwn(globalThis, \"String\")), you can use the following code:

\n

js

\n
function foo() {\n  String(\"s\"); // The function `String` is globally available\n}\n
\n

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String; you can just type the unqualified String. To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

\n

js

\n
foo = \"f\"; // In non-strict mode, assumes you want to create a property named `foo` on the global object\nObject.hasOwn(globalThis, \"foo\"); // true\n
\n

In strict mode, assignment to an unqualified identifier in strict mode will result in a ReferenceError, to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

\n

Assignment with destructuring

\n
\n

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

\n

js

\n
const result = /(a+)(b+)(c+)/.exec(\"aaabcc\");\nlet a = \"\",\n  b = \"\",\n  c = \"\";\n[, a, b, c] = result;\nconsole.log(a, b, c); // \"aaa\" \"b\" \"cc\"\n
\n

For more information, see Destructuring assignment.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment\n

\n
\n", + "operators/multiplication_assignment": "

Multiplication assignment (*=)

The *= operator performs multiplication on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x *= y\n
\n

Description

\n

x *= y is equivalent to x = x * y, except that the expression x is only evaluated once.

Examples

\n

Using multiplication assignment

\n
\n

js

\n
let bar = 5;\n\nbar *= 2; // 10\nbar *= \"foo\"; // NaN\n\nlet foo = 3n;\nfoo *= 2n; // 6n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Multiplication_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication_assignment\n

\n
\n", + "operators/division_assignment": "

Division assignment (/=)

The /= operator performs division on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x /= y\n
\n

Description

\n

x /= y is equivalent to x = x / y, except that the expression x is only evaluated once.

Examples

\n

Using division assignment

\n
\n

js

\n
let bar = 5;\n\nbar /= 2; // 2.5\nbar /= 2; // 1.25\nbar /= 0; // Infinity\nbar /= \"foo\"; // NaN\n\nlet foo = 3n;\nfoo /= 2n; // 1n\nfoo /= 2n; // 0n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Division_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division_assignment\n

\n
\n", + "operators/remainder_assignment": "

Remainder assignment (%=)

The %= operator performs remainder on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x %= y\n
\n

Description

\n

x %= y is equivalent to x = x % y, except that the expression x is only evaluated once.

Examples

\n

Using remainder assignment

\n
\n

js

\n
let bar = 5;\n\nbar %= 2; // 1\nbar %= \"foo\"; // NaN\nbar %= 0; // NaN\n\nlet foo = 3n;\nfoo %= 2n; // 1n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Remainder_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder_assignment\n

\n
\n", + "operators/addition_assignment": "

Addition assignment (+=)

The += operator performs addition (which is either numeric addition or string concatenation) on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x += y\n
\n

Description

\n

x += y is equivalent to x = x + y, except that the expression x is only evaluated once.

Examples

\n

Using addition assignment

\n
\n
\n

js

\n
let baz = true;\n\n// Boolean + Number -> addition\nbaz += 1; // 2\n\n// Number + Boolean -> addition\nbaz += false; // 2\n
\n
\n

js

\n
let foo = \"foo\";\n\n// String + Boolean -> concatenation\nfoo += false; // \"foofalse\"\n\n// String + String -> concatenation\nfoo += \"bar\"; // \"foofalsebar\"\n
\n
\n

js

\n
let bar = 5;\n\n// Number + Number -> addition\nbar += 2; // 7\n\n// Number + String -> concatenation\nbar += \"foo\"; // \"7foo\"\n
\n
\n

js

\n
let x = 1n;\n\n// BigInt + BigInt -> addition\nx += 2n; // 3n\n\n// BigInt + Number -> throws TypeError\nx += 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Addition_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment\n

\n
\n", + "operators/subtraction_assignment": "

Subtraction assignment (-=)

The -= operator performs subtraction on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x -= y\n
\n

Description

\n

x -= y is equivalent to x = x - y, except that the expression x is only evaluated once.

Examples

\n

Using subtraction assignment

\n
\n

js

\n
let bar = 5;\n\nbar -= 2; // 3\nbar -= \"foo\"; // NaN\n\nlet foo = 3n;\nfoo -= 2n; // 1n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Subtraction_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction_assignment\n

\n
\n", + "operators/left_shift_assignment": "

Left shift assignment (<<=)

The <<= operator performs left shift on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x <<= y\n
\n

Description

\n

x <<= y is equivalent to x = x << y, except that the expression x is only evaluated once.

Examples

\n

Using left shift assignment

\n
\n

js

\n
let a = 5;\n// 00000000000000000000000000000101\n\na <<= 2; // 20\n// 00000000000000000000000000010100\n\nlet b = 5n;\nb <<= 2n; // 20n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Left_shift_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift_assignment\n

\n
\n", + "operators/right_shift_assignment": "

Right shift assignment (>>=)

The >>= operator performs right shift on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x >>= y\n
\n

Description

\n

x >>= y is equivalent to x = x >> y, except that the expression x is only evaluated once.

Examples

\n

Using right shift assignment

\n
\n

js

\n
let a = 5; //   (00000000000000000000000000000101)\na >>= 2; //   1 (00000000000000000000000000000001)\n\nlet b = -5; //  (-00000000000000000000000000000101)\nb >>= 2; //  -2 (-00000000000000000000000000000010)\n\nlet c = 5n;\nc >>= 2n; // 1n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Right_shift_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment\n

\n
\n", + "operators/unsigned_right_shift_assignment": "

Unsigned right shift assignment (>>>=)

The >>>= operator performs unsigned right shift on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x >>>= y\n
\n

Description

\n

x >>>= y is equivalent to x = x >>> y, except that the expression x is only evaluated once.

Examples

\n

Using unsigned right shift assignment

\n
\n

js

\n
let a = 5; // (00000000000000000000000000000101)\na >>>= 2; // 1 (00000000000000000000000000000001)\n\nlet b = -5; // (-00000000000000000000000000000101)\nb >>>= 2; // 1073741822 (00111111111111111111111111111110)\n\nlet c = 5n;\nc >>>= 2n; // 1n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Unsigned_right_shift_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment\n

\n
\n", + "operators/bitwise_and_assignment": "

Bitwise AND assignment (&=)

The &= operator performs bitwise AND on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x &= y\n
\n

Description

\n

x &= y is equivalent to x = x & y, except that the expression x is only evaluated once.

Examples

\n

Using bitwise AND assignment

\n
\n

js

\n
let a = 5;\n// 5:     00000000000000000000000000000101\n// 2:     00000000000000000000000000000010\na &= 2; // 0\n\nlet b = 5n;\nb &= 2n; // 0n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_AND_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment\n

\n
\n", + "operators/bitwise_xor_assignment": "

Bitwise XOR assignment (^=)

The ^= operator performs bitwise XOR on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x ^= y\n
\n

Description

\n

x ^= y is equivalent to x = x ^ y, except that the expression x is only evaluated once.

Examples

\n

Using bitwise XOR assignment

\n
\n

js

\n
let a = 5; // (00000000000000000000000000000101)\na ^= 3; // (00000000000000000000000000000011)\n\nconsole.log(a); // 6 (00000000000000000000000000000110)\n\nlet b = 5; // (00000000000000000000000000000101)\nb ^= 0; // (00000000000000000000000000000000)\n\nconsole.log(b); // 5 (00000000000000000000000000000101)\n\nlet c = 5n;\nc ^= 3n;\nconsole.log(c); // 6n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_XOR_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment\n

\n
\n", + "operators/bitwise_or_assignment": "

Bitwise OR assignment (|=)

The |= operator performs bitwise OR on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x |= y\n
\n

Description

\n

x |= y is equivalent to x = x | y, except that the expression x is only evaluated once.

Examples

\n

Using bitwise OR assignment

\n
\n

js

\n
let a = 5;\na |= 2; // 7\n// 5: 00000000000000000000000000000101\n// 2: 00000000000000000000000000000010\n// -----------------------------------\n// 7: 00000000000000000000000000000111\n\nlet b = 5n;\nb |= 2n; // 7n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Bitwise_OR_assignment11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment\n

\n
\n", + "operators/exponentiation_assignment": "

Exponentiation assignment (**=)

The **= operator performs exponentiation on the two operands and assigns the result to the left operand.

\n

Try it

\n

Syntax

\n
\n

js

\n
x **= y\n
\n

Description

\n

x **= y is equivalent to x = x ** y, except that the expression x is only evaluated once.

Examples

\n

Using exponentiation assignment

\n
\n

js

\n
let bar = 5;\n\nbar **= 2; // 25\nbar **= \"foo\"; // NaN\n\nlet foo = 3n;\nfoo **= 2n; // 9n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Exponentiation_assignment521452No3910.15152524110.36.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation_assignment\n

\n
\n", + "operators/logical_and_assignment": "

Logical AND assignment (&&=)

The &&= operator only evaluates the right operand and assigns to the left if the left operand is truthy.

\n

Try it

\n

Syntax

\n
\n

js

\n
x &&= y\n
\n

Description

\n
\n

Logical AND assignment short-circuits, meaning that x &&= y is equivalent to x && (x = y), except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not truthy, due to short-circuiting of the logical AND operator. For example, the following does not throw an error, despite x being const:

\n

js

\n
const x = 0;\nx &&= 2;\n
\n

Neither would the following trigger the setter:

\n

js

\n
const x = {\n  get value() {\n    return 0;\n  },\n  set value(v) {\n    console.log(\"Setter called\");\n  },\n};\n\nx.value &&= 2;\n
\n

In fact, if x is not truthy, y is not evaluated at all.

\n

js

\n
const x = 0;\nx &&= console.log(\"y evaluated\");\n// Logs nothing\n
\n
\n

Examples

\n

Using logical AND assignment

\n
\n

js

\n
let x = 0;\nlet y = 1;\n\nx &&= 0; // 0\nx &&= 1; // 0\ny &&= 1; // 1\ny &&= 0; // 0\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Logical_AND_assignment858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment\n

\n
\n", + "operators/logical_or_assignment": "

Logical OR assignment (||=)

The ||= operator only evaluates the right operand and assigns to the left if the left operand is falsy.

\n

Try it

\n

Syntax

\n
\n

js

\n
x ||= y\n
\n

Description

\n
\n

Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const:

\n

js

\n
const x = 1;\nx ||= 2;\n
\n

Neither would the following trigger the setter:

\n

js

\n
const x = {\n  get value() {\n    return 1;\n  },\n  set value(v) {\n    console.log(\"Setter called\");\n  },\n};\n\nx.value ||= 2;\n
\n

In fact, if x is not falsy, y is not evaluated at all.

\n

js

\n
const x = 1;\nx ||= console.log(\"y evaluated\");\n// Logs nothing\n
\n
\n

Examples

\n

Setting default content

\n
\n

If the \"lyrics\" element is empty, display a default value:

\n

js

\n
document.getElementById(\"lyrics\").textContent ||= \"No lyrics.\";\n
\n

Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.

Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= must be used, so that \"No lyrics.\" is displayed instead of a blank space. However, if the API returns null or undefined in case of blank content, ??= should be used instead.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Logical_OR_assignment858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment\n

\n
\n", + "operators/nullish_coalescing_assignment": "

Nullish coalescing assignment (??=)

The ??= operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null or undefined).

\n

Try it

\n

Syntax

\n
\n

js

\n
x ??= y\n
\n

Description

\n
\n

Nullish coalescing assignment short-circuits, meaning that x ??= y is equivalent to x ?? (x = y), except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const:

\n

js

\n
const x = 1;\nx ??= 2;\n
\n

Neither would the following trigger the setter:

\n

js

\n
const x = {\n  get value() {\n    return 1;\n  },\n  set value(v) {\n    console.log(\"Setter called\");\n  },\n};\n\nx.value ??= 2;\n
\n

In fact, if x is not nullish, y is not evaluated at all.

\n

js

\n
const x = 1;\nx ??= console.log(\"y evaluated\");\n// Logs nothing\n
\n
\n

Examples

\n

Using nullish coalescing assignment

\n
\n

You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??= also applies the default value if the property has value null.

\n

js

\n
function config(options) {\n  options.duration ??= 100;\n  options.speed ??= 25;\n  return options;\n}\n\nconfig({ duration: 125 }); // { duration: 125, speed: 25 }\nconfig({}); // { duration: 100, speed: 25 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-assignment-operators
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Nullish_coalescing_assignment858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment\n

\n
\n", + "operators/destructuring_assignment": "

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

\n

Try it

\n

Syntax

\n
\n

js

\n
const [a, b] = array;\nconst [a, , b] = array;\nconst [a = aDefault, b] = array;\nconst [a, b, ...rest] = array;\nconst [a, , b, ...rest] = array;\nconst [a, b, ...{ pop, push }] = array;\nconst [a, b, ...[c, d]] = array;\n\nconst { a, b } = obj;\nconst { a: a1, b: b1 } = obj;\nconst { a: a1 = aDefault, b = bDefault } = obj;\nconst { a, b, ...rest } = obj;\nconst { a: a1, b: b1, ...rest } = obj;\nconst { [key]: a } = obj;\n\nlet a, b, a1, b1, c, d, rest, pop, push;\n[a, b] = array;\n[a, , b] = array;\n[a = aDefault, b] = array;\n[a, b, ...rest] = array;\n[a, , b, ...rest] = array;\n[a, b, ...{ pop, push }] = array;\n[a, b, ...[c, d]] = array;\n\n({ a, b } = obj); // parentheses are required\n({ a: a1, b: b1 } = obj);\n({ a: a1 = aDefault, b = bDefault } = obj);\n({ a, b, ...rest } = obj);\n({ a: a1, b: b1, ...rest } = obj);\n
\n

Description

\n
\n

The object and array literal expressions provide an easy way to create ad hoc packages of data.

\n

js

\n
const x = [1, 2, 3, 4, 5];\n
\n

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

\n

js

\n
const x = [1, 2, 3, 4, 5];\nconst [y, z] = x;\nconsole.log(y); // 1\nconsole.log(z); // 2\n
\n

Similarly, you can destructure objects on the left-hand side of the assignment.

\n

js

\n
const obj = { a: 1, b: 2 };\nconst { a, b } = obj;\n// is equivalent to:\n// const a = obj.a;\n// const b = obj.b;\n
\n

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

\n

Binding and assignment

\n
\n

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern, with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword (var, let, or const). Then, each individual property must either be bound to a variable or further destructured.

\n

js

\n
const obj = { a: 1, b: { c: 2 } };\nconst {\n  a,\n  b: { c: d },\n} = obj;\n// Two variables are bound: `a` and `d`\n
\n

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let, once with const.

\n

js

\n
const obj = { a: 1, b: { c: 2 } };\nconst { a } = obj; // a is constant\nlet {\n  b: { c: d },\n} = obj; // d is re-assignable\n
\n

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let, or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

\n

js

\n
const numbers = [];\nconst obj = { a: 1, b: 2 };\n({ a: numbers[0], b: numbers[1] } = obj);\n// The properties `a` and `b` are assigned to properties of `numbers`\n
\n

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements. However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 }.

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

\n

js

\n
const numbers = [];\nconst obj = { a: 1, b: 2 };\nconst { a: numbers[0], b: numbers[1] } = obj;\n\n// This is equivalent to:\n//   const numbers[0] = obj.a;\n//   const numbers[1] = obj.b;\n// Which definitely is not valid.\n
\n

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *=.

\n

Default value

\n
\n

Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined. It is not used if the property has value null.

\n

js

\n
const [a = 1] = []; // a is 1\nconst { b = 2 } = { b: undefined }; // b is 2\nconst { c = 2 } = { c: null }; // c is null\n
\n

The default value can be any expression. It will only be evaluated when necessary.

\n

js

\n
const { b = console.log(\"hey\") } = { b: 2 };\n// Does not log anything, because `b` is defined and there's no need\n// to evaluate the default value.\n
\n
\n

Rest property

\n
\n

You can end a destructuring pattern with a rest property ...rest. This pattern will store all remaining properties of the object or array into a new object or array.

\n

js

\n
const { a, ...others } = { a: 1, b: 2, c: 3 };\nconsole.log(others); // { b: 2, c: 3 }\n\nconst [first, ...others2] = [1, 2, 3];\nconsole.log(others2); // [2, 3]\n
\n

The rest property must be the last in the pattern, and must not have a trailing comma.

\n

js

\n
const [a, ...b,] = [1, 2, 3];\n\n// SyntaxError: rest element may not have a trailing comma\n// Always consider using rest operator as the last element\n
\n
\n

Examples

\n

Array destructuring

\n
\n

Basic variable assignment

\n

js

\n
const foo = [\"one\", \"two\", \"three\"];\n\nconst [red, yellow, green] = foo;\nconsole.log(red); // \"one\"\nconsole.log(yellow); // \"two\"\nconsole.log(green); // \"three\"\n
\n

Destructuring with more elements than the source

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N, only the first N variables are assigned values. The values of the remaining variables will be undefined.

\n

js

\n
const foo = [\"one\", \"two\"];\n\nconst [red, yellow, green, blue] = foo;\nconsole.log(red); // \"one\"\nconsole.log(yellow); // \"two\"\nconsole.log(green); // undefined\nconsole.log(blue); // undefined\n
\n

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick).

\n

js

\n
let a = 1;\nlet b = 3;\n\n[a, b] = [b, a];\nconsole.log(a); // 3\nconsole.log(b); // 1\n\nconst arr = [1, 2, 3];\n[arr[2], arr[1]] = [arr[1], arr[2]];\nconsole.log(arr); // [1, 3, 2]\n
\n

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

\n

js

\n
function f() {\n  return [1, 2];\n}\n\nconst [a, b] = f();\nconsole.log(a); // 1\nconsole.log(b); // 2\n
\n

Ignoring some returned values

You can ignore return values that you're not interested in:

\n

js

\n
function f() {\n  return [1, 2, 3];\n}\n\nconst [a, , b] = f();\nconsole.log(a); // 1\nconsole.log(b); // 3\n\nconst [c] = f();\nconsole.log(c); // 1\n
\n

You can also ignore all returned values:

\n

js

\n
[, ,] = f();\n
\n

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

\n

js

\n
const [a, b, ...{ length }] = [1, 2, 3];\nconsole.log(a, b, length); // 1 2 1\n
\n
\n

js

\n
const [a, b, ...[c, d]] = [1, 2, 3, 4];\nconsole.log(a, b, c, d); // 1 2 3 4\n
\n

These binding patterns can even be nested, as long as each rest property is the last in the list.

\n

js

\n
const [a, b, ...[c, d, ...[e, f]]] = [1, 2, 3, 4, 5, 6];\nconsole.log(a, b, c, d, e, f); // 1 2 3 4 5 6\n
\n

On the other hand, object destructuring can only have an identifier as the rest property.

\n

js

\n
const { a, ...{ b } } = { a: 1, b: 2 };\n// SyntaxError: `...` must be followed by an identifier in declaration contexts\n\nlet a, b;\n({ a, ...{ b } } = { a: 1, b: 2 });\n// SyntaxError: `...` must be followed by an assignable reference in assignment contexts\n
\n

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

\n

js

\n
function parseProtocol(url) {\n  const parsedURL = /^(\\w+):\\/\\/([^/]+)\\/(.*)$/.exec(url);\n  if (!parsedURL) {\n    return false;\n  }\n  console.log(parsedURL);\n  // [\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\",\n  // \"https\", \"developer.mozilla.org\", \"en-US/docs/Web/JavaScript\"]\n\n  const [, protocol, fullhost, fullpath] = parsedURL;\n  return protocol;\n}\n\nconsole.log(\n  parseProtocol(\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\"),\n);\n// \"https\"\n
\n

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

\n

js

\n
const [a, b] = new Map([\n  [1, 2],\n  [3, 4],\n]);\nconsole.log(a, b); // [1, 2] [3, 4]\n
\n

Non-iterables cannot be destructured as arrays.

\n

js

\n
const obj = { 0: \"a\", 1: \"b\", length: 2 };\nconst [a, b] = obj;\n// TypeError: obj is not iterable\n
\n

Iterables are only iterated until all bindings are assigned.

\n

js

\n
const obj = {\n  *[Symbol.iterator]() {\n    for (const v of [0, 1, 2, 3]) {\n      console.log(v);\n      yield v;\n    }\n  },\n};\nconst [a, b] = obj; // Only logs 0 and 1\n
\n

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

\n

js

\n
const obj = {\n  *[Symbol.iterator]() {\n    for (const v of [0, 1, 2, 3]) {\n      console.log(v);\n      yield v;\n    }\n  },\n};\nconst [a, b, ...rest] = obj; // Logs 0 1 2 3\nconsole.log(rest); // [2, 3] (an array)\n
\n
\n

Object destructuring

\n
\n

Basic assignment

\n

js

\n
const user = {\n  id: 42,\n  isVerified: true,\n};\n\nconst { id, isVerified } = user;\n\nconsole.log(id); // 42\nconsole.log(isVerified); // true\n
\n

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

\n

js

\n
const o = { p: 42, q: true };\nconst { p: foo, q: bar } = o;\n\nconsole.log(foo); // 42\nconsole.log(bar); // true\n
\n

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo.

Assigning to new variable names and providing default values

A property can be both

\n

js

\n
const { a: aa = 10, b: bb = 5 } = { a: 3 };\n\nconsole.log(aa); // 3\nconsole.log(bb); // 5\n
\n

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

\n

js

\n
const user = {\n  id: 42,\n  displayName: \"jdoe\",\n  fullName: {\n    firstName: \"Jane\",\n    lastName: \"Doe\",\n  },\n};\n
\n

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

\n

js

\n
function userId({ id }) {\n  return id;\n}\n\nconsole.log(userId(user)); // 42\n
\n

You can define the name of the unpacked variable. Here we unpack the property named displayName, and rename it to dname for use within the function body.

\n

js

\n
function userDisplayName({ displayName: dname }) {\n  return dname;\n}\n\nconsole.log(userDisplayName(user)); // \"jdoe\"\n
\n

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name.

\n

js

\n
function whois({ displayName, fullName: { firstName: name } }) {\n  return `${displayName} is ${name}`;\n}\n\nconsole.log(whois(user)); // \"jdoe is Jane\"\n
\n

Setting a function parameter's default value

Default values can be specified using =, and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big', default co-ordinates are x: 0, y: 0 and default radius is 25.

\n

js

\n
function drawChart({\n  size = \"big\",\n  coords = { x: 0, y: 0 },\n  radius = 25,\n} = {}) {\n  console.log(size, coords, radius);\n  // do some chart drawing\n}\n\ndrawChart({\n  coords: { x: 18, y: 30 },\n  radius: 30,\n});\n
\n

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {}.

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment.

Nested object and array destructuring

\n

js

\n
const metadata = {\n  title: \"Scratchpad\",\n  translations: [\n    {\n      locale: \"de\",\n      localizationTags: [],\n      lastEdit: \"2014-04-14T08:43:37\",\n      url: \"/de/docs/Tools/Scratchpad\",\n      title: \"JavaScript-Umgebung\",\n    },\n  ],\n  url: \"/en-US/docs/Tools/Scratchpad\",\n};\n\nconst {\n  title: englishTitle, // rename\n  translations: [\n    {\n      title: localeTitle, // rename\n    },\n  ],\n} = metadata;\n\nconsole.log(englishTitle); // \"Scratchpad\"\nconsole.log(localeTitle); // \"JavaScript-Umgebung\"\n
\n

For of iteration and destructuring

\n

js

\n
const people = [\n  {\n    name: \"Mike Smith\",\n    family: {\n      mother: \"Jane Smith\",\n      father: \"Harry Smith\",\n      sister: \"Samantha Smith\",\n    },\n    age: 35,\n  },\n  {\n    name: \"Tom Jones\",\n    family: {\n      mother: \"Norah Jones\",\n      father: \"Richard Jones\",\n      brother: \"Howard Jones\",\n    },\n    age: 25,\n  },\n];\n\nfor (const {\n  name: n,\n  family: { father: f },\n} of people) {\n  console.log(`Name: ${n}, Father: ${f}`);\n}\n\n// \"Name: Mike Smith, Father: Harry Smith\"\n// \"Name: Tom Jones, Father: Richard Jones\"\n
\n

Computed object property names and destructuring

Computed property names, like on object literals, can be used with destructuring.

\n

js

\n
const key = \"z\";\nconst { [key]: foo } = { z: \"bar\" };\n\nconsole.log(foo); // \"bar\"\n
\n

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

\n

js

\n
const foo = { \"fizz-buzz\": true };\nconst { \"fizz-buzz\": fizzBuzz } = foo;\n\nconsole.log(fizzBuzz); // true\n
\n
\n

Destructuring primitive values

\n
\n

Object destructuring is almost equivalent to property accessing. This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

\n

js

\n
const { a, toFixed } = 1;\nconsole.log(a, toFixed); // undefined ƒ toFixed() { [native code] }\n
\n

Same as accessing properties, destructuring null or undefined throws a TypeError.

\n

js

\n
const { a } = undefined; // TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.\nconst { b } = null; // TypeError: Cannot destructure property 'b' of 'null' as it is null.\n
\n

This happens even when the pattern is empty.

\n

js

\n
const {} = null; // TypeError: Cannot destructure 'null' as it is null.\n
\n

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

\n

js

\n
const props = [\n  { id: 1, name: \"Fizz\" },\n  { id: 2, name: \"Buzz\" },\n  { id: 3, name: \"FizzBuzz\" },\n];\n\nconst [, , { name }] = props;\n\nconsole.log(name); // \"FizzBuzz\"\n
\n

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

\n

js

\n
const obj = {\n  self: \"123\",\n  __proto__: {\n    prot: \"456\",\n  },\n};\nconst { self, prot } = obj;\n\nconsole.log(self); // \"123\"\nconsole.log(prot); // \"456\"\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-destructuring-assignment
ECMAScript Language Specification
# sec-destructuring-binding-patterns
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Destructuring_assignment4914
41Firefox provided a non-standard destructuring implementation from Firefox 2 to 40.
No3684949
41Firefox provided a non-standard destructuring implementation from Firefox 2 to 40.
3685.01.06.0.0
computed_property_names491441No361049494136105.01.06.0.0
rest_in_arrays491641No369.1494941369.35.01.06.0.0
rest_in_objects607955No4711.16060554411.38.01.08.3.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\n

\n
\n", + "operators/yield": "

yield

The yield operator is used to pause and resume a generator function.

\n

Try it

\n

Syntax

\n
\n

js

\n
yield\nyield expression\n
\n

Parameters

\n
\nexpression Optional\n

The value to yield from the generator function via the iterator protocol. If omitted, undefined is yielded.

Return value

\n
\n

Returns the optional value passed to the generator's next() method to resume its execution.

Note: This means next() is asymmetric: it always sends a value to the currently suspended yield, but returns the operand of the next yield. The argument passed to the first next() call cannot be retrieved because there's no currently suspended yield.

\n

Description

\n
\n

The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.

yield can only be used directly within the generator function that contains it. It cannot be used within nested functions.

Calling a generator function constructs a Generator object. Each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following:

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called again. If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. The first next() call does not have a corresponding suspended yield operation, so there's no way to get the argument passed to the first next() call.

If the generator's return() or throw() method is called, it acts as if a return or throw statement was executed at the paused yield expression. You can use try...catch...finally within the generator function body to handle these early completions. If the return() or throw() method is called but there's no suspended yield expression (because next() has not been called yet, or because the generator has already completed), then the early completions cannot be handled and always terminate the generator.

\n

Examples

\n

Using yield

\n
\n

The following code is the declaration of an example generator function.

\n

js

\n
function* countAppleSales() {\n  const saleList = [3, 7, 5];\n  for (let i = 0; i < saleList.length; i++) {\n    yield saleList[i];\n  }\n}\n
\n

Once a generator function is defined, it can be used by constructing an iterator as shown.

\n

js

\n
const appleStore = countAppleSales(); // Generator { }\nconsole.log(appleStore.next()); // { value: 3, done: false }\nconsole.log(appleStore.next()); // { value: 7, done: false }\nconsole.log(appleStore.next()); // { value: 5, done: false }\nconsole.log(appleStore.next()); // { value: undefined, done: true }\n
\n

You can also send a value with next(value) into the generator. step evaluates as a return value of the yield expression — although the value passed to the generator's next() method the first time next() is called is ignored.

\n

js

\n
function* counter(value) {\n  while (true) {\n    const step = yield value++;\n\n    if (step) {\n      value += step;\n    }\n  }\n}\n\nconst generatorFunc = counter(0);\nconsole.log(generatorFunc.next().value); // 0\nconsole.log(generatorFunc.next().value); // 1\nconsole.log(generatorFunc.next().value); // 2\nconsole.log(generatorFunc.next().value); // 3\nconsole.log(generatorFunc.next(10).value); // 14\nconsole.log(generatorFunc.next().value); // 15\nconsole.log(generatorFunc.next(10).value); // 26\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-YieldExpression
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
yield3912
26[\"Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.\", \"Starting with Firefox 29, an IteratorResult object returned for completed generator function.\"]
No26103939
26[\"Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.\", \"Starting with Firefox 29, an IteratorResult object returned for completed generator function.\"]
26104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield\n

\n
\n", + "operators/yield*": "

yield*

The yield* operator is used to delegate to another iterable object, such as a Generator.

\n

Try it

\n

Syntax

\n
\n

js

\n
yield* expression\n
\n

Parameters

\n
\nexpression Optional\n

An iterable object.

Return value

\n

Returns the value returned by that iterator when it's closed (when done is true).

Description

\n
\n

The yield* expression iterates over the operand and yields each value returned by it. It delegates iteration of the current generator to an underlying iterator — which we will refer to as \"generator\" and \"iterator\", respectively. yield* first gets the iterator from the operand by calling the latter's @@iterator method. Then, each time the next() method of the generator is called, yield* calls the iterator's next() method, passing the argument received by the generator's next() method (always undefined for the first call), and yielding the same result object as what's returned from the iterator's next() method. If the iterator result has done: true, then the yield* expression stops executing and returns the value of that result.

The yield* operator forwards the current generator's throw() and return() methods to the underlying iterator as well. If the current generator is prematurely closed through one of these methods, the underlying iterator will be notified. If the generator's throw()/return() method is called, the throw()/return() method of the underlying iterator is called with the same argument. The return value of throw()/return() is handled like the next() method's result, and if the method throws, the exception is propagated from the yield* expression.

If the underlying iterator doesn't have a throw() method, this causes yield* to throw a TypeError – but before throwing the error, the underlying iterator's return() method is called if one exists. If the underlying iterator doesn't have a return() method, the yield* expression turns into a return statement, just like calling return() on a suspended yield expression.

\n

Examples

\n

Delegating to another generator

\n
\n

In following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2().

\n

js

\n
function* g1() {\n  yield 2;\n  yield 3;\n  yield 4;\n}\n\nfunction* g2() {\n  yield 1;\n  yield* g1();\n  yield 5;\n}\n\nconst gen = g2();\n\nconsole.log(gen.next()); // {value: 1, done: false}\nconsole.log(gen.next()); // {value: 2, done: false}\nconsole.log(gen.next()); // {value: 3, done: false}\nconsole.log(gen.next()); // {value: 4, done: false}\nconsole.log(gen.next()); // {value: 5, done: false}\nconsole.log(gen.next()); // {value: undefined, done: true}\n
\n
\n

Other Iterable objects

\n
\n

Besides generator objects, yield* can also yield other kinds of iterables (e.g., arrays, strings, or arguments objects).

\n

js

\n
function* g3(...args) {\n  yield* [1, 2];\n  yield* \"34\";\n  yield* args;\n}\n\nconst gen = g3(5, 6);\n\nconsole.log(gen.next()); // {value: 1, done: false}\nconsole.log(gen.next()); // {value: 2, done: false}\nconsole.log(gen.next()); // {value: \"3\", done: false}\nconsole.log(gen.next()); // {value: \"4\", done: false}\nconsole.log(gen.next()); // {value: 5, done: false}\nconsole.log(gen.next()); // {value: 6, done: false}\nconsole.log(gen.next()); // {value: undefined, done: true}\n
\n
\n

The value of yield* expression itself

\n
\n

yield* is an expression, not a statement, so it evaluates to a value.

\n

js

\n
function* g4() {\n  yield* [1, 2, 3];\n  return \"foo\";\n}\n\nfunction* g5() {\n  const g4ReturnValue = yield* g4();\n  console.log(g4ReturnValue); // 'foo'\n  return g4ReturnValue;\n}\n\nconst gen = g5();\n\nconsole.log(gen.next()); // {value: 1, done: false}\nconsole.log(gen.next()); // {value: 2, done: false}\nconsole.log(gen.next()); // {value: 3, done: false} done is false because g5 generator isn't finished, only g4\nconsole.log(gen.next()); // {value: 'foo', done: true}\n
\n
\n

Method forwarding

\n
\n

The next(), throw(), and return() methods of the current generator are all forwarded to the underlying iterator.

\n

js

\n
const iterable = {\n  [Symbol.iterator]() {\n    let count = 0;\n    return {\n      next(v) {\n        console.log(\"next called with\", v);\n        count++;\n        return { value: count, done: false };\n      },\n      return(v) {\n        console.log(\"return called with\", v);\n        return { value: \"iterable return value\", done: true };\n      },\n      throw(v) {\n        console.log(\"throw called with\", v);\n        return { value: \"iterable thrown value\", done: true };\n      },\n    };\n  },\n};\n\nfunction* gf() {\n  yield* iterable;\n  return \"gf return value\";\n}\n\nconst gen = gf();\nconsole.log(gen.next(10));\n// next called with undefined; the argument of the first next() call is always ignored\n// { value: 1, done: false }\nconsole.log(gen.next(20));\n// next called with 20\n// { value: 2, done: false }\nconsole.log(gen.return(30));\n// return called with 30\n// { value: 'iterable return value', done: true }\nconsole.log(gen.next(40));\n// { value: undefined, done: true }; gen is already closed\n\nconst gen2 = gf();\nconsole.log(gen2.next(10));\n// next called with undefined\n// { value: 1, done: false }\nconsole.log(gen2.throw(50));\n// throw called with 50\n// { value: 'gf return value', done: true }\nconsole.log(gen.next(60));\n// { value: undefined, done: true }; gen is already closed\n
\n

If the return()/throw() method of the underlying iterator returns done: false, the current generator continues executing and yield* continues to delegate to the underlying iterator.

\n

js

\n
const iterable = {\n  [Symbol.iterator]() {\n    let count = 0;\n    return {\n      next(v) {\n        console.log(\"next called with\", v);\n        count++;\n        return { value: count, done: false };\n      },\n      return(v) {\n        console.log(\"return called with\", v);\n        return { value: \"iterable return value\", done: false };\n      },\n    };\n  },\n};\n\nfunction* gf() {\n  yield* iterable;\n  return \"gf return value\";\n}\n\nconst gen = gf();\nconsole.log(gen.next(10));\n// next called with undefined\n// { value: 1, done: false }\nconsole.log(gen.return(20));\n// return called with 20\n// { value: 'iterable return value', done: false }\nconsole.log(gen.next(30));\n// { value: 2, done: false }; gen is not closed\n
\n

If the underlying iterator doesn't have a throw() method and the generator's throw() is called, yield* throws an error.

\n

js

\n
const iterable = {\n  [Symbol.iterator]() {\n    let count = 0;\n    return {\n      next(v) {\n        count++;\n        return { value: count, done: false };\n      },\n    };\n  },\n};\n\nfunction* gf() {\n  yield* iterable;\n  return \"gf return value\";\n}\n\nconst gen = gf();\ngen.next(); // First next() starts the yield* expression\ngen.throw(20); // TypeError: The iterator does not provide a 'throw' method.\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator-function-definitions-runtime-semantics-evaluation
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
yield*3912
27Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.
No26103939
27Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.
26104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*\n

\n
\n", + "operators/spread_syntax": "

Spread syntax (...)

\n

The ... syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax \"expands\" an array into its elements, while rest syntax collects multiple elements and \"condenses\" them into a single element. See rest parameters and rest property.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
myFunction(a, ...iterableObj, b)\n[1, ...iterableObj, '4', 'five', 6]\n{ ...obj, key: 'value' }\n
\n

Description

\n
\n

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:

Although the syntax looks the same, they come with slightly different semantics.

Only iterable values, like Array and String, can be spread in array literals and argument lists. Many objects are not iterable, including all plain objects that lack a Symbol.iterator method:

\n

js

\n
const obj = { key1: \"value1\" };\nconst array = [...obj]; // TypeError: obj is not iterable\n
\n

On the other hand, spreading in object literals enumerates the own properties of the value. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.

\n

js

\n
const array = [1, 2, 3];\nconst obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }\n
\n

All primitives can be spread in objects. Only strings have enumerable own properties, and spreading anything else doesn't create properties on the new object.

\n

js

\n
const obj = { ...true, ...\"test\", ...10 };\n// { '0': 't', '1': 'e', '2': 's', '3': 't' }\n
\n

When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See Function.prototype.apply() for more details.

\n

Examples

\n

Spread in function calls

\n
\n

Replace apply()

It is common to use Function.prototype.apply() in cases where you want to use the elements of an array as arguments to a function.

\n

js

\n
function myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction.apply(null, args);\n
\n

With spread syntax the above can be written as:

\n

js

\n
function myFunction(x, y, z) {}\nconst args = [0, 1, 2];\nmyFunction(...args);\n
\n

Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times.

\n

js

\n
function myFunction(v, w, x, y, z) {}\nconst args = [0, 1];\nmyFunction(-1, ...args, 2, ...[3]);\n
\n

Apply for new operator

When calling a constructor with new, it's not possible to directly use an array and apply(), because apply() calls the target function instead of constructing it, which means, among other things, that new.target will be undefined. However, an array can be easily used with new thanks to spread syntax:

\n

js

\n
const dateFields = [1970, 0, 1]; // 1 Jan 1970\nconst d = new Date(...dateFields);\n
\n
\n

Spread in array literals

\n
\n

A more powerful array literal

Without spread syntax, the array literal syntax is no longer sufficient to create a new array using an existing array as one part of it. Instead, imperative code must be used using a combination of methods, including push(), splice(), concat(), etc. With spread syntax, this becomes much more succinct:

\n

js

\n
const parts = [\"shoulders\", \"knees\"];\nconst lyrics = [\"head\", ...parts, \"and\", \"toes\"];\n//  [\"head\", \"shoulders\", \"knees\", \"and\", \"toes\"]\n
\n

Just like spread for argument lists, ... can be used anywhere in the array literal, and may be used more than once.

Copying an array

You can use spread syntax to make a shallow copy of an array. Each array element retains its identity without getting copied.

\n

js

\n
const arr = [1, 2, 3];\nconst arr2 = [...arr]; // like arr.slice()\n\narr2.push(4);\n// arr2 becomes [1, 2, 3, 4]\n// arr remains unaffected\n
\n

Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with Object.assign() — no native operation in JavaScript does a deep clone. The web API method structuredClone() allows deep copying values of certain supported types. See shallow copy for more details.

\n

js

\n
const a = [[1], [2], [3]];\nconst b = [...a];\n\nb.shift().shift();\n// 1\n\n// Oh no! Now array 'a' is affected as well:\nconsole.log(a);\n// [[], [2], [3]]\n
\n

A better way to concatenate arrays

Array.prototype.concat() is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as:

\n

js

\n
let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\n// Append all items from arr2 onto arr1\narr1 = arr1.concat(arr2);\n
\n

With spread syntax this becomes:

\n

js

\n
let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\narr1 = [...arr1, ...arr2];\n// arr1 is now [0, 1, 2, 3, 4, 5]\n
\n

Array.prototype.unshift() is often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as:

\n

js

\n
const arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\n//  Prepend all items from arr2 onto arr1\nArray.prototype.unshift.apply(arr1, arr2);\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\n
\n

With spread syntax, this becomes:

\n

js

\n
let arr1 = [0, 1, 2];\nconst arr2 = [3, 4, 5];\n\narr1 = [...arr2, ...arr1];\nconsole.log(arr1); // [3, 4, 5, 0, 1, 2]\n
\n

Note: Unlike unshift(), this creates a new arr1, instead of modifying the original arr1 array in-place.

Conditionally adding values to an array

You can make an element present or absent in an array literal, depending on a condition, using a conditional operator.

\n

js

\n
const isSummer = false;\nconst fruits = [\"apple\", \"banana\", ...(isSummer ? [\"watermelon\"] : [])];\n// ['apple', 'banana']\n
\n

When the condition is false, we spread an empty array, so that nothing gets added to the final array. Note that this is different from the following:

\n

js

\n
const fruits = [\"apple\", \"banana\", isSummer ? \"watermelon\" : undefined];\n// ['apple', 'banana', undefined]\n
\n

In this case, an extra undefined element is added when isSummer is false, and this element will be visited by methods such as Array.prototype.map().

\n

Spread in object literals

\n
\n

Copying and merging objects

You can use spread syntax to merge multiple objects into one new object.

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { bar: \"baz\", y: 13 };\n\nconst mergedObj = { ...obj1, ...obj2 };\n// { foo: \"bar\", x: 42, bar: \"baz\", y: 13 }\n
\n

A single spread creates a shallow copy of the original object (but without non-enumerable properties and without copying the prototype), similar to copying an array.

\n

js

\n
const clonedObj = { ...obj1 };\n// { foo: \"bar\", x: 42 }\n
\n

Overriding properties

When one object is spread into another object, or when multiple objects are spread into one object, and properties with identical names are encountered, the property takes the last value assigned while remaining in the position it was originally set.

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\n\nconst mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; // { x: 42, foo: \"baz\", y: 9 }\n
\n

Conditionally adding properties to an object

You can make an element present or absent in an object literal, depending on a condition, using a conditional operator.

\n

js

\n
const isSummer = false;\nconst fruits = {\n  apple: 10,\n  banana: 5,\n  ...(isSummer ? { watermelon: 30 } : {}),\n};\n// { apple: 10, banana: 5 }\n
\n

The case where the condition is false is an empty object, so that nothing gets spread into the final object. Note that this is different from the following:

\n

js

\n
const fruits = {\n  apple: 10,\n  banana: 5,\n  watermelon: isSummer ? 30 : undefined,\n};\n// { apple: 10, banana: 5, watermelon: undefined }\n
\n

In this case, the watermelon property is always present and will be visited by methods such as Object.keys().

Because primitives can be spread into objects as well, and from the observation that all falsy values do not have enumerable properties, you can simply use a logical AND operator:

\n

js

\n
const isSummer = false;\nconst fruits = {\n  apple: 10,\n  banana: 5,\n  ...(isSummer && { watermelon: 30 }),\n};\n
\n

In this case, if isSummer is any falsy value, no property will be created on the fruits object.

Comparing with Object.assign()

Note that Object.assign() can be used to mutate an object, whereas spread syntax can't.

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nObject.assign(obj1, { x: 1337 });\nconsole.log(obj1); // { foo: \"bar\", x: 1337 }\n
\n

In addition, Object.assign() triggers setters on the target object, whereas spread syntax does not.

\n

js

\n
const objectAssign = Object.assign(\n  {\n    set foo(val) {\n      console.log(val);\n    },\n  },\n  { foo: 1 },\n);\n// Logs \"1\"; objectAssign.foo is still the original setter\n\nconst spread = {\n  set foo(val) {\n    console.log(val);\n  },\n  ...{ foo: 1 },\n};\n// Nothing is logged; spread.foo is 1\n
\n

You cannot naively re-implement the Object.assign() function through a single spreading:

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) => ({ ...objects });\n\nconst mergedObj1 = merge(obj1, obj2);\n// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }\n\nconst mergedObj2 = merge({}, obj1, obj2);\n// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }\n
\n

In the above example, the spread syntax does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter. Here is an implementation of merge using the spread syntax, whose behavior is similar to Object.assign(), except that it doesn't trigger setters, nor mutates any object:

\n

js

\n
const obj1 = { foo: \"bar\", x: 42 };\nconst obj2 = { foo: \"baz\", y: 13 };\nconst merge = (...objects) =>\n  objects.reduce((acc, cur) => ({ ...acc, ...cur }));\n\nconst mergedObj1 = merge(obj1, obj2);\n// { foo: 'baz', x: 42, y: 13 }\n
\n
\n

Specifications

\n
\n\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# prod-SpreadElement
ECMAScript Language Specification
# prod-ArgumentList
ECMAScript Language Specification
# prod-PropertyDefinition
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Spread_syntax461216No3784646163785.01.05.0.0
spread_in_arrays461216No3784646163785.01.05.0.0
spread_in_function_calls461227No3784646273785.0?5.0.0
spread_in_object_literals607955No4711.16060554411.38.2?8.3.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\n

\n
\n", + "operators/comma_operator": "

Comma operator (,)

The , operator evaluates each of its operands (from left to right) and returns the value of the last operand. This is commonly used to provide multiple updaters to a for loop's afterthought.

\n

Try it

\n

Syntax

\n
\n

js

\n
expr1, expr2, expr3/* , … */\n
\n

Parameters

\n
\nexpr1, expr2, expr3, …

One or more expressions, the last of which is returned as the value of the compound expression.

Description

\n
\n

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple updaters in a for loop.

Because all expressions except the last are evaluated and then discarded, these expressions must have side effects to be useful. Common expressions that have side effects are assignments, function calls, and ++ and -- operators. Others may also have side effects if they invoke getters or trigger type coercions.

The comma operator has the lowest precedence of all operators. If you want to incorporate a comma-joined expression into a bigger expression, you must parenthesize it.

The comma operator is completely different from commas used as syntactic separators in other locations, which include:

In fact, although some of these places accept almost all expressions, they don't accept comma-joined expressions because that would be ambiguous with the syntactic comma separators. In this case, you must parenthesize the comma-joined expression. For example, the following is a const declaration that declares two variables, where the comma is not the comma operator:

\n

js

\n
const a = 1, b = 2;\n
\n

It is different from the following, where b = 2 is an assignment expression, not a declaration. The value of a is 2, the return value of the assignment, while the value of 1 is discarded:

\n

js

\n
const a = (1, b = 2);\n
\n

Comma operators cannot appear as trailing commas.

\n

Examples

\n

Using the comma operator in a for loop

\n
\n

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once, thus printing the values of the diagonal elements in the array:

\n

js

\n
const a = Array.from({ length: 10 }, () =>\n  Array.from({ length: 10 }, Math.random),\n); // A 10×10 array of random numbers\n\nfor (let i = 0, j = 9; i <= 9; i++, j--) {\n  console.log(`a[${i}][${j}] = ${a[i][j]}`);\n}\n
\n
\n

Using the comma operator to join assignments

\n
\n

Because commas have the lowest precedence — even lower than assignment — commas can be used to join multiple assignment expressions. In the following example, a is set to the value of b = 3 (which is 3). Then, the c = 4 expression evaluates and its result becomes the return value of the entire comma expression.

\n

js

\n
let a, b, c;\n\na = b = 3, c = 4; // Returns 4\nconsole.log(a); // 3 (left-most)\n\nlet x, y, z;\n\nx = (y = 5, z = 6); // Returns 6\nconsole.log(x); // 6 (right-most)\n
\n
\n

Processing and then returning

\n
\n

Another example that one could make with the comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

\n

js

\n
function myFunc() {\n  let x = 0;\n\n  return (x += 1, x); // the same as return ++x;\n}\n
\n

This is especially useful for one-line arrow functions. The following example uses a single map() to get both the sum of an array and the squares of its elements, which would otherwise require two iterations, one with reduce() and one with map():

\n

js

\n
let sum = 0;\nconst squares = [1, 2, 3, 4, 5].map((x) => ((sum += x), x * x));\nconsole.log(squares); // [1, 4, 9, 16, 25]\nconsole.log(sum); // 15\n
\n
\n

Discarding reference binding

\n
\n

The comma operator always returns the last expression as a value instead of a reference. This causes some contextual information such as the this binding to be lost. For example, a property access returns a reference to the function, which also remembers the object that it's accessed on, so that calling the property works properly. If the method is returned from a comma expression, then the function is called as if it's a new function value, and this is undefined.

\n

js

\n
const obj = {\n  value: \"obj\",\n  method() {\n    console.log(this.value);\n  },\n};\n\nobj.method(); // \"obj\"\n(obj.method)(); // \"obj\" (the grouping operator still returns the reference)\n(0, obj.method)(); // undefined (the comma operator returns a new value)\n
\n

You can enter indirect eval with this technique, because direct eval requires the function call to happen on the reference to the eval() function.

\n

js

\n
globalThis.isDirectEval = false;\n\n{\n  const isDirectEval = true;\n  console.log(eval(\"isDirectEval\")); // true\n  console.log((eval)(\"isDirectEval\")); // true (the grouping operator still returns a reference to `eval`)\n  console.log((0, eval)(\"isDirectEval\")); // false (the comma operator returns a new value)\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-comma-operator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Comma_operator11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator\n

\n
\n", + "functions": "

Functions

\n

Generally speaking, a function is a \"subprogram\" that can be called by code external (or internal, in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function as parameters, and the function will return a value.

In JavaScript, functions are first-class objects, because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.

For more examples and explanations, see the JavaScript guide about functions.

\n
\n

Description

\n
\n

Function values are typically instances of Function. See Function for information on properties and methods of Function objects. Callable values cause typeof to return \"function\" instead of \"object\".

Note: Not all callable values are instanceof Function. For example, the Function.prototype object is callable but not an instance of Function. You can also manually set the prototype chain of your function so it no longer inherits from Function.prototype. However, such cases are extremely rare.

\n

Return value

\n
\n

By default, if a function's execution doesn't end at a return statement, or if the return keyword doesn't have an expression after it, then the return value is undefined. The return statement allows you to return an arbitrary value from the function. One function call can only return one value, but you can simulate the effect of returning multiple values by returning an object or array and destructuring the result.

Note: Constructors called with new have a different set of logic to determine their return values.

\n

Passing arguments

\n
\n

Parameters and arguments have slightly different meanings, but in MDN web docs, we often use them interchangeably. For a quick reference:

\n

js

\n
function formatNumber(num) {\n  return num.toFixed(2);\n}\n\nformatNumber(2);\n
\n

In this example, the num variable is called the function's parameter: it's declared in the parenthesis-enclosed list of the function's definition. The function expects the num parameter to be a number — although this is not enforceable in JavaScript without writing runtime validation code. In the formatNumber(2) call, the number 2 is the function's argument: it's the value that is actually passed to the function in the function call. The argument value can be accessed inside the function body through the corresponding parameter name or the arguments object.

Arguments are always passed by value and never passed by reference. This means that if a function reassigns a parameter, the value won't change outside the function. More precisely, object arguments are passed by sharing, which means if the object's properties are mutated, the change will impact the outside of the function. For example:

\n

js

\n
function updateBrand(obj) {\n  // Mutating the object is visible outside the function\n  obj.brand = \"Toyota\";\n  // Try to reassign the parameter, but this won't affect\n  // the variable's value outside the function\n  obj = null;\n}\n\nconst car = {\n  brand: \"Honda\",\n  model: \"Accord\",\n  year: 1998,\n};\n\nconsole.log(car.brand); // Honda\n\n// Pass object reference to the function\nupdateBrand(car);\n\n// updateBrand mutates car\nconsole.log(car.brand); // Toyota\n
\n

The this keyword refers to the object that the function is accessed on — it does not refer to the currently executing function, so you must refer to the function value by name, even within the function body.

\n

Defining functions

\n
\n

Broadly speaking, JavaScript has four kinds of functions:

For every kind of function, there are three ways to define it:

Declaration

function, function*, async function, async function*

Expression

function, function*, async function, async function*

Constructor

Function(), GeneratorFunction(), AsyncFunction(), AsyncGeneratorFunction()

In addition, there are special syntaxes for defining arrow functions and methods, which provide more precise semantics for their usage. Classes are conceptually not functions (because they throw an error when called without new), but they also inherit from Function.prototype and have typeof MyClass === \"function\".

\n

js

\n
// Constructor\nconst multiply = new Function(\"x\", \"y\", \"return x * y\");\n\n// Declaration\nfunction multiply(x, y) {\n  return x * y;\n} // No need for semicolon here\n\n// Expression; the function is anonymous but assigned to a variable\nconst multiply = function (x, y) {\n  return x * y;\n};\n// Expression; the function has its own name\nconst multiply = function funcName(x, y) {\n  return x * y;\n};\n\n// Arrow function\nconst multiply = (x, y) => x * y;\n\n// Method\nconst obj = {\n  multiply(x, y) {\n    return x * y;\n  },\n};\n
\n

All syntaxes do approximately the same thing, but there are some subtle behavior differences.

For function expressions, there is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be different from the variable the function is assigned to — they have no relation to each other. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or gets another value, if the same name is declared elsewhere). For example:

\n

js

\n
const y = function x() {};\nconsole.log(x); // ReferenceError: x is not defined\n
\n

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in, as well as in their own body.

A function defined by new Function will dynamically have its source assembled, which is observable when you serialize it. For example, console.log(new Function().toString()) gives:

\n

js

\n
function anonymous(\n) {\n\n}\n
\n

This is the actual source used to compile the function. However, although the Function() constructor will create the function with name anonymous, this name is not added to the scope of the body. The body only ever has access to global variables. For example, the following would result in an error:

\n

js

\n
new Function(\"alert(anonymous);\")();\n
\n

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

\n

js

\n
// p is a global variable\nglobalThis.p = 5;\nfunction myFunc() {\n  // p is a local variable\n  const p = 9;\n\n  function decl() {\n    console.log(p);\n  }\n  const expr = function () {\n    console.log(p);\n  };\n  const cons = new Function(\"\\tconsole.log(p);\");\n\n  decl();\n  expr();\n  cons();\n}\nmyFunc();\n\n// Logs:\n// 9 (for 'decl' by function declaration (current scope))\n// 9 (for 'expr' by function expression (current scope))\n// 5 (for 'cons' by Function constructor (global scope))\n
\n

Functions defined by function expressions and function declarations are parsed only once, while a function defined by the Function constructor parses the string passed to it each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than new Function(...). Therefore the Function constructor should generally be avoided whenever possible.

A function declaration may be unintentionally turned into a function expression when it appears in an expression context.

\n

js

\n
// A function declaration\nfunction foo() {\n  console.log(\"FOO!\");\n}\n\ndoSomething(\n  // A function expression passed as an argument\n  function foo() {\n    console.log(\"FOO!\");\n  },\n);\n
\n

On the other hand, a function expression may also be turned into a function declaration. An expression statement cannot begin with the function or async function keywords, which is a common mistake when implementing IIFEs (Immediately Invoked Function Expressions).

\n

js

\n
function () { // SyntaxError: Function statements require a function name\n  console.log(\"FOO!\");\n}();\n\nfunction foo() {\n  console.log(\"FOO!\");\n}(); // SyntaxError: Unexpected token ')'\n
\n

Instead, start the expression statement with something else, so that the function keyword unambiguously starts a function expression. Common options include grouping and using void.

\n

js

\n
(function () {\n  console.log(\"FOO!\");\n})();\n\nvoid function () {\n  console.log(\"FOO!\");\n}();\n
\n
\n

Function parameters

\n
\n

Each function parameter is a simple identifier that you can access in the local scope.

\n

js

\n
function myFunc(a, b, c) {\n  // You can access the values of a, b, and c here\n}\n
\n

There are three special parameter syntaxes:

\n

js

\n
function myFunc({ a, b }, c = 1, ...rest) {\n  // You can access the values of a, b, c, and rest here\n}\n
\n

There are some consequences if one of the above non-simple parameter syntaxes is used:

\n

The arguments object

\n
\n

You can refer to a function's arguments within the function by using the arguments object.

arguments

An array-like object containing the arguments passed to the currently executing function.

arguments.callee

The currently executing function.

arguments.length

The number of arguments passed to the function.

\n

Getter and setter functions

\n
\n

You can define accessor properties on any standard built-in object or user-defined object that supports the addition of new properties. Within object literals and classes, you can use special syntaxes to define the getter and setter of an accessor property.

get

Binds an object property to a function that will be called when that property is looked up.

set

Binds an object property to a function to be called when there is an attempt to set that property.

Note that these syntaxes create an object property, not a method. The getter and setter functions themselves can only be accessed using reflective APIs such as Object.getOwnPropertyDescriptor().

\n

Block-level functions

\n
\n

In strict mode, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

\n

js

\n
\"use strict\";\n\nfunction f() {\n  return 1;\n}\n\n{\n  function f() {\n    return 2;\n  }\n}\n\nf() === 1; // true\n\n// f() === 2 in non-strict mode\n
\n
\n

Block-level functions in non-strict code

\n
\n

In a word: Don't.

In non-strict code, function declarations inside blocks behave strangely. For example:

\n

js

\n
if (shouldDefineZero) {\n  function zero() {\n    // DANGER: compatibility risk\n    console.log(\"This is zero.\");\n  }\n}\n
\n

The semantics of this in strict mode are well-specified — zero only ever exists within that scope of the if block. If shouldDefineZero is false, then zero should never be defined, since the block never executes. However, historically, this was left unspecified, so different browsers implemented it differently in non-strict mode. For more information, see the function declaration reference.

A safer way to define functions conditionally is to assign a function expression to a variable:

\n

js

\n
// Using a var makes it available as a global variable,\n// with closer behavior to a top-level function declaration\nvar zero;\nif (shouldDefineZero) {\n  zero = function () {\n    console.log(\"This is zero.\");\n  };\n}\n
\n
\n

Examples

\n

Returning a formatted number

\n
\n

The following function returns a string containing the formatted representation of a number padded with leading zeros.

\n

js

\n
// This function returns a string padded with leading zeros\nfunction padZeros(num, totalLen) {\n  let numStr = num.toString(); // Initialize return value as string\n  const numZeros = totalLen - numStr.length; // Calculate no. of zeros\n  for (let i = 1; i <= numZeros; i++) {\n    numStr = `0${numStr}`;\n  }\n  return numStr;\n}\n
\n

The following statements call the padZeros function.

\n

js

\n
let result;\nresult = padZeros(42, 4); // returns \"0042\"\nresult = padZeros(42, 2); // returns \"42\"\nresult = padZeros(5, 4); // returns \"0005\"\n
\n
\n

Determining whether a function exists

\n
\n

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise, some other action is taken.

\n

js

\n
if (typeof window.noFunc === \"function\") {\n  // use noFunc()\n} else {\n  // do something else\n}\n
\n

Note that in the if test, a reference to noFunc is used — there are no parentheses () after the function name so the actual function is not called.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Functions11213314.418410.111.01.00.10.0
arguments11213314.418410.111.01.00.10.0
arrow_functions4512
22[\"The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required.\", \"Before Firefox 39, a line terminator (\\\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\\\n => {} will now throw a SyntaxError in this and later versions.\"]
No32104545
22[\"The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required.\", \"Before Firefox 39, a line terminator (\\\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\\\n => {} will now throw a SyntaxError in this and later versions.\"]
32105.01.04.0.0
block_level_functions49124611361049494636105.01.04.0.0
default_parameters491415No361049491536105.01.06.0.0
get1121.599.534.41841411.01.00.10.0
method_definitions391234No2693939342694.01.04.0.0
rest_parameters471215No341047471534105.01.06.0.0
set1121.599.534.41841411.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions\n

\n
\n", + "functions/arrow_functions": "

Arrow function expressions

\n

An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage:

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
() => expression\n\nparam => expression\n\n(param) => expression\n\n(param1, paramN) => expression\n\n() => {\n  statements\n}\n\nparam => {\n  statements\n}\n\n(param1, paramN) => {\n  statements\n}\n
\n

Rest parameters, default parameters, and destructuring within params are supported, and always require parentheses:

\n

js

\n
(a, b, ...r) => expression\n(a = 400, b = 20, c) => expression\n([a, b] = [10, 20]) => expression\n({ a, b } = { a: 10, b: 20 }) => expression\n
\n

Arrow functions can be async by prefixing the expression with the async keyword.

\n

js

\n
async param => expression\nasync (param1, param2, ...paramN) => {\n  statements\n}\n
\n
\n

Description

\n
\n

Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.

Note: Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.

\n

js

\n
// Traditional anonymous function\n(function (a) {\n  return a + 100;\n});\n\n// 1. Remove the word \"function\" and place arrow between the argument and opening body brace\n(a) => {\n  return a + 100;\n};\n\n// 2. Remove the body braces and word \"return\" — the return is implied.\n(a) => a + 100;\n\n// 3. Remove the parameter parentheses\na => a + 100;\n
\n

In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.

The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.

\n

js

\n
// Traditional anonymous function\n(function (a, b) {\n  return a + b + 100;\n});\n\n// Arrow function\n(a, b) => a + b + 100;\n\nconst a = 4;\nconst b = 2;\n\n// Traditional anonymous function (no parameters)\n(function () {\n  return a + b + 100;\n});\n\n// Arrow function (no parameters)\n() => a + b + 100;\n
\n

The braces can only be omitted if the function directly returns an expression. If the body has additional lines of processing, the braces are required — and so is the return keyword. Arrow functions cannot guess what or when you want to return.

\n

js

\n
// Traditional anonymous function\n(function (a, b) {\n  const chuck = 42;\n  return a + b + chuck;\n});\n\n// Arrow function\n(a, b) => {\n  const chuck = 42;\n  return a + b + chuck;\n};\n
\n

Arrow functions are always unnamed. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable so it has a name.

\n

js

\n
// Traditional Function\nfunction bob(a) {\n  return a + 100;\n}\n\n// Arrow Function\nconst bob2 = (a) => a + 100;\n
\n
\n

Function body

\n
\n

Arrow functions can have either an expression body or the usual block body.

In an expression body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

\n

js

\n
const func = (x) => x * x;\n// expression body syntax, implied \"return\"\n\nconst func2 = (x, y) => {\n  return x + y;\n};\n// with block body, explicit \"return\" needed\n
\n

Returning object literals using the expression body syntax (params) => { object: literal } does not work as expected.

\n

js

\n
const func = () => { foo: 1 };\n// Calling func() returns undefined!\n\nconst func2 = () => { foo: function () {} };\n// SyntaxError: function statement requires a name\n\nconst func3 = () => { foo() {} };\n// SyntaxError: Unexpected token '{'\n
\n

This is because JavaScript only sees the arrow function as having an expression body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, where foo is a label, not a key in an object literal.

To fix this, wrap the object literal in parentheses:

\n

js

\n
const func = () => ({ foo: 1 });\n
\n
\n

Cannot be used as methods

\n
\n

Arrow function expressions should only be used for non-method functions because they do not have their own this. Let's see what happens when we try to use them as methods:

\n

js

\n
\"use strict\";\n\nconst obj = {\n  i: 10,\n  b: () => console.log(this.i, this),\n  c() {\n    console.log(this.i, this);\n  },\n};\n\nobj.b(); // logs undefined, Window { /* … */ } (or the global object)\nobj.c(); // logs 10, Object { /* … */ }\n
\n

Another example involving Object.defineProperty():

\n

js

\n
\"use strict\";\n\nconst obj = {\n  a: 10,\n};\n\nObject.defineProperty(obj, \"b\", {\n  get: () => {\n    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window { /* … */ } (or the global object)\n    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'\n  },\n});\n
\n

Because a class's body has a this context, arrow functions as class fields close over the class's this context, and the this inside the arrow function's body will correctly point to the instance (or the class itself, for static fields). However, because it is a closure, not the function's own binding, the value of this will not change based on the execution context.

\n

js

\n
class C {\n  a = 1;\n  autoBoundMethod = () => {\n    console.log(this.a);\n  };\n}\n\nconst c = new C();\nc.autoBoundMethod(); // 1\nconst { autoBoundMethod } = c;\nautoBoundMethod(); // 1\n// If it were a normal method, it should be undefined in this case\n
\n

Arrow function properties are often said to be \"auto-bound methods\", because the equivalent with normal methods is:

\n

js

\n
class C {\n  a = 1;\n  constructor() {\n    this.method = this.method.bind(this);\n  }\n  method() {\n    console.log(this.a);\n  }\n}\n
\n

Note: Class fields are defined on the instance, not on the prototype, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.

For similar reasons, the call(), apply(), and bind() methods are not useful when called on arrow functions, because arrow functions establish this based on the scope the arrow function is defined within, and the this value does not change based on how the function is invoked.

\n

No binding of arguments

\n
\n

Arrow functions do not have their own arguments object. Thus, in this example, arguments is a reference to the arguments of the enclosing scope:

\n

js

\n
function foo(n) {\n  const f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n\n  return f();\n}\n\nfoo(3); // 3 + 3 = 6\n
\n

Note: You cannot declare a variable called arguments in strict mode, so the code above would be a syntax error. This makes the scoping effect of arguments much easier to comprehend.

In most cases, using rest parameters is a good alternative to using an arguments object.

\n

js

\n
function foo(n) {\n  const f = (...args) => args[0] + n;\n  return f(10);\n}\n\nfoo(1); // 11\n
\n
\n

Cannot be used as constructors

\n
\n

Arrow functions cannot be used as constructors and will throw an error when called with new. They also do not have a prototype property.

\n

js

\n
const Foo = () => {};\nconst foo = new Foo(); // TypeError: Foo is not a constructor\nconsole.log(\"prototype\" in Foo); // false\n
\n
\n

Cannot be used as generators

\n

The yield keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.

Line break before arrow

\n
\n

An arrow function cannot contain a line break between its parameters and its arrow.

\n

js

\n
const func = (a, b, c)\n  => 1;\n// SyntaxError: Unexpected token '=>'\n
\n

For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.

\n

js

\n
const func = (a, b, c) =>\n  1;\n\nconst func2 = (a, b, c) => (\n  1\n);\n\nconst func3 = (a, b, c) => {\n  return 1;\n};\n\nconst func4 = (\n  a,\n  b,\n  c,\n) => 1;\n
\n
\n

Precedence of arrow

\n
\n

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

\n

js

\n
let callback;\n\ncallback = callback || () => {};\n// SyntaxError: invalid arrow-function arguments\n
\n

Because => has a lower precedence than most operators, parentheses are necessary to avoid callback || () being parsed as the arguments list of the arrow function.

\n

js

\n
callback = callback || (() => {});\n
\n
\n

Examples

\n

Using arrow functions

\n
\n

js

\n
// An empty arrow function returns undefined\nconst empty = () => {};\n\n(() => \"foobar\")();\n// Returns \"foobar\"\n// (this is an Immediately Invoked Function Expression)\n\nconst simple = (a) => (a > 15 ? 15 : a);\nsimple(16); // 15\nsimple(10); // 10\n\nconst max = (a, b) => (a > b ? a : b);\n\n// Easy array filtering, mapping, etc.\nconst arr = [5, 6, 13, 0, 1, 18, 23];\n\nconst sum = arr.reduce((a, b) => a + b);\n// 66\n\nconst even = arr.filter((v) => v % 2 === 0);\n// [6, 0, 18]\n\nconst double = arr.map((v) => v * 2);\n// [10, 12, 26, 0, 2, 36, 46]\n\n// More concise promise chains\npromise\n  .then((a) => {\n    // …\n  })\n  .then((b) => {\n    // …\n  });\n\n// Parameterless arrow functions that are visually easier to parse\nsetTimeout(() => {\n  console.log(\"I happen sooner\");\n  setTimeout(() => {\n    // deeper code\n    console.log(\"I happen later\");\n  }, 1);\n}, 1);\n
\n

Using call, bind, and apply

\n
\n

The call(), apply(), and bind() methods work as expected with traditional functions, because we establish the scope for each of the methods:

\n

js

\n
const obj = {\n  num: 100,\n};\n\n// Setting \"num\" on globalThis to show how it is NOT used.\nglobalThis.num = 42;\n\n// A simple traditional function to operate on \"this\"\nconst add = function (a, b, c) {\n  return this.num + a + b + c;\n};\n\nconsole.log(add.call(obj, 1, 2, 3)); // 106\nconsole.log(add.apply(obj, [1, 2, 3])); // 106\nconst boundAdd = add.bind(obj);\nconsole.log(boundAdd(1, 2, 3)); // 106\n
\n

With arrow functions, since our add function is essentially created on the globalThis (global) scope, it will assume this is the globalThis.

\n

js

\n
const obj = {\n  num: 100,\n};\n\n// Setting \"num\" on globalThis to show how it gets picked up.\nglobalThis.num = 42;\n\n// Arrow function\nconst add = (a, b, c) => this.num + a + b + c;\n\nconsole.log(add.call(obj, 1, 2, 3)); // 48\nconsole.log(add.apply(obj, [1, 2, 3])); // 48\nconst boundAdd = add.bind(obj);\nconsole.log(boundAdd(1, 2, 3)); // 48\n
\n

Perhaps the greatest benefit of using arrow functions is with methods like setTimeout() and EventTarget.prototype.addEventListener() that usually require some kind of closure, call(), apply(), or bind() to ensure that the function is executed in the proper scope.

With traditional function expressions, code like this does not work as expected:

\n

js

\n
const obj = {\n  count: 10,\n  doSomethingLater() {\n    setTimeout(function () {\n      // the function executes on the window scope\n      this.count++;\n      console.log(this.count);\n    }, 300);\n  },\n};\n\nobj.doSomethingLater(); // logs \"NaN\", because the property \"count\" is not in the window scope.\n
\n

With arrow functions, the this scope is more easily preserved:

\n

js

\n
const obj = {\n  count: 10,\n  doSomethingLater() {\n    // The method syntax binds \"this\" to the \"obj\" context.\n    setTimeout(() => {\n      // Since the arrow function doesn't have its own binding and\n      // setTimeout (as a function call) doesn't create a binding\n      // itself, the \"obj\" context of the outer method is used.\n      this.count++;\n      console.log(this.count);\n    }, 300);\n  },\n};\n\nobj.doSomethingLater(); // logs 11\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arrow-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Arrow_functions4512
22[\"The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required.\", \"Before Firefox 39, a line terminator (\\\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\\\n => {} will now throw a SyntaxError in this and later versions.\"]
No32104545
22[\"The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required.\", \"Before Firefox 39, a line terminator (\\\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\\\n => {} will now throw a SyntaxError in this and later versions.\"]
32105.01.04.0.0
trailing_comma581252No451058585243107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\n

\n
\n", + "functions/default_parameters": "

Default parameters

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

\n

Try it

\n

Syntax

\n
\n

js

\n
function fnName(param1 = defaultValue1, /* …, */ paramN = defaultValueN) {\n  // …\n}\n
\n

Description

\n
\n

In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help.

In the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return NaN.

\n

js

\n
function multiply(a, b) {\n  return a * b;\n}\n\nmultiply(5, 2); // 10\nmultiply(5); // NaN !\n
\n

In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. In the following example, b is set to 1 if multiply is called with only one argument:

\n

js

\n
function multiply(a, b) {\n  b = typeof b !== \"undefined\" ? b : 1;\n  return a * b;\n}\n\nmultiply(5, 2); // 10\nmultiply(5); // 5\n
\n

With default parameters, checks in the function body are no longer necessary. Now, you can assign 1 as the default value for b in the function head:

\n

js

\n
function multiply(a, b = 1) {\n  return a * b;\n}\n\nmultiply(5, 2); // 10\nmultiply(5); // 5\nmultiply(5, undefined); // 5\n
\n

Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

\n

js

\n
function f(x = 1, y) {\n  return [x, y];\n}\n\nf(); // [1, undefined]\nf(2); // [2, undefined]\n
\n

Note: The first default parameter and all parameters after it will not contribute to the function's length.

The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.

This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time ReferenceError. This also includes var-declared variables in the function body.

For example, the following function will throw a ReferenceError when invoked, because the default parameter value does not have access to the child scope of the function body:

\n

js

\n
function f(a = go()) {\n  function go() {\n    return \":P\";\n  }\n}\n\nf(); // ReferenceError: go is not defined\n
\n

This function will print the value of the parameter a, because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b.

\n

js

\n
function f(a, b = () => console.log(a)) {\n  var a = 1;\n  b();\n}\n\nf(); // undefined\nf(5); // 5\n
\n
\n

Examples

\n

Passing undefined vs. other falsy values

\n
\n

In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.

\n

js

\n
function test(num = 1) {\n  console.log(typeof num);\n}\n\ntest(); // 'number' (num is set to 1)\ntest(undefined); // 'number' (num is set to 1 too)\n\n// test with other falsy values:\ntest(\"\"); // 'string' (num is set to '')\ntest(null); // 'object' (num is set to null)\n
\n
\n

Evaluated at call time

\n
\n

The default argument is evaluated at call time. Unlike with Python (for example), a new object is created each time the function is called.

\n

js

\n
function append(value, array = []) {\n  array.push(value);\n  return array;\n}\n\nappend(1); // [1]\nappend(2); // [2], not [1, 2]\n
\n

This even applies to functions and variables:

\n

js

\n
function callSomething(thing = something()) {\n  return thing;\n}\n\nlet numberOfTimesCalled = 0;\nfunction something() {\n  numberOfTimesCalled += 1;\n  return numberOfTimesCalled;\n}\n\ncallSomething(); // 1\ncallSomething(); // 2\n
\n
\n

Earlier parameters are available to later default parameters

\n
\n

Parameters defined earlier (to the left) are available to later default parameters:

\n

js

\n
function greet(name, greeting, message = `${greeting}${name}`) {\n  return [name, greeting, message];\n}\n\ngreet(\"David\", \"Hi\"); // [\"David\", \"Hi\", \"Hi David\"]\ngreet(\"David\", \"Hi\", \"Happy Birthday!\"); // [\"David\", \"Hi\", \"Happy Birthday!\"]\n
\n

This functionality can be approximated like this, which demonstrates how many edge cases are handled:

\n

js

\n
function go() {\n  return \":P\";\n}\n\nfunction withDefaults(\n  a,\n  b = 5,\n  c = b,\n  d = go(),\n  e = this,\n  f = arguments,\n  g = this.value,\n) {\n  return [a, b, c, d, e, f, g];\n}\n\nfunction withoutDefaults(a, b, c, d, e, f, g) {\n  switch (arguments.length) {\n    case 0:\n    case 1:\n      b = 5;\n    case 2:\n      c = b;\n    case 3:\n      d = go();\n    case 4:\n      e = this;\n    case 5:\n      f = arguments;\n    case 6:\n      g = this.value;\n  }\n  return [a, b, c, d, e, f, g];\n}\n\nwithDefaults.call({ value: \"=^_^=\" });\n// [undefined, 5, 5, \":P\", {value:\"=^_^=\"}, arguments, \"=^_^=\"]\n\nwithoutDefaults.call({ value: \"=^_^=\" });\n// [undefined, 5, 5, \":P\", {value:\"=^_^=\"}, arguments, \"=^_^=\"]\n
\n
\n

Destructured parameter with default value assignment

\n
\n

You can use default value assignment with the destructuring assignment syntax.

A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: [x = 1, y = 2] = []. This makes it possible to pass nothing to the function and still have those values prefilled:

\n

js

\n
function preFilledArray([x = 1, y = 2] = []) {\n  return x + y;\n}\n\npreFilledArray(); // 3\npreFilledArray([]); // 3\npreFilledArray([2]); // 4\npreFilledArray([2, 3]); // 5\n\n// Works the same for objects:\nfunction preFilledObject({ z = 3 } = {}) {\n  return z;\n}\n\npreFilledObject(); // 3\npreFilledObject({}); // 3\npreFilledObject({ z: 2 }); // 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Default_parameters491415No361049491536105.01.06.0.0
destructured_parameter_with_default_value_assignment491441No361049494136105.01.06.0.0
parameters_without_defaults_after_default_parameters491426No361049492636105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\n

\n
\n", + "functions/rest_parameters": "

Rest parameters

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

\n

Try it

\n

Syntax

\n
\n

js

\n
function f(a, b, ...theArgs) {\n  // …\n}\n
\n

Description

\n
\n

A function definition's last parameter can be prefixed with ... (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within an Array object.

\n

js

\n
function myFun(a, b, ...manyMoreArgs) {\n  console.log(\"a\", a);\n  console.log(\"b\", b);\n  console.log(\"manyMoreArgs\", manyMoreArgs);\n}\n\nmyFun(\"one\", \"two\", \"three\", \"four\", \"five\", \"six\");\n\n// Console Output:\n// a, one\n// b, two\n// manyMoreArgs, [\"three\", \"four\", \"five\", \"six\"]\n
\n

A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.

\n

js

\n
function wrong1(...one, ...wrong) {}\nfunction wrong2(...wrong, arg2, arg3) {}\n
\n

The rest parameter is not counted towards the function's length property.

\n

The difference between rest parameters and the arguments object

\n
\n

There are three main differences between rest parameters and the arguments object:

\n

Examples

\n

Using rest parameters

\n
\n

In this example, the first argument is mapped to a and the second to b, so these named arguments are used as normal.

However, the third argument, manyMoreArgs, will be an array that contains the third, fourth, fifth, sixth, …, nth — as many arguments as the user specifies.

\n

js

\n
function myFun(a, b, ...manyMoreArgs) {\n  console.log(\"a\", a);\n  console.log(\"b\", b);\n  console.log(\"manyMoreArgs\", manyMoreArgs);\n}\n\nmyFun(\"one\", \"two\", \"three\", \"four\", \"five\", \"six\");\n\n// a, \"one\"\n// b, \"two\"\n// manyMoreArgs, [\"three\", \"four\", \"five\", \"six\"] <-- an array\n
\n

Below, even though there is just one value, the last argument still gets put into an array.

\n

js

\n
// Using the same function definition from example above\n\nmyFun(\"one\", \"two\", \"three\");\n\n// a, \"one\"\n// b, \"two\"\n// manyMoreArgs, [\"three\"] <-- an array with just one value\n
\n

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

\n

js

\n
// Using the same function definition from example above\n\nmyFun(\"one\", \"two\");\n\n// a, \"one\"\n// b, \"two\"\n// manyMoreArgs, [] <-- still an array\n
\n

Below, only one argument is provided, so b gets the default value undefined, but manyMoreArgs is still an empty array.

\n

js

\n
// Using the same function definition from example above\n\nmyFun(\"one\");\n\n// a, \"one\"\n// b, undefined\n// manyMoreArgs, [] <-- still an array\n
\n
\n

Argument length

\n
\n

Since theArgs is an array, a count of its elements is given by the length property. If the function's only parameter is a rest parameter, restParams.length will be equal to arguments.length.

\n

js

\n
function fun1(...theArgs) {\n  console.log(theArgs.length);\n}\n\nfun1(); // 0\nfun1(5); // 1\nfun1(5, 6, 7); // 3\n
\n
\n

Using rest parameters in combination with ordinary parameters

\n
\n

In the next example, a rest parameter is used to collect all parameters after the first parameter into an array. Each one of the parameter values collected into the array is then multiplied by the first parameter, and the array is returned:

\n

js

\n
function multiply(multiplier, ...theArgs) {\n  return theArgs.map((element) => multiplier * element);\n}\n\nconst arr = multiply(2, 15, 25, 42);\nconsole.log(arr); // [30, 50, 84]\n
\n
\n

From arguments to an array

\n
\n

Array methods can be used on rest parameters, but not on the arguments object:

\n

js

\n
function sortRestArgs(...theArgs) {\n  const sortedArgs = theArgs.sort();\n  return sortedArgs;\n}\n\nconsole.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7\n\nfunction sortArguments() {\n  const sortedArgs = arguments.sort();\n  return sortedArgs; // this will never happen\n}\n\nconsole.log(sortArguments(5, 3, 7, 1));\n// throws a TypeError (arguments.sort is not a function)\n
\n

Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.

Before rest parameters, arguments need to be converted to a normal array before calling array methods on them:

\n

js

\n
function fn(a, b) {\n  const normalArray = Array.prototype.slice.call(arguments);\n  // — or —\n  const normalArray2 = [].slice.call(arguments);\n  // — or —\n  const normalArrayFrom = Array.from(arguments);\n\n  const first = normalArray.shift(); // OK, gives the first argument\n  const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)\n}\n
\n

Now, you can easily gain access to a normal array using a rest parameter:

\n

js

\n
function fn(...args) {\n  const normalArray = args;\n  const first = normalArray.shift(); // OK, gives the first argument\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
rest_parameters471215No341047471534105.01.06.0.0
destructuring497952No361049495236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters\n

\n
\n", + "functions/arguments": "

The arguments object

arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.

\n

Try it

\n

Description

\n
\n

Note: In modern code, rest parameters should be preferred.

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

For example, if a function is passed 3 arguments, you can access them as follows:

\n

js

\n
arguments[0]; // first argument\narguments[1]; // second argument\narguments[2]; // third argument\n
\n

The arguments object is useful for functions called with more arguments than they are formally declared to accept, called variadic functions, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

\n

js

\n
function longestString() {\n  let longest = \"\";\n  for (let i = 0; i < arguments.length; i++) {\n    if (arguments[i].length > longest.length) {\n      longest = arguments[i];\n    }\n  }\n  return longest;\n}\n
\n

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

\n

Assigning to indices

\n
\n

Each argument index can also be set or reassigned:

\n

js

\n
arguments[1] = \"new value\";\n
\n

Non-strict functions that only has simple parameters (that is, no rest, default, or destructured parameters) will sync the new value of parameters with the arguments object, and vice versa:

\n

js

\n
function func(a) {\n  arguments[0] = 99; // updating arguments[0] also updates a\n  console.log(a);\n}\nfunc(10); // 99\n\nfunction func2(a) {\n  a = 99; // updating a also updates arguments[0]\n  console.log(arguments[0]);\n}\nfunc2(10); // 99\n
\n

Non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to parameters in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called.

\n

js

\n
function funcWithDefault(a = 55) {\n  arguments[0] = 99; // updating arguments[0] does not also update a\n  console.log(a);\n}\nfuncWithDefault(10); // 10\n\nfunction funcWithDefault2(a = 55) {\n  a = 99; // updating a does not also update arguments[0]\n  console.log(arguments[0]);\n}\nfuncWithDefault2(10); // 10\n\n// An untracked default parameter\nfunction funcWithDefault3(a = 55) {\n  console.log(arguments[0]);\n  console.log(arguments.length);\n}\nfuncWithDefault3(); // undefined; 0\n
\n

This is the same behavior exhibited by all strict-mode functions, regardless of the type of parameters they are passed. That is, assigning new values to parameters in the body of the function never affects the arguments object, nor will assigning new values to the arguments indices affect the value of parameters, even when the function only has simple parameters.

Note: You cannot write a \"use strict\"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

\n

arguments is an array-like object

\n
\n

arguments is an array-like object, which means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() or map(). However, it can be converted to a real Array, using one of slice(), Array.from(), or spread syntax.

\n

js

\n
const args = Array.prototype.slice.call(arguments);\n// or\nconst args = Array.from(arguments);\n// or\nconst args = [...arguments];\n
\n

For common use cases, using it as an array-like object is sufficient, since it both is iterable and has length and number indices. For example, Function.prototype.apply() accepts array-like objects.

\n

js

\n
function midpoint() {\n  return (\n    (Math.min.apply(null, arguments) + Math.max.apply(null, arguments)) / 2\n  );\n}\n\nconsole.log(midpoint(3, 1, 4, 1, 5)); // 3\n
\n
\n

Properties

\n
\narguments.callee Deprecated \n

Reference to the currently executing function that the arguments belong to. Forbidden in strict mode.

arguments.length

The number of arguments that were passed to the function.

arguments[@@iterator]

Returns a new Array iterator object that contains the values for each index in arguments.

Examples

\n

Defining a function that concatenates several strings

\n
\n

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

\n

js

\n
function myConcat(separator) {\n  const args = Array.prototype.slice.call(arguments, 1);\n  return args.join(separator);\n}\n
\n

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

\n

js

\n
myConcat(\", \", \"red\", \"orange\", \"blue\");\n// \"red, orange, blue\"\n\nmyConcat(\"; \", \"elephant\", \"giraffe\", \"lion\", \"cheetah\");\n// \"elephant; giraffe; lion; cheetah\"\n\nmyConcat(\". \", \"sage\", \"basil\", \"oregano\", \"pepper\", \"parsley\");\n// \"sage. basil. oregano. pepper. parsley\"\n
\n
\n

Defining a function that creates HTML lists

\n
\n

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is \"u\" if the list is to be unordered (bulleted), or \"o\" if the list is to be ordered (numbered). The function is defined as follows:

\n

js

\n
function list(type) {\n  let html = `<${type}l><li>`;\n  const args = Array.prototype.slice.call(arguments, 1);\n  html += args.join(\"</li><li>\");\n  html += `</li></${type}l>`; // end list\n  return html;\n}\n
\n

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

\n

js

\n
list(\"u\", \"One\", \"Two\", \"Three\");\n// \"<ul><li>One</li><li>Two</li><li>Three</li></ul>\"\n
\n
\n

Using typeof with arguments

\n
\n

The typeof operator returns 'object' when used with arguments

\n

js

\n
console.log(typeof arguments); // 'object'\n
\n

The type of individual arguments can be determined by indexing arguments:

\n

js

\n
console.log(typeof arguments[0]); // returns the type of the first argument\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arguments-exotic-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator521246No3995252464196.01.04.0.0
arguments11213314.418410.111.01.00.10.0
callee11216414.418410.111.01.00.10.0
length11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments\n

\n
\n", + "functions/method_definitions": "

Method definitions

Method definition is a shorter syntax for defining a function property in an object initializer. It can also be used in classes.

\n

Try it

\n

Syntax

\n
\n

js

\n
({\n  property(parameters) {},\n  *generator(parameters) {},\n  async property(parameters) {},\n  async *generator(parameters) {},\n\n  // with computed keys\n  [expression](parameters) {},\n  *[expression](parameters) {},\n  async [expression](parameters) {},\n  async *[expression](parameters) {},\n})\n
\n

Description

\n
\n

The shorthand syntax is similar to the getter and setter syntax.

Given the following code:

\n

js

\n
const obj = {\n  foo: function () {\n    // …\n  },\n  bar: function () {\n    // …\n  },\n};\n
\n

You are now able to shorten this to:

\n

js

\n
const obj = {\n  foo() {\n    // …\n  },\n  bar() {\n    // …\n  },\n};\n
\n

function*, async function, and async function* properties all have their respective method syntaxes; see examples below.

However, note that the method syntax is not equivalent to a normal property with a function as its value — there are semantic differences. This makes methods defined in object literals more consistent with methods in classes.

\n

Method definitions are not constructable

\n
\n

Methods cannot be constructors! They will throw a TypeError if you try to instantiate them. On the other hand, a property created as a function can be used as a constructor.

\n

js

\n
const obj = {\n  method() {},\n};\nnew obj.method(); // TypeError: obj.method is not a constructor\n
\n
\n

Using super in method definitions

\n
\n

Only functions defined as methods have access to the super keyword. super.prop looks up the property on the prototype of the object that the method was initialized on.

\n

js

\n
const obj = {\n  __proto__: {\n    prop: \"foo\",\n  },\n  notAMethod: function () {\n    console.log(super.prop); // SyntaxError: 'super' keyword unexpected here\n  },\n};\n
\n
\n

Examples

\n

Using method definitions

\n
\n

js

\n
const obj = {\n  a: \"foo\",\n  b() {\n    return this.a;\n  },\n};\nconsole.log(obj.b()); // \"foo\"\n
\n

Method definitions in classes

\n
\n

You can use the exact same syntax to define public instance methods that are available on class instances. In classes, you don't need the comma separator between methods.

\n

js

\n
class ClassWithPublicInstanceMethod {\n  publicMethod() {\n    return \"hello world\";\n  }\n  secondPublicMethod() {\n    return \"goodbye world\";\n  }\n}\n\nconst instance = new ClassWithPublicInstanceMethod();\nconsole.log(instance.publicMethod()); // \"hello world\"\n
\n

Public instance methods are defined on the prototype property of the class and are thus shared by all instances of the class. They are writable, non-enumerable, and configurable.

Inside instance methods, this and super work like in normal methods. Usually, this refers to the instance itself. In subclasses, super lets you access the prototype of the object that the method is attached to, allowing you to call methods from the superclass.

\n

js

\n
class BaseClass {\n  msg = \"hello world\";\n  basePublicMethod() {\n    return this.msg;\n  }\n}\n\nclass SubClass extends BaseClass {\n  subPublicMethod() {\n    return super.basePublicMethod();\n  }\n}\n\nconst instance = new SubClass();\nconsole.log(instance.subPublicMethod()); // \"hello world\"\n
\n

Static methods and private methods use similar syntaxes, which are described in the static and private class features pages.

\n

Computed property names

\n
\n

The method syntax also supports computed property names.

\n

js

\n
const bar = {\n  foo0: function () {\n    return 0;\n  },\n  foo1() {\n    return 1;\n  },\n  [\"foo\" + 2]() {\n    return 2;\n  },\n};\n\nconsole.log(bar.foo0()); // 0\nconsole.log(bar.foo1()); // 1\nconsole.log(bar.foo2()); // 2\n
\n
\n

Generator methods

\n
\n

Note that the asterisk (*) in the generator method syntax must be before the generator property name. (That is, * g(){} will work, but g *(){} will not.)

\n

js

\n
// Using a named property\nconst obj = {\n  g: function* () {\n    let index = 0;\n    while (true) {\n      yield index++;\n    }\n  },\n};\n\n// The same object using shorthand syntax\nconst obj2 = {\n  *g() {\n    let index = 0;\n    while (true) {\n      yield index++;\n    }\n  },\n};\n\nconst it = obj2.g();\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\n
\n
\n

Async methods

\n
\n

js

\n
// Using a named property\nconst obj = {\n  f: async function () {\n    await somePromise;\n  },\n};\n\n// The same object using shorthand syntax\nconst obj2 = {\n  async f() {\n    await somePromise;\n  },\n};\n
\n

Async generator methods

\n
\n

js

\n
const obj = {\n  f: async function* () {\n    yield 1;\n    yield 2;\n    yield 3;\n  },\n};\n\n// The same object using shorthand syntax\nconst obj2 = {\n  async *f() {\n    yield 1;\n    yield 2;\n    yield 3;\n  },\n};\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-method-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Method_definitions391234No2693939342694.01.04.0.0
async_generator_methods637955No501263635546128.01.010.0.0
async_methods551552No4210.15555524210.36.01.07.6.0
generator_methods_not_constructable421343No299.1424243299.34.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions\n

\n
\n", + "functions/get": "

get

The get syntax binds an object property to a function that will be called when that property is looked up. It can also be used in classes.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
{ get prop() { /* … */ } }\n{ get [expression]() { /* … */ } }\n
\n

There are some additional syntax restrictions:

\n

Parameters

\n
prop

The name of the property to bind to the given function. In the same way as other properties in object initializers, it can be a string literal, a number literal, or an identifier.

expression

You can also use expressions for a computed property name to bind to the given function.

Description

\n
\n

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

\n

Examples

\n

Defining a getter on new objects in object initializers

\n
\n

This will create a pseudo-property latest for object obj, which will return the last array item in log.

\n

js

\n
const obj = {\n  log: [\"example\", \"test\"],\n  get latest() {\n    if (this.log.length === 0) return undefined;\n    return this.log[this.log.length - 1];\n  },\n};\nconsole.log(obj.latest); // \"test\"\n
\n

Note that attempting to assign a value to latest will not change it.

\n

Using getters in classes

\n
\n

You can use the exact same syntax to define public instance getters that are available on class instances. In classes, you don't need the comma separator between methods.

\n

js

\n
class ClassWithGetSet {\n  #msg = \"hello world\";\n  get msg() {\n    return this.#msg;\n  }\n  set msg(x) {\n    this.#msg = `hello ${x}`;\n  }\n}\n\nconst instance = new ClassWithGetSet();\nconsole.log(instance.msg); // \"hello world\"\n\ninstance.msg = \"cake\";\nconsole.log(instance.msg); // \"hello cake\"\n
\n

Getter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike getter properties in object literals, getter properties in classes are not enumerable.

Static getters and private getters use similar syntaxes, which are described in the static and private class features pages.

\n

Deleting a getter using the delete operator

\n
\n

If you want to remove the getter, you can just delete it:

\n

js

\n
delete obj.latest;\n
\n
\n

Defining a getter on existing objects using defineProperty\n

\n
\n

To append a getter to an existing object later at any time, use Object.defineProperty().

\n

js

\n
const o = { a: 0 };\n\nObject.defineProperty(o, \"b\", {\n  get() {\n    return this.a + 1;\n  },\n});\n\nconsole.log(o.b); // Runs the getter, which yields a + 1 (which is 1)\n
\n
\n

Using a computed property name

\n
\n

js

\n
const expr = \"foo\";\n\nconst obj = {\n  get [expr]() {\n    return \"bar\";\n  },\n};\n\nconsole.log(obj.foo); // \"bar\"\n
\n

Defining static getters

\n
\n

js

\n
class MyConstants {\n  static get foo() {\n    return \"foo\";\n  }\n}\n\nconsole.log(MyConstants.foo); // 'foo'\nMyConstants.foo = \"bar\";\nconsole.log(MyConstants.foo); // 'foo', a static getter's value cannot be changed\n
\n

Smart / self-overwriting / lazy getters

\n
\n

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.

An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or memoized) getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:

Note: This means that you shouldn't write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.

Note that getters are not \"lazy\" or \"memoized\" by nature; you must implement this technique if you desire this behavior.

In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.

\n

js

\n
const obj = {\n  get notifier() {\n    delete this.notifier;\n    this.notifier = document.getElementById(\"bookmarked-notification-anchor\");\n    return this.notifier;\n  },\n};\n
\n
\n

get vs. defineProperty

\n
\n

While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes.

When using get the property will be defined on the instance's prototype, while using Object.defineProperty() the property will be defined on the instance it is applied to.

\n

js

\n
class Example {\n  get hello() {\n    return \"world\";\n  }\n}\n\nconst obj = new Example();\nconsole.log(obj.hello);\n// \"world\"\n\nconsole.log(Object.getOwnPropertyDescriptor(obj, \"hello\"));\n// undefined\n\nconsole.log(\n  Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), \"hello\"),\n);\n// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-method-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
get1121.599.534.41841411.01.00.10.0
computed_property_names461234No479.1464634339.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get\n

\n
\n", + "functions/set": "

set

The set syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in classes.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
{ set prop(val) { /* … */ } }\n{ set [expression](val) { /* … */ } }\n
\n

There are some additional syntax restrictions:

\n

Parameters

\n
prop

The name of the property to bind to the given function. In the same way as other properties in object initializers, it can be a string literal, a number literal, or an identifier.

val

An alias for the variable that holds the value attempted to be assigned to prop.

expression

You can also use expressions for a computed property name to bind to the given function.

Description

\n

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.

Examples

\n

Defining a setter on new objects in object initializers

\n
\n

The following example defines a pseudo-property current of object language. When current is assigned a value, it updates log with that value:

\n

js

\n
const language = {\n  set current(name) {\n    this.log.push(name);\n  },\n  log: [],\n};\n\nlanguage.current = \"EN\";\nconsole.log(language.log); // ['EN']\n\nlanguage.current = \"FA\";\nconsole.log(language.log); // ['EN', 'FA']\n
\n

Note that current is not defined, and any attempts to access it will result in undefined.

\n

Using setters in classes

\n
\n

You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.

\n

js

\n
class ClassWithGetSet {\n  #msg = \"hello world\";\n  get msg() {\n    return this.#msg;\n  }\n  set msg(x) {\n    this.#msg = `hello ${x}`;\n  }\n}\n\nconst instance = new ClassWithGetSet();\nconsole.log(instance.msg); // \"hello world\"\n\ninstance.msg = \"cake\";\nconsole.log(instance.msg); // \"hello cake\"\n
\n

Setter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.

Static setters and private setters use similar syntaxes, which are described in the static and private class features pages.

\n

Removing a setter with the delete operator

\n
\n

If you want to remove the setter, you can just delete it:

\n

js

\n
delete language.current;\n
\n
\n

Defining a setter on existing objects using defineProperty\n

\n
\n

To append a setter to an existing object, use Object.defineProperty().

\n

js

\n
const o = { a: 0 };\n\nObject.defineProperty(o, \"b\", {\n  set(x) {\n    this.a = x / 2;\n  },\n});\n\no.b = 10;\n// Runs the setter, which assigns 10 / 2 (5) to the 'a' property\n\nconsole.log(o.a); // 5\n
\n
\n

Using a computed property name

\n
\n

js

\n
const expr = \"foo\";\n\nconst obj = {\n  baz: \"bar\",\n  set [expr](v) {\n    this.baz = v;\n  },\n};\n\nconsole.log(obj.baz); // \"bar\"\n\nobj.foo = \"baz\";\n// Run the setter\n\nconsole.log(obj.baz); // \"baz\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-method-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set1121.599.534.41841411.01.00.10.0
computed_property_names461234No479.1464634339.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set\n

\n
\n", + "classes": "

Classes

\n

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are unique to classes.

For more examples and explanations, see the Using classes guide.

\n
\n

Description

\n

Defining classes

\n
\n

Classes are in fact \"special functions\", and just as you can define function expressions and function declarations, a class can be defined in two ways: a class expression or a class declaration.

\n

js

\n
// Declaration\nclass Rectangle {\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n}\n\n// Expression; the class is anonymous but assigned to a variable\nconst Rectangle = class {\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n};\n\n// Expression; the class has its own name\nconst Rectangle = class Rectangle2 {\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n};\n
\n

Like function expressions, class expressions may be anonymous, or have a name that's different from the variable that it's assigned to. However, unlike function declarations, class declarations have the same temporal dead zone restrictions as let or const and behave as if they are not hoisted.

\n

Class body

\n
\n

The body of a class is the part that is in curly braces {}. This is where you define class members, such as methods or constructor.

The body of a class is executed in strict mode even without the \"use strict\" directive.

A class element can be characterized by three aspects:

Together, they add up to 16 possible combinations. To divide the reference more logically and avoid overlapping content, the different elements are introduced in detail in different pages:

Method definitions

Public instance method

getter

Public instance getter

setter

Public instance setter

Public class fields

Public instance field

static

Public static method, getter, setter, and field

Private class features

Everything that's private

Note: Private features have the restriction that all property names declared in the same class must be unique. All other public properties do not have this restriction — you can have multiple public properties with the same name, and the last one overwrites the others. This is the same behavior as in object initializers.

In addition, there are two special class element syntaxes: constructor and static initialization blocks, with their own references.

Constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name \"constructor\" in a class — a SyntaxError is thrown if the class contains more than one occurrence of a constructor method.

A constructor can use the super keyword to call the constructor of the super class.

You can create instance properties inside the constructor:

\n

js

\n
class Rectangle {\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n}\n
\n

Alternatively, if your instance properties' values do not depend on the constructor's arguments, you can define them as class fields.

Static initialization blocks

Static initialization blocks allow flexible initialization of static properties, including the evaluation of statements during initialization, while granting access to the private scope.

Multiple static blocks can be declared, and these can be interleaved with the declaration of static fields and methods (all static items are evaluated in declaration order).

Methods

Methods are defined on the prototype of each class instance and are shared by all instances. Methods can be plain functions, async functions, generator functions, or async generator functions. For more information, see method definitions.

\n

js

\n
class Rectangle {\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n  // Getter\n  get area() {\n    return this.calcArea();\n  }\n  // Method\n  calcArea() {\n    return this.height * this.width;\n  }\n  *getSides() {\n    yield this.height;\n    yield this.width;\n    yield this.height;\n    yield this.width;\n  }\n}\n\nconst square = new Rectangle(10, 10);\n\nconsole.log(square.area); // 100\nconsole.log([...square.getSides()]); // [10, 10, 10, 10]\n
\n

Static methods and fields

The static keyword defines a static method or field for a class. Static properties (fields and methods) are defined on the class itself instead of each instance. Static methods are often used to create utility functions for an application, whereas static fields are useful for caches, fixed-configuration, or any other data that doesn't need to be replicated across instances.

\n

js

\n
class Point {\n  constructor(x, y) {\n    this.x = x;\n    this.y = y;\n  }\n\n  static displayName = \"Point\";\n  static distance(a, b) {\n    const dx = a.x - b.x;\n    const dy = a.y - b.y;\n\n    return Math.hypot(dx, dy);\n  }\n}\n\nconst p1 = new Point(5, 5);\nconst p2 = new Point(10, 10);\np1.displayName; // undefined\np1.distance; // undefined\np2.displayName; // undefined\np2.distance; // undefined\n\nconsole.log(Point.displayName); // \"Point\"\nconsole.log(Point.distance(p1, p2)); // 7.0710678118654755\n
\n

Field declarations

With the class field declaration syntax, the constructor example can be written as:

\n

js

\n
class Rectangle {\n  height = 0;\n  width;\n  constructor(height, width) {\n    this.height = height;\n    this.width = width;\n  }\n}\n
\n

Class fields are similar to object properties, not variables, so we don't use keywords such as const to declare them. In JavaScript, private features use a special identifier syntax, so modifier keywords like public and private should not be used either.

As seen above, the fields can be declared with or without a default value. Fields without default values default to undefined. By declaring fields up-front, class definitions become more self-documenting, and the fields are always present, which help with optimizations.

See public class fields for more information.

Private class features

Using private fields, the definition can be refined as below.

\n

js

\n
class Rectangle {\n  #height = 0;\n  #width;\n  constructor(height, width) {\n    this.#height = height;\n    this.#width = width;\n  }\n}\n
\n

It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things that are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change from version to version.

Private fields can only be declared up-front in a field declaration. They cannot be created later through assigning to them, the way that normal properties can.

For more information, see private class features.

\n

Inheritance

\n
\n

The extends keyword is used in class declarations or class expressions to create a class as a child of another constructor (either a class or a function).

\n

js

\n
class Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name) {\n    super(name); // call the super class constructor and pass in the name parameter\n  }\n\n  speak() {\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst d = new Dog(\"Mitzie\");\nd.speak(); // Mitzie barks.\n
\n

If there is a constructor present in the subclass, it needs to first call super() before using this. The super keyword can also be used to call corresponding methods of super class.

\n

js

\n
class Cat {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Lion extends Cat {\n  speak() {\n    super.speak();\n    console.log(`${this.name} roars.`);\n  }\n}\n\nconst l = new Lion(\"Fuzzy\");\nl.speak();\n// Fuzzy makes a noise.\n// Fuzzy roars.\n
\n
\n

Evaluation order

\n
\n

When a class declaration or class expression is evaluated, its various components are evaluated in the following order:

  1. The extends clause, if present, is first evaluated. It must evaluate to a valid constructor function or null, or a TypeError is thrown.
  2. The constructor method is extracted, substituted with a default implementation if constructor is not present. However, because the constructor definition is only a method definition, this step is not observable.
  3. The class elements' property keys are evaluated in the order of declaration. If the property key is computed, the computed expression is evaluated, with the this value set to the this value surrounding the class (not the class itself). None of the property values are evaluated yet.
  4. Methods and accessors are installed in the order of declaration. Instance methods and accessors are installed on the prototype property of the current class, and static methods and accessors are installed on the class itself. Private instance methods and accessors are saved to be installed on the instance directly later. This step is not observable.
  5. The class is now initialized with the prototype specified by extends and implementation specified by constructor. For all steps above, if an evaluated expression tries to access the name of the class, a ReferenceError is thrown because the class is not initialized yet.
  6. The class elements' values are evaluated in the order of declaration:
    • For each instance field (public or private), its initializer expression is saved. The initializer is evaluated during instance creation, at the start of the constructor (for base classes) or immediately before the super() call returns (for derived classes).
    • For each static field (public or private), its initializer is evaluated with this set to the class itself, and the property is created on the class.
    • \nStatic initialization blocks are evaluated with this set to the class itself.
  7. The class is now fully initialized and can be used as a constructor function.

For how instances are created, see the constructor reference.

\n

Examples

\n

Binding this with instance and static methods

\n
\n

When a static or instance method is called without a value for this, such as by assigning the method to a variable and then calling it, the this value will be undefined inside the method. This behavior is the same even if the \"use strict\" directive isn't present, because code within the class body is always executed in strict mode.

\n

js

\n
class Animal {\n  speak() {\n    return this;\n  }\n  static eat() {\n    return this;\n  }\n}\n\nconst obj = new Animal();\nobj.speak(); // the Animal object\nconst speak = obj.speak;\nspeak(); // undefined\n\nAnimal.eat(); // class Animal\nconst eat = Animal.eat;\neat(); // undefined\n
\n

If we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls are automatically bound to globalThis. In strict mode, the value of this remains as undefined.

\n

js

\n
function Animal() {}\n\nAnimal.prototype.speak = function () {\n  return this;\n};\n\nAnimal.eat = function () {\n  return this;\n};\n\nconst obj = new Animal();\nconst speak = obj.speak;\nspeak(); // global object (in non–strict mode)\n\nconst eat = Animal.eat;\neat(); // global object (in non-strict mode)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-class-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Classes49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
constructor49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
extends49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
private_class_fields747990No6214.17474905314.511.01.012.0.0
private_class_fields_in919190No7715919190641516.01.916.4.0
private_class_methods848490No7015848490601514.01.014.6.0
public_class_fields727969No6014.1
14–14.1Doesn't support public static fields. See WebKit bug 194095.
\n
7272795114.5
14–14.5Doesn't support public static fields. See WebKit bug 194095.
\n
11.01.012.0.0
static49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
static_class_fields727975No6014.17272795114.511.01.012.0.0
static_initialization_blocks949493No8016.49494936616.417.01.1416.11.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\n

\n
\n", + "classes/constructor": "

constructor

\n

The constructor method is a special method of a class for creating and initializing an object instance of that class.

Note: This page introduces the constructor syntax. For the constructor property present on all objects, see Object.prototype.constructor.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
constructor() { /* … */ }\nconstructor(argument0) { /* … */ }\nconstructor(argument0, argument1) { /* … */ }\nconstructor(argument0, argument1, /* …, */ argumentN) { /* … */ }\n
\n

There are some additional syntax restrictions:

\n

Description

\n
\n

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

\n

js

\n
class Person {\n  constructor(name) {\n    this.name = name;\n  }\n\n  introduce() {\n    console.log(`Hello, my name is ${this.name}`);\n  }\n}\n\nconst otto = new Person(\"Otto\");\n\notto.introduce(); // Hello, my name is Otto\n
\n

If you don't provide your own constructor, then a default constructor will be supplied for you. If your class is a base class, the default constructor is empty:

\n

js

\n
constructor() {}\n
\n

If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:

\n

js

\n
constructor(...args) {\n  super(...args);\n}\n
\n

Note: The difference between an explicit constructor like the one above and the default constructor is that the latter doesn't actually invoke the array iterator through argument spreading.

That enables code like this to work:

\n

js

\n
class ValidationError extends Error {\n  printCustomerMessage() {\n    return `Validation failed :-( (details: ${this.message})`;\n  }\n}\n\ntry {\n  throw new ValidationError(\"Not a valid phone number\");\n} catch (error) {\n  if (error instanceof ValidationError) {\n    console.log(error.name); // This is Error instead of ValidationError!\n    console.log(error.printCustomerMessage());\n  } else {\n    console.log(\"Unknown error\", error);\n    throw error;\n  }\n}\n
\n

The ValidationError class doesn't need an explicit constructor, because it doesn't need to do any custom initialization. The default constructor then takes care of initializing the parent Error from the argument it is given.

However, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using super(). For example:

\n

js

\n
class ValidationError extends Error {\n  constructor(message) {\n    super(message); // call parent class constructor\n    this.name = \"ValidationError\";\n    this.code = \"42\";\n  }\n\n  printCustomerMessage() {\n    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;\n  }\n}\n\ntry {\n  throw new ValidationError(\"Not a valid phone number\");\n} catch (error) {\n  if (error instanceof ValidationError) {\n    console.log(error.name); // Now this is ValidationError!\n    console.log(error.printCustomerMessage());\n  } else {\n    console.log(\"Unknown error\", error);\n    throw error;\n  }\n}\n
\n

Using new on a class goes through the following steps:

  1. (If it's a derived class) The constructor body before the super() call is evaluated. This part should not access this because it's not yet initialized.
  2. (If it's a derived class) The super() call is evaluated, which initializes the parent class through the same process.
  3. The current class's fields are initialized.
  4. The constructor body after the super() call (or the entire body, if it's a base class) is evaluated.

Within the constructor body, you can access the object being created through this and access the class that is called with new through new.target. Note that methods (including getters and setters) and the prototype chain are already initialized on this before the constructor is executed, so you can even access methods of the subclass from the constructor of the superclass. However, if those methods use this, the this will not have been fully initialized yet. This means reading public fields of the derived class will result in undefined, while reading private fields will result in a TypeError.

\n

js

\n
new (class C extends class B {\n  constructor() {\n    console.log(this.foo());\n  }\n} {\n  #a = 1;\n  foo() {\n    return this.#a; // TypeError: Cannot read private member #a from an object whose class did not declare it\n    // It's not really because the class didn't declare it,\n    // but because the private field isn't initialized yet\n    // when the superclass constructor is running\n  }\n})();\n
\n

The constructor method may have a return value. While the base class may return anything from its constructor, the derived class must return an object or undefined, or a TypeError will be thrown.

\n

js

\n
class ParentClass {\n  constructor() {\n    return 1;\n  }\n}\n\nconsole.log(new ParentClass()); // ParentClass {}\n// The return value is ignored because it's not an object\n// This is consistent with function constructors\n\nclass ChildClass extends ParentClass {\n  constructor() {\n    return 1;\n  }\n}\n\nconsole.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined\n
\n

If the parent class constructor returns an object, that object will be used as the this value on which class fields of the derived class will be defined. This trick is called \"return overriding\", which allows a derived class's fields (including private ones) to be defined on unrelated objects.

The constructor follows normal method syntax, so parameter default values, rest parameters, etc. can all be used.

\n

js

\n
class Person {\n  constructor(name = \"Anonymous\") {\n    this.name = name;\n  }\n  introduce() {\n    console.log(`Hello, my name is ${this.name}`);\n  }\n}\n\nconst person = new Person();\nperson.introduce(); // Hello, my name is Anonymous\n
\n

The constructor must be a literal name. Computed properties cannot become constructors.

\n

js

\n
class Foo {\n  // This is a computed property. It will not be picked up as a constructor.\n  [\"constructor\"]() {\n    console.log(\"called\");\n    this.a = 1;\n  }\n}\n\nconst foo = new Foo(); // No log\nconsole.log(foo); // Foo {}\nfoo.constructor(); // Logs \"called\"\nconsole.log(foo); // Foo { a: 1 }\n
\n

Async methods, generator methods, accessors, and class fields are forbidden from being called constructor. Private names cannot be called #constructor. Any member named constructor must be a plain method.

\n

Examples

\n

Using the constructor

\n
\n

This code snippet is taken from the classes sample (live demo).

\n

js

\n
class Square extends Polygon {\n  constructor(length) {\n    // Here, it calls the parent class' constructor with lengths\n    // provided for the Polygon's width and height\n    super(length, length);\n    // NOTE: In derived classes, `super()` must be called before you\n    // can use `this`. Leaving this out will cause a ReferenceError.\n    this.name = \"Square\";\n  }\n\n  get area() {\n    return this.height * this.width;\n  }\n\n  set area(value) {\n    this.height = value ** 0.5;\n    this.width = value ** 0.5;\n  }\n}\n
\n
\n

Calling super in a constructor bound to a different prototype

\n
\n

super() calls the constructor that's the prototype of the current class. If you change the prototype of the current class itself, super() will call the constructor that's the new prototype. Changing the prototype of the current class's prototype property doesn't affect which constructor super() calls.

\n

js

\n
class Polygon {\n  constructor() {\n    this.name = \"Polygon\";\n  }\n}\n\nclass Rectangle {\n  constructor() {\n    this.name = \"Rectangle\";\n  }\n}\n\nclass Square extends Polygon {\n  constructor() {\n    super();\n  }\n}\n\n// Make Square extend Rectangle (which is a base class) instead of Polygon\nObject.setPrototypeOf(Square, Rectangle);\n\nconst newInstance = new Square();\n\n// newInstance is still an instance of Polygon, because we didn't\n// change the prototype of Square.prototype, so the prototype chain\n// of newInstance is still\n//   newInstance --> Square.prototype --> Polygon.prototype\nconsole.log(newInstance instanceof Polygon); // true\nconsole.log(newInstance instanceof Rectangle); // false\n\n// However, because super() calls Rectangle as constructor, the name property\n// of newInstance is initialized with the logic in Rectangle\nconsole.log(newInstance.name); // Rectangle\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-static-semantics-constructormethod
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
constructor49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor\n

\n
\n", + "classes/extends": "

extends

The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
class ChildClass extends ParentClass { /* … */ }\n
\n
ParentClass

An expression that evaluates to a constructor function (including a class) or null.

\n

Description

\n
\n

The extends keyword can be used to subclass custom classes as well as built-in objects.

Any constructor that can be called with new and has the prototype property can be the candidate for the parent class. The two conditions must both hold — for example, bound functions and Proxy can be constructed, but they don't have a prototype property, so they cannot be subclassed.

\n

js

\n
function OldStyleClass() {\n  this.someProperty = 1;\n}\nOldStyleClass.prototype.someMethod = function () {};\n\nclass ChildClass extends OldStyleClass {}\n\nclass ModernClass {\n  someProperty = 1;\n  someMethod() {}\n}\n\nclass AnotherChildClass extends ModernClass {}\n
\n

The prototype property of the ParentClass must be an Object or null, but you would rarely worry about this in practice, because a non-object prototype doesn't behave as it should anyway. (It's ignored by the new operator.)

\n

js

\n
function ParentClass() {}\nParentClass.prototype = 3;\n\nclass ChildClass extends ParentClass {}\n// Uncaught TypeError: Class extends value does not have valid prototype property 3\n\nconsole.log(Object.getPrototypeOf(new ParentClass()));\n// [Object: null prototype] {}\n// Not actually a number!\n
\n

extends sets the prototype for both ChildClass and ChildClass.prototype.

Prototype of ChildClass\n Prototype of ChildClass.prototype\n
\nextends clause absent Function.prototype Object.prototype
extends null Function.prototype null
extends ParentClass ParentClass ParentClass.prototype
\n

js

\n
class ParentClass {}\nclass ChildClass extends ParentClass {}\n\n// Allows inheritance of static properties\nObject.getPrototypeOf(ChildClass) === ParentClass;\n// Allows inheritance of instance properties\nObject.getPrototypeOf(ChildClass.prototype) === ParentClass.prototype;\n
\n

The right-hand side of extends does not have to be an identifier. You can use any expression that evaluates to a constructor. This is often useful to create mixins. The this value in the extends expression is the this surrounding the class definition, and referring to the class's name is a ReferenceError because the class is not initialized yet. await and yield work as expected in this expression.

\n

js

\n
class SomeClass extends class {\n  constructor() {\n    console.log(\"Base class\");\n  }\n} {\n  constructor() {\n    super();\n    console.log(\"Derived class\");\n  }\n}\n\nnew SomeClass();\n// Base class\n// Derived class\n
\n

While the base class may return anything from its constructor, the derived class must return an object or undefined, or a TypeError will be thrown.

\n

js

\n
class ParentClass {\n  constructor() {\n    return 1;\n  }\n}\n\nconsole.log(new ParentClass()); // ParentClass {}\n// The return value is ignored because it's not an object\n// This is consistent with function constructors\n\nclass ChildClass extends ParentClass {\n  constructor() {\n    super();\n    return 1;\n  }\n}\n\nconsole.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined\n
\n

If the parent class constructor returns an object, that object will be used as the this value for the derived class when further initializing class fields. This trick is called \"return overriding\", which allows a derived class's fields (including private ones) to be defined on unrelated objects.

\n

Subclassing built-ins

\n
\n

Warning: The standard committee now holds the position that the built-in subclassing mechanism in previous spec versions is over-engineered and causes non-negligible performance and security impacts. New built-in methods consider less about subclasses, and engine implementers are investigating whether to remove certain subclassing mechanisms. Consider using composition instead of inheritance when enhancing built-ins.

Here are some things you may expect when extending a class:

However, the above expectations take non-trivial efforts to implement properly.

These problems are not unique to built-in classes. For your own classes, you will likely have to make the same decisions. However, for built-in classes, optimizability and security are a much bigger concern. New built-in methods always construct the base class and call as few custom methods as possible. If you want to subclass built-ins while achieving the above expectations, you need to override all methods that have the default behavior baked into them. Any addition of new methods on the base class may also break the semantics of your subclass because they are inherited by default. Therefore, a better way to extend built-ins is to use composition.

\n

Extending null

\n
\n

extends null was designed to allow easy creation of objects that do not inherit from Object.prototype. However, due to unsettled decisions about whether super() should be called within the constructor, it's not possible to construct such a class in practice using any constructor implementation that doesn't return an object. The TC39 committee is working on re-enabling this feature.

\n

js

\n
new (class extends null {})();\n// TypeError: Super constructor null of anonymous class is not a constructor\n\nnew (class extends null {\n  constructor() {}\n})();\n// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor\n\nnew (class extends null {\n  constructor() {\n    super();\n  }\n})();\n// TypeError: Super constructor null of anonymous class is not a constructor\n
\n

Instead, you need to explicitly return an instance from the constructor.

\n

js

\n
class NullClass extends null {\n  constructor() {\n    // Using new.target allows derived classes to\n    // have the correct prototype chain\n    return Object.create(new.target.prototype);\n  }\n}\n\nconst proto = Object.getPrototypeOf;\nconsole.log(proto(proto(new NullClass()))); // null\n
\n
\n

Examples

\n

Using extends

\n
\n

The first example creates a class called Square from a class called Polygon. This example is extracted from this live demo (source).

\n

js

\n
class Square extends Polygon {\n  constructor(length) {\n    // Here, it calls the parent class' constructor with lengths\n    // provided for the Polygon's width and height\n    super(length, length);\n    // Note: In derived classes, super() must be called before you\n    // can use 'this'. Leaving this out will cause a reference error.\n    this.name = \"Square\";\n  }\n\n  get area() {\n    return this.height * this.width;\n  }\n}\n
\n
\n

Extending plain objects

\n
\n

Classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object by making all properties of this object available on inherited instances, you can instead use Object.setPrototypeOf():

\n

js

\n
const Animal = {\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  },\n};\n\nclass Dog {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\nObject.setPrototypeOf(Dog.prototype, Animal);\n\nconst d = new Dog(\"Mitzie\");\nd.speak(); // Mitzie makes a noise.\n
\n
\n

Extending built-in objects

\n
\n

This example extends the built-in Date object. This example is extracted from this live demo (source).

\n

js

\n
class MyDate extends Date {\n  getFormattedDate() {\n    const months = [\n      \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n      \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n    ];\n    return `${this.getDate()}-${months[this.getMonth()]}-${this.getFullYear()}`;\n  }\n}\n
\n
\n

Extending Object\n

\n
\n

All JavaScript objects inherit from Object.prototype by default, so writing extends Object at first glance seems redundant. The only difference from not writing extends at all is that the constructor itself inherits static methods from Object, such as Object.keys(). However, because no Object static method uses the this value, there's still no value in inheriting these static methods.

The Object() constructor special-cases the subclassing scenario. If it's implicitly called via super(), it always initializes a new object with new.target.prototype as its prototype. Any value passed to super() is ignored.

\n

js

\n
class C extends Object {\n  constructor(v) {\n    super(v);\n  }\n}\n\nconsole.log(new C(1) instanceof Number); // false\nconsole.log(C.keys({ a: 1, b: 2 })); // [ 'a', 'b' ]\n
\n

Compare this behavior with a custom wrapper that does not special-case subclassing:

\n

js

\n
function MyObject(v) {\n  return new Object(v);\n}\nclass D extends MyObject {\n  constructor(v) {\n    super(v);\n  }\n}\nconsole.log(new D(1) instanceof Number); // true\n
\n
\n

Species

\n
\n

You might want to return Array objects in your derived array class MyArray. The species pattern lets you override default constructors.

For example, when using methods such as Array.prototype.map() that return the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The Symbol.species symbol lets you do this:

\n

js

\n
class MyArray extends Array {\n  // Overwrite species to the parent Array constructor\n  static get [Symbol.species]() {\n    return Array;\n  }\n}\n\nconst a = new MyArray(1, 2, 3);\nconst mapped = a.map((x) => x * x);\n\nconsole.log(mapped instanceof MyArray); // false\nconsole.log(mapped instanceof Array); // true\n
\n

This behavior is implemented by many built-in copying methods. For caveats of this feature, see the subclassing built-ins discussion.

\n

Mix-ins

\n
\n

Abstract subclasses or mix-ins are templates for classes. A class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins:

\n

js

\n
const calculatorMixin = (Base) =>\n  class extends Base {\n    calc() {}\n  };\n\nconst randomizerMixin = (Base) =>\n  class extends Base {\n    randomize() {}\n  };\n
\n

A class that uses these mix-ins can then be written like this:

\n

js

\n
class Foo {}\nclass Bar extends calculatorMixin(randomizerMixin(Foo)) {}\n
\n
\n

Avoiding inheritance

\n
\n

Inheritance is a very strong coupling relationship in object-oriented programming. It means all behaviors of the base class are inherited by the subclass by default, which may not always be what you want. For example, consider the implementation of a ReadOnlyMap:

\n

js

\n
class ReadOnlyMap extends Map {\n  set() {\n    throw new TypeError(\"A read-only map must be set at construction time.\");\n  }\n}\n
\n

It turns out that ReadOnlyMap is not constructible, because the Map() constructor calls the instance's set() method.

\n

js

\n
const m = new ReadOnlyMap([[\"a\", 1]]); // TypeError: A read-only map must be set at construction time.\n
\n

We may get around this by using a private flag to indicate whether the instance is being constructed. However, a more significant problem with this design is that it breaks the Liskov substitution principle, which states that a subclass should be substitutable for its superclass. If a function expects a Map object, it should be able to use a ReadOnlyMap object as well, which will break here.

Inheritance often leads to the circle-ellipse problem, because neither type perfectly entails the behavior of the other, although they share a lot of common traits. In general, unless there's a very good reason to use inheritance, it's better to use composition instead. Composition means that a class has a reference to an object of another class, and only uses that object as an implementation detail.

\n

js

\n
class ReadOnlyMap {\n  #data;\n  constructor(values) {\n    this.#data = new Map(values);\n  }\n  get(key) {\n    return this.#data.get(key);\n  }\n  has(key) {\n    return this.#data.has(key);\n  }\n  get size() {\n    return this.#data.size;\n  }\n  *keys() {\n    yield* this.#data.keys();\n  }\n  *values() {\n    yield* this.#data.values();\n  }\n  *entries() {\n    yield* this.#data.entries();\n  }\n  *[Symbol.iterator]() {\n    yield* this.#data[Symbol.iterator]();\n  }\n}\n
\n

In this case, the ReadOnlyMap class is not a subclass of Map, but it still implements most of the same methods. This means more code duplication, but it also means that the ReadOnlyMap class is not strongly coupled to the Map class, and does not easily break if the Map class is changed, avoiding the semantic issues of built-in subclassing. For example, if the Map class adds an emplace() method that does not call set(), it would cause the ReadOnlyMap class to no longer be read-only unless the latter is updated accordingly to override emplace() as well. Moreover, ReadOnlyMap objects do not have the set method at all, which is more accurate than throwing an error at runtime.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-class-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
extends49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends\n

\n
\n", + "classes/private_class_fields": "

Private class features

\n

Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.

Private members are not native to the language before this syntax existed. In prototypical inheritance, its behavior may be emulated with WeakMap objects or closures, but they can't compare to the # syntax in terms of ergonomics.

\n
\n

Syntax

\n
\n
\n

js

\n
class ClassWithPrivate {\n  #privateField;\n  #privateFieldWithInitializer = 42;\n\n  #privateMethod() {\n    // …\n  }\n\n  static #privateStaticField;\n  static #privateStaticFieldWithInitializer = 42;\n\n  static #privateStaticMethod() {\n    // …\n  }\n}\n
\n

There are some additional syntax restrictions:

\n

Description

\n
\n

Most class features have their private counterparts:

These features are collectively called private properties. However, constructors cannot be private in JavaScript. To prevent classes from being constructed outside of the class, you have to use a private flag.

Private properties are declared with # names (pronounced \"hash names\"), which are identifiers prefixed with #. The hash prefix is an inherent part of the property name — you can draw relationship with the old underscore prefix convention _privateField — but it's not an ordinary string property, so you can't dynamically access it with the bracket notation.

It is a syntax error to refer to # names from outside of the class. It is also a syntax error to refer to private properties that were not declared in the class body, or to attempt to remove declared properties with delete.

\n

js

\n
class ClassWithPrivateField {\n  #privateField;\n\n  constructor() {;\n    delete this.#privateField; // Syntax error\n    this.#undeclaredField = 42; // Syntax error\n  }\n}\n\nconst instance = new ClassWithPrivateField();\ninstance.#privateField; // Syntax error\n
\n

JavaScript, being a dynamic language, is able to perform this compile-time check because of the special hash identifier syntax, making it different from normal properties on the syntax level.

Note: Code run in the Chrome console can access private properties outside the class. This is a DevTools-only relaxation of the JavaScript syntax restriction.

If you access a private property from an object that doesn't have the property, a TypeError is thrown, instead of returning undefined as normal properties do.

\n

js

\n
class C {\n  #x;\n\n  static getX(obj) {\n    return obj.#x;\n  }\n}\n\nconsole.log(C.getX(new C())); // undefined\nconsole.log(C.getX({})); // TypeError: Cannot read private member #x from an object whose class did not declare it\n
\n

This example also illustrates that you can access private properties within static functions too, and on externally defined instances of the class.

You can use the in operator to check whether an externally defined object possesses a private property. This will return true if the private field or method exists, and false otherwise.

\n

js

\n
class C {\n  #x;\n  constructor(x) {\n    this.#x = x;\n  }\n  static getX(obj) {\n    if (#x in obj) return obj.#x;\n\n    return \"obj must be an instance of C\";\n  }\n}\nconsole.log(C.getX(new C(\"foo\"))); // \"foo\"\nconsole.log(C.getX(new C(0.196))); // 0.196\nconsole.log(C.getX(new C(new Date()))); // the current date and time\nconsole.log(C.getX({})); // \"obj must be an instance of C\"\n
\n

Note a corollary of private names being always pre-declared and non-deletable: if you found that an object possesses one private property of the current class (either from a try...catch or an in check), it must possess all other private properties. An object possessing the private properties of a class generally means it was constructed by that class (although not always).

Private properties are not part of the prototypical inheritance model since they can only be accessed within the current class's body and aren't inherited by subclasses. Private properties with the same name within different classes are entirely different and do not interoperate with each other. See them as external metadata attached to each instance, managed by the class. For this reason, Object.freeze() and Object.seal() have no effect on private properties.

For more information on how and when private fields are initialized, see public class fields.

\n

Examples

\n

Private fields

\n
\n

Private fields include private instance fields and private static fields. Private fields are only accessible from inside the class declaration.

Private instance fields

Like their public counterparts, private instance fields:

\n

js

\n
class ClassWithPrivateField {\n  #privateField;\n\n  constructor() {\n    this.#privateField = 42;\n  }\n}\n\nclass Subclass extends ClassWithPrivateField {\n  #subPrivateField;\n\n  constructor() {\n    super();\n    this.#subPrivateField = 23;\n  }\n}\n\nnew Subclass(); // In some dev tools, it shows Subclass {#privateField: 42, #subPrivateField: 23}\n
\n

Note: #privateField from the ClassWithPrivateField base class is private to ClassWithPrivateField and is not accessible from the derived Subclass.

Returning overriding object

A class's constructor can return a different object, which will be used as the new this for the derived class constructor. The derived class may then define private fields on that returned object — meaning it is possible to \"stamp\" private fields onto unrelated objects.

\n

js

\n
class Stamper extends class {\n  // A base class whose constructor returns the object it's given\n  constructor(obj) {\n    return obj;\n  }\n} {\n  // This declaration will \"stamp\" the private field onto the object\n  // returned by the base class constructor\n  #stamp = 42;\n  static getStamp(obj) {\n    return obj.#stamp;\n  }\n}\n\nconst obj = {};\nnew Stamper(obj);\n// `Stamper` calls `Base`, which returns `obj`, so `obj` is\n// now the `this` value. `Stamper` then defines `#stamp` on `obj`\n\nconsole.log(obj); // In some dev tools, it shows {#stamp: 42}\nconsole.log(Stamper.getStamp(obj)); // 42\nconsole.log(obj instanceof Stamper); // false\n\n// You cannot stamp private properties twice\nnew Stamper(obj); // Error: Initializing an object twice is an error with private fields\n
\n

Warning: This is a potentially very confusing thing to do. You are generally advised to avoid returning anything from the constructor — especially something unrelated to this.

Private static fields

Like their public counterparts, private static fields:

\n

js

\n
class ClassWithPrivateStaticField {\n  static #privateStaticField = 42;\n\n  static publicStaticMethod() {\n    return ClassWithPrivateStaticField.#privateStaticField;\n  }\n}\n\nconsole.log(ClassWithPrivateStaticField.publicStaticMethod()); // 42\n
\n

There is a restriction on private static fields: only the class which defines the private static field can access the field. This can lead to unexpected behavior when using this. In the following example, this refers to the Subclass class (not the ClassWithPrivateStaticField class) when we try to call Subclass.publicStaticMethod(), and so causes a TypeError.

\n

js

\n
class ClassWithPrivateStaticField {\n  static #privateStaticField = 42;\n\n  static publicStaticMethod() {\n    return this.#privateStaticField;\n  }\n}\n\nclass Subclass extends ClassWithPrivateStaticField {}\n\nSubclass.publicStaticMethod(); // TypeError: Cannot read private member #privateStaticField from an object whose class did not declare it\n
\n

This is the same if you call the method with super, because super methods are not called with the super class as this.

\n

js

\n
class ClassWithPrivateStaticField {\n  static #privateStaticField = 42;\n\n  static publicStaticMethod() {\n    // When invoked through super, `this` still refers to Subclass\n    return this.#privateStaticField;\n  }\n}\n\nclass Subclass extends ClassWithPrivateStaticField {\n  static callSuperMethod() {\n    return super.publicStaticMethod();\n  }\n}\n\nSubclass.callSuperMethod(); // TypeError: Cannot read private member #privateStaticField from an object whose class did not declare it\n
\n

You are advised to always access private static fields through the class name, not through this, so inheritance doesn't break the method.

\n

Private methods

\n
\n

Private methods include private instance methods and private static methods. Private methods are only accessible from inside the class declaration.

Private instance methods

Unlike their public counterparts, private instance methods:

\n

js

\n
class ClassWithPrivateMethod {\n  #privateMethod() {\n    return 42;\n  }\n\n  publicMethod() {\n    return this.#privateMethod();\n  }\n}\n\nconst instance = new ClassWithPrivateMethod();\nconsole.log(instance.publicMethod()); // 42\n
\n

Private instance methods may be generator, async, or async generator functions. Private getters and setters are also possible, and follow the same syntax requirements as their public getter and setter counterparts.

\n

js

\n
class ClassWithPrivateAccessor {\n  #message;\n\n  get #decoratedMessage() {\n    return `🎬${this.#message}🛑`;\n  }\n  set #decoratedMessage(msg) {\n    this.#message = msg;\n  }\n\n  constructor() {\n    this.#decoratedMessage = \"hello world\";\n    console.log(this.#decoratedMessage);\n  }\n}\n\nnew ClassWithPrivateAccessor(); // 🎬hello world🛑\n
\n

Unlike public methods, private methods are not accessible on the .prototype property of their class.

\n

js

\n
class C {\n  #method() {}\n\n  static getMethod(x) {\n    return x.#method;\n  }\n}\n\nconsole.log(C.getMethod(new C())); // [Function: #method]\nconsole.log(C.getMethod(C.prototype)); // TypeError: Receiver must be an instance of class C\n
\n

Private static methods

Like their public counterparts, private static methods:

\n

js

\n
class ClassWithPrivateStaticMethod {\n  static #privateStaticMethod() {\n    return 42;\n  }\n\n  static publicStaticMethod() {\n    return ClassWithPrivateStaticMethod.#privateStaticMethod();\n  }\n}\n\nconsole.log(ClassWithPrivateStaticMethod.publicStaticMethod()); // 42\n
\n

Private static methods may be generator, async, and async generator functions.

The same restriction previously mentioned for private static fields holds for private static methods, and similarly can lead to unexpected behavior when using this. In the following example, when we try to call Subclass.publicStaticMethod(), this refers to the Subclass class (not the ClassWithPrivateStaticMethod class) and so causes a TypeError.

\n

js

\n
class ClassWithPrivateStaticMethod {\n  static #privateStaticMethod() {\n    return 42;\n  }\n\n  static publicStaticMethod() {\n    return this.#privateStaticMethod();\n  }\n}\n\nclass Subclass extends ClassWithPrivateStaticMethod {}\n\nconsole.log(Subclass.publicStaticMethod()); // TypeError: Cannot read private member #privateStaticMethod from an object whose class did not declare it\n
\n
\n

Simulating private constructors

\n
\n

Many other languages include the capability to mark a constructor as private, which prevents the class from being instantiated outside of the class itself — you can only use static factory methods that create instances, or not be able to create instances at all. JavaScript does not have a native way to do this, but it can be accomplished by using a private static flag.

\n

js

\n
class PrivateConstructor {\n  static #isInternalConstructing = false;\n\n  constructor() {\n    if (!PrivateConstructor.#isInternalConstructing) {\n      throw new TypeError(\"PrivateConstructor is not constructable\");\n    }\n    PrivateConstructor.#isInternalConstructing = false;\n    // More initialization logic\n  }\n\n  static create() {\n    PrivateConstructor.#isInternalConstructing = true;\n    const instance = new PrivateConstructor();\n    return instance;\n  }\n}\n\nnew PrivateConstructor(); // TypeError: PrivateConstructor is not constructable\nPrivateConstructor.create(); // PrivateConstructor {}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-PrivateIdentifier
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Private_class_fields747990No6214.17474905314.511.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\n

\n
\n", + "classes/public_class_fields": "

Public class fields

Public fields are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they participate in prototype inheritance.

\n

Syntax

\n
\n
\n

js

\n
class ClassWithField {\n  instanceField;\n  instanceFieldWithInitializer = \"instance field\";\n  static staticField;\n  static staticFieldWithInitializer = \"static field\";\n}\n
\n

There are some additional syntax restrictions:

\n

Description

\n
\n

This page introduces public instance fields in detail.

Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.

Public instance fields are added to the instance either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass. Fields without initializers are initialized to undefined. Like properties, field names may be computed.

\n

js

\n
const PREFIX = \"prefix\";\n\nclass ClassWithField {\n  field;\n  fieldWithInitializer = \"instance field\";\n  [`${PREFIX}Field`] = \"prefixed field\";\n}\n\nconst instance = new ClassWithField();\nconsole.log(Object.hasOwn(instance, \"field\")); // true\nconsole.log(instance.field); // undefined\nconsole.log(instance.fieldWithInitializer); // \"instance field\"\nconsole.log(instance.prefixField); // \"prefixed field\"\n
\n

Computed field names are only evaluated once, at class definition time. This means that each class always has a fixed set of field names, and two instances cannot have different field names via computed names. The this value in the computed expression is the this surrounding the class definition, and referring to the class's name is a ReferenceError because the class is not initialized yet. await and yield work as expected in this expression.

\n

js

\n
class C {\n  [Math.random()] = 1;\n}\n\nconsole.log(new C());\nconsole.log(new C());\n// Both instances have the same field name\n
\n

In the field initializer, this refers to the class instance under construction, and super refers to the prototype property of the base class, which contains the base class's instance methods, but not its instance fields.

\n

js

\n
class Base {\n  baseField = \"base field\";\n  anotherBaseField = this.baseField;\n  baseMethod() {\n    return \"base method output\";\n  }\n}\n\nclass Derived extends Base {\n  subField = super.baseMethod();\n}\n\nconst base = new Base();\nconst sub = new Derived();\n\nconsole.log(base.anotherBaseField); // \"base field\"\n\nconsole.log(sub.subField); // \"base method output\"\n
\n

The field initializer expression is evaluated each time a new instance is created. (Because the this value is different for each instance, the initializer expression can access instance-specific properties.)

\n

js

\n
class C {\n  obj = {};\n}\n\nconst instance1 = new C();\nconst instance2 = new C();\nconsole.log(instance1.obj === instance2.obj); // false\n
\n

The expression is evaluated synchronously. You cannot use await or yield in the initializer expression. (Think of the initializer expression as being implicitly wrapped in a function.)

Because instance fields of a class are added before the respective constructor runs, you can access the fields' values within the constructor. However, because instance fields of a derived class are defined after super() returns, the base class's constructor does not have access to the derived class's fields.

\n

js

\n
class Base {\n  constructor() {\n    console.log(\"Base constructor:\", this.field);\n  }\n}\n\nclass Derived extends Base {\n  field = 1;\n  constructor() {\n    super();\n    console.log(\"Derived constructor:\", this.field);\n    this.field = 2;\n  }\n}\n\nconst instance = new Derived();\n// Base constructor: undefined\n// Derived constructor: 1\nconsole.log(instance.field); // 2\n
\n

Fields are added one-by-one. Field initializers can refer to field values above it, but not below it. All instance and static methods are added beforehand and can be accessed, although calling them may not behave as expected if they refer to fields below the one being initialized.

\n

js

\n
class C {\n  a = 1;\n  b = this.c;\n  c = this.a + 1;\n  d = this.c + 1;\n}\n\nconst instance = new C();\nconsole.log(instance.d); // 3\nconsole.log(instance.b); // undefined\n
\n

Note: This is more important with private fields, because accessing a non-initialized private field throws a TypeError, even if the private field is declared below. (If the private field is not declared, it would be an early SyntaxError.)

Because class fields are added using the [[DefineOwnProperty]] semantic (which is essentially Object.defineProperty()), field declarations in derived classes do not invoke setters in the base class. This behavior differs from using this.field = … in the constructor.

\n

js

\n
class Base {\n  set field(val) {\n    console.log(val);\n  }\n}\n\nclass DerivedWithField extends Base {\n  field = 1;\n}\n\nconst instance = new DerivedWithField(); // No log\n\nclass DerivedWithConstructor extends Base {\n  constructor() {\n    super();\n    this.field = 1;\n  }\n}\n\nconst instance2 = new DerivedWithConstructor(); // Logs 1\n
\n

Note: Before the class fields specification was finalized with the [[DefineOwnProperty]] semantic, most transpilers, including Babel and tsc, transformed class fields to the DerivedWithConstructor form, which has caused subtle bugs after class fields were standardized.

\n

Examples

\n

Using class fields

\n
\n

Class fields cannot depend on arguments of the constructor, so field initializers usually evaluate to the same value for each instance (unless the same expression can evaluate to different values each time, such as Date.now() or object initializers).

\n

js

\n
class Person {\n  name = nameArg; // nameArg is out of scope of the constructor\n  constructor(nameArg) {}\n}\n
\n
\n

js

\n
class Person {\n  // All instances of Person will have the same name\n  name = \"Dragomir\";\n}\n
\n

However, even declaring an empty class field is beneficial, because it indicates the existence of the field, which allows type checkers as well as human readers to statically analyze the shape of the class.

\n

js

\n
class Person {\n  name;\n  age;\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n}\n
\n

The code above seems repetitive, but consider the case where this is dynamically mutated: the explicit field declaration makes it clear which fields will definitely be present on the instance.

\n

js

\n
class Person {\n  name;\n  age;\n  constructor(properties) {\n    Object.assign(this, properties);\n  }\n}\n
\n

Because initializers are evaluated after the base class has executed, you can access properties created by the base class constructor.

\n

js

\n
class Person {\n  name;\n  age;\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n}\n\nclass Professor extends Person {\n  name = `Professor ${this.name}`;\n}\n\nconsole.log(new Professor(\"Radev\", 54).name); // \"Professor Radev\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-FieldDefinition
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Public_class_fields727969No6014.1
14–14.1Doesn't support public static fields. See WebKit bug 194095.
\n
7272795114.5
14–14.5Doesn't support public static fields. See WebKit bug 194095.
\n
11.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields\n

\n
\n", + "classes/static": "

static

\n

The static keyword defines a static method or field for a class, or a static initialization block (see the link for more information about this usage). Static properties cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

Note: In the context of classes, MDN Web Docs content uses the terms properties and fields interchangeably.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
class ClassWithStatic {\n  static staticField;\n  static staticFieldWithInitializer = value;\n  static staticMethod() {\n    // …\n  }\n}\n
\n

There are some additional syntax restrictions:

\n

Description

\n
\n

This page introduces public static properties of classes, which include static methods, static accessors, and static fields.

Public static features are declared using the static keyword. They are added to the class constructor at the time of class evaluation using the [[DefineOwnProperty]] semantic (which is essentially Object.defineProperty()). They are accessed again from the class constructor.

Static methods are often utility functions, such as functions to create or clone instances. Public static fields are useful when you want a field to exist only once per class, not on every class instance you create. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

Static field names can be computed. The this value in the computed expression is the this surrounding the class definition, and referring to the class's name is a ReferenceError because the class is not initialized yet. await and yield work as expected in this expression.

Static fields can have an initializer. Static fields without initializers are initialized to undefined. Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.

\n

js

\n
class ClassWithStaticField {\n  static staticField;\n  static staticFieldWithInitializer = \"static field\";\n}\n\nclass SubclassWithStaticField extends ClassWithStaticField {\n  static subStaticField = \"subclass field\";\n}\n\nconsole.log(Object.hasOwn(ClassWithStaticField, \"staticField\")); // true\nconsole.log(ClassWithStaticField.staticField); // undefined\nconsole.log(ClassWithStaticField.staticFieldWithInitializer); // \"static field\"\nconsole.log(SubclassWithStaticField.staticFieldWithInitializer); // \"static field\"\nconsole.log(SubclassWithStaticField.subStaticField); // \"subclass field\"\n
\n

In the field initializer, this refers to the current class (which you can also access through its name), and super refers to the base class constructor.

\n

js

\n
class ClassWithStaticField {\n  static baseStaticField = \"base static field\";\n  static anotherBaseStaticField = this.baseStaticField;\n\n  static baseStaticMethod() {\n    return \"base static method output\";\n  }\n}\n\nclass SubClassWithStaticField extends ClassWithStaticField {\n  static subStaticField = super.baseStaticMethod();\n}\n\nconsole.log(ClassWithStaticField.anotherBaseStaticField); // \"base static field\"\nconsole.log(SubClassWithStaticField.subStaticField); // \"base static method output\"\n
\n

The expression is evaluated synchronously. You cannot use await or yield in the initializer expression. (Think of the initializer expression as being implicitly wrapped in a function.)

Static field initializers and static initialization blocks are evaluated one-by-one. Field initializers can refer to field values above it, but not below it. All static methods are added beforehand and can be accessed, although calling them may not behave as expected if they refer to fields below the one being initialized.

Note: This is more important with private static fields, because accessing a non-initialized private field throws a TypeError, even if the private field is declared below. (If the private field is not declared, it would be an early SyntaxError.)

\n

Examples

\n

Using static members in classes

\n
\n

The following example demonstrates several things:

  1. How a static member (method or property) is defined on a class.
  2. That a class with a static member can be sub-classed.
  3. How a static member can and cannot be called.
\n

js

\n
class Triple {\n  static customName = \"Tripler\";\n  static description = \"I triple any number you provide\";\n  static calculate(n = 1) {\n    return n * 3;\n  }\n}\n\nclass SquaredTriple extends Triple {\n  static longDescription;\n  static description = \"I square the triple of any number you provide\";\n  static calculate(n) {\n    return super.calculate(n) * super.calculate(n);\n  }\n}\n\nconsole.log(Triple.description); // 'I triple any number you provide'\nconsole.log(Triple.calculate()); // 3\nconsole.log(Triple.calculate(6)); // 18\n\nconst tp = new Triple();\n\nconsole.log(SquaredTriple.calculate(3)); // 81 (not affected by parent's instantiation)\nconsole.log(SquaredTriple.description); // 'I square the triple of any number you provide'\nconsole.log(SquaredTriple.longDescription); // undefined\nconsole.log(SquaredTriple.customName); // 'Tripler'\n\n// This throws because calculate() is a static member, not an instance member.\nconsole.log(tp.calculate()); // 'tp.calculate is not a function'\n
\n
\n

Calling static members from another static method

\n
\n

In order to call a static method or property within another static method of the same class, you can use the this keyword.

\n

js

\n
class StaticMethodCall {\n  static staticProperty = \"static property\";\n  static staticMethod() {\n    return `Static method and ${this.staticProperty} has been called`;\n  }\n  static anotherStaticMethod() {\n    return `${this.staticMethod()} from another static method`;\n  }\n}\nStaticMethodCall.staticMethod();\n// 'Static method and static property has been called'\n\nStaticMethodCall.anotherStaticMethod();\n// 'Static method and static property has been called from another static method'\n
\n
\n

Calling static members from a class constructor and other methods

\n
\n

Static members are not directly accessible using the this keyword from non-static methods. You need to call them using the class name: CLASSNAME.STATIC_METHOD_NAME() / CLASSNAME.STATIC_PROPERTY_NAME or by calling the method as a property of the constructor: this.constructor.STATIC_METHOD_NAME() / this.constructor.STATIC_PROPERTY_NAME

\n

js

\n
class StaticMethodCall {\n  constructor() {\n    console.log(StaticMethodCall.staticProperty); // 'static property'\n    console.log(this.constructor.staticProperty); // 'static property'\n    console.log(StaticMethodCall.staticMethod()); // 'static method has been called.'\n    console.log(this.constructor.staticMethod()); // 'static method has been called.'\n  }\n\n  static staticProperty = \"static property\";\n  static staticMethod() {\n    return \"static method has been called.\";\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-class-definitions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
static49
42–49Strict mode is required.
\n
1345No36
29–36Strict mode is required.
\n
949
42–49Strict mode is required.
\n
49
42–49Strict mode is required.
\n
4536
29–36Strict mode is required.
\n
95.0
4.0–5.0Strict mode is required.
\n
1.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static\n

\n
\n", + "classes/static_initialization_blocks": "

Static initialization blocks

Static initialization blocks are declared within a class. It contains statements to be evaluated during class initialization. This permits more flexible initialization logic than static properties, such as using try...catch or setting multiple fields from a single value. Initialization is performed in the context of the current class declaration, with access to private state, which allows the class to share information of its private properties with other classes or functions declared in the same scope (analogous to \"friend\" classes in C++).

\n

Try it

\n

Syntax

\n
\n

js

\n
class ClassWithSIB {\n  static {\n    // …\n  }\n}\n
\n

Description

\n
\n

Without static initialization blocks, complex static initialization might be achieved by calling a static method after the class declaration:

\n

js

\n
class MyClass {\n  static init() {\n    // Access to private static fields is allowed here\n  }\n}\n\nMyClass.init();\n
\n

However, this approach exposes an implementation detail (the init() method) to the user of the class. On the other hand, any initialization logic declared outside the class does not have access to private static fields. Static initialization blocks allow arbitrary initialization logic to be declared within the class and executed during class evaluation.

A class can have any number of static {} initialization blocks in its class body. These are evaluated, along with any interleaved static field initializers, in the order they are declared. Any static initialization of a super class is performed first, before that of its sub classes.

The scope of the variables declared inside the static block is local to the block. This includes var, function, const, and let declarations. var declarations in the block are not hoisted.

\n

js

\n
var y = \"Outer y\";\n\nclass A {\n  static field = \"Inner y\";\n  static {\n    var y = this.field;\n  }\n}\n\n// var defined in static block is not hoisted\nconsole.log(y); // 'Outer y'\n
\n

The this inside a static block refers to the constructor object of the class. super.property can be used to access static properties of the super class. Note however that it is a syntax error to call super() in a class static initialization block, or to use the arguments object.

The statements are evaluated synchronously. You cannot use await or yield in this block. (Think of the initialization statements as being implicitly wrapped in a function.)

The scope of the static block is nested within the lexical scope of the class body, and can access private names declared within the class without causing a syntax error.

Static field initializers and static initialization blocks are evaluated one-by-one. The initialization block can refer to field values above it, but not below it. All static methods are added beforehand and can be accessed, although calling them may not behave as expected if they refer to fields below the current block.

Note: This is more important with private static fields, because accessing a non-initialized private field throws a TypeError, even if the private field is declared below. (If the private field is not declared, it would be an early SyntaxError.)

A static initialization block may not have decorators (the class itself may).

\n

Examples

\n

Multiple blocks

\n
\n

The code below demonstrates a class with static initialization blocks and interleaved static field initializers. The output shows that the blocks and fields are evaluated in execution order.

\n

js

\n
class MyClass {\n  static field1 = console.log(\"static field1\");\n  static {\n    console.log(\"static block1\");\n  }\n  static field2 = console.log(\"static field2\");\n  static {\n    console.log(\"static block2\");\n  }\n}\n// 'static field1'\n// 'static block1'\n// 'static field2'\n// 'static block2'\n
\n

Note that any static initialization of a super class is performed first, before that of its sub classes.

\n

Using this and super

\n
\n

The this inside a static block refers to the constructor object of the class. This code shows how to access a public static field.

\n

js

\n
class A {\n  static field = \"static field\";\n  static {\n    console.log(this.field);\n  }\n}\n// 'static field'\n
\n

The super.property syntax can be used inside a static block to reference static properties of a super class.

\n

js

\n
class A {\n  static field = \"static field\";\n}\n\nclass B extends A {\n  static {\n    console.log(super.field);\n  }\n}\n// 'static field'\n
\n
\n

Access to private properties

\n
\n

This example below shows how access can be granted to a private instance field of a class from an object outside the class (example from the v8.dev blog):

\n

js

\n
let getDPrivateField;\n\nclass D {\n  #privateField;\n  constructor(v) {\n    this.#privateField = v;\n  }\n  static {\n    getDPrivateField = (d) => d.#privateField;\n  }\n}\n\nconsole.log(getDPrivateField(new D(\"private\"))); // 'private'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-ClassStaticBlock
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Static_initialization_blocks949493No8016.49494936616.417.01.1416.11.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks\n

\n
\n", + "iteration_protocols": "

Iteration protocols

\n

Iteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.

There are two protocols: The iterable protocol and the iterator protocol.

\n
\n

The iterable protocol

\n
\n

The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not.

In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator:

[Symbol.iterator]

A zero-argument function that returns an object, conforming to the iterator protocol.

Whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the this keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.

This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using yield.

\n

The iterator protocol

\n
\n

The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.

An object is an iterator when it implements a next() method with the following semantics:

next()

A function that accepts zero or one argument and returns an object conforming to the IteratorResult interface (see below). If a non-object value gets returned (such as false or undefined) when a built-in language feature (such as for...of) is using the iterator, a TypeError (\"iterator.next() returned a non-object value\") will be thrown.

All iterator protocol methods (next(), return(), and throw()) are expected to return an object implementing the IteratorResult interface. It must have the following properties:

\ndone Optional\n

A boolean that's false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.)

Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator.

\nvalue Optional\n

Any JavaScript value returned by the iterator. Can be omitted when done is true.

In practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to { done: false, value: undefined }.

If an iterator returns a result with done: true, any subsequent calls to next() are expected to return done: true as well, although this is not enforced on the language level.

The next method can receive a value which will be made available to the method body. No built-in language feature will pass any value. The value passed to the next method of generators will become the value of the corresponding yield expression.

Optionally, the iterator can also implement the return(value) and throw(exception) methods, which, when called, tells the iterator that the caller is done with iterating it and can perform any necessary cleanup (such as closing database connection).

\nreturn(value) Optional\n

A function that accepts zero or one argument and returns an object conforming to the IteratorResult interface, typically with value equal to the value passed in and done equal to true. Calling this method tells the iterator that the caller does not intend to make any more next() calls and can perform any cleanup actions.

\nthrow(exception) Optional\n

A function that accepts zero or one argument and returns an object conforming to the IteratorResult interface, typically with done equal to true. Calling this method tells the iterator that the caller detects an error condition, and exception is typically an Error instance.

Note: It is not possible to know reflectively (i.e. without actually calling next() and validating the returned result) whether a particular object implements the iterator protocol.

It is very easy to make an iterator also iterable: just implement an [@@iterator]() method that returns this.

\n

js

\n
// Satisfies both the Iterator Protocol and Iterable\nconst myIterator = {\n  next() {\n    // ...\n  },\n  [Symbol.iterator]() {\n    return this;\n  },\n};\n
\n

Such object is called an iterable iterator. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables — therefore, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. (In fact, almost all syntaxes and APIs expect iterables, not iterators.) The generator object is an example:

\n

js

\n
const aGeneratorObject = (function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n})();\n\nconsole.log(typeof aGeneratorObject.next);\n// \"function\" — it has a next method (which returns the right result), so it's an iterator\n\nconsole.log(typeof aGeneratorObject[Symbol.iterator]);\n// \"function\" — it has an @@iterator method (which returns the right iterator), so it's an iterable\n\nconsole.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);\n// true — its @@iterator method returns itself (an iterator), so it's an iterable iterator\n
\n

All built-in iterators inherit from Iterator.prototype, which implements the [@@iterator]() method as returning this, so that built-in iterators are also iterable.

However, when possible, it's better for iterable[Symbol.iterator] to return different iterators that always start from the beginning, like Set.prototype[@@iterator]() does.

\n

The async iterator and async iterable protocols

\n
\n

There are another pair of protocols used for async iteration, named async iterator and async iterable protocols. They have very similar interfaces compared to the iterable and iterator protocols, except that each return value from the calls to the iterator methods is wrapped in a promise.

An object implements the async iterable protocol when it implements the following methods:

[Symbol.asyncIterator]

A zero-argument function that returns an object, conforming to the async iterator protocol.

An object implements the async iterator protocol when it implements the following methods:

next()

A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the IteratorResult interface, and the properties have the same semantics as those of the sync iterator's.

\nreturn(value) Optional\n

A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the IteratorResult interface, and the properties have the same semantics as those of the sync iterator's.

\nthrow(exception) Optional\n

A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the IteratorResult interface, and the properties have the same semantics as those of the sync iterator's.

\n

Interactions between the language and iteration protocols

\n

The language specifies APIs that either produce or consume iterables and iterators.

Built-in iterables

\n
\n

String, Array, TypedArray, Map, Set, and Segments (returned by Intl.Segmenter.prototype.segment()) are all built-in iterables, because each of their prototype objects implements an @@iterator method. In addition, the arguments object and some DOM collection types such as NodeList are also iterables. ReadableStream is the only built-in async iterable at the time of writing.

Generator functions return generator objects, which are iterable iterators. Async generator functions return async generator objects, which are async iterable iterators.

The iterators returned from built-in iterables actually all inherit from a common class Iterator, which implements the aforementioned [Symbol.iterator]() { return this; } method, making them all iterable iterators. The Iterator class also provides additional helper methods in addition to the next() method required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.

console.log([][Symbol.iterator]());\n\nArray Iterator {}\n  [[Prototype]]: Array Iterator     ==> This is the prototype shared by all array iterators\n    next: ƒ next()\n    Symbol(Symbol.toStringTag): \"Array Iterator\"\n    [[Prototype]]: Object           ==> This is the prototype shared by all built-in iterators\n      Symbol(Symbol.iterator): ƒ [Symbol.iterator]()\n      [[Prototype]]: Object         ==> This is Object.prototype\n
\n

Built-in APIs accepting iterables

\n
\n

There are many APIs that accept iterables. Some examples include:

\n

js

\n
const myObj = {};\n\nnew WeakSet(\n  (function* () {\n    yield {};\n    yield myObj;\n    yield {};\n  })(),\n).has(myObj); // true\n
\n
\n

Syntaxes expecting iterables

\n
\n

Some statements and expressions expect iterables, for example the for...of loops, array and parameter spreading, yield*, and array destructuring:

\n

js

\n
for (const value of [\"a\", \"b\", \"c\"]) {\n  console.log(value);\n}\n// \"a\"\n// \"b\"\n// \"c\"\n\nconsole.log([...\"abc\"]); // [\"a\", \"b\", \"c\"]\n\nfunction* gen() {\n  yield* [\"a\", \"b\", \"c\"];\n}\n\nconsole.log(gen().next()); // { value: \"a\", done: false }\n\n[a, b, c] = new Set([\"a\", \"b\", \"c\"]);\nconsole.log(a); // \"a\"\n
\n

When built-in syntaxes are iterating an iterator, and the last result's done is false (i.e. the iterator is able to produce more values) but no more values are needed, the return method will get called if present. This can happen, for example, if a break or return is encountered in a for...of loop, or if all identifiers are already bound in an array destructuring.

\n

js

\n
const obj = {\n  [Symbol.iterator]() {\n    let i = 0;\n    return {\n      next() {\n        i++;\n        console.log(\"Returning\", i);\n        if (i === 3) return { done: true, value: i };\n        return { done: false, value: i };\n      },\n      return() {\n        console.log(\"Closing\");\n        return { done: true };\n      },\n    };\n  },\n};\n\nconst [a] = obj;\n// Returning 1\n// Closing\n\nconst [b, c, d] = obj;\n// Returning 1\n// Returning 2\n// Returning 3\n// Already reached the end (the last call returned `done: true`),\n// so `return` is not called\n\nfor (const b of obj) {\n  break;\n}\n// Returning 1\n// Closing\n
\n

The for await...of loop and yield* in async generator functions (but not sync generator functions) are the only ways to interact with async iterables. Using for...of, array spreading, etc. on an async iterable that's not also a sync iterable (i.e. it has [@@asyncIterator]() but no [@@iterator]()) will throw a TypeError: x is not iterable.

\n

Non-well-formed iterables

\n
\n

If an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable.

Using one is likely to result in runtime errors or buggy behavior:

\n

js

\n
const nonWellFormedIterable = {};\nnonWellFormedIterable[Symbol.iterator] = () => 1;\n[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value\n
\n
\n

Examples

\n

User-defined iterables

\n
\n

You can make your own iterables like this:

\n

js

\n
const myIterable = {\n  *[Symbol.iterator]() {\n    yield 1;\n    yield 2;\n    yield 3;\n  },\n};\n\nconsole.log([...myIterable]); // [1, 2, 3]\n
\n
\n

Simple iterator

\n
\n

Iterators are stateful by nature. If you don't define it as a generator function (as the example above shows), you would likely want to encapsulate the state in a closure.

\n

js

\n
function makeIterator(array) {\n  let nextIndex = 0;\n  return {\n    next() {\n      return nextIndex < array.length\n        ? {\n            value: array[nextIndex++],\n            done: false,\n          }\n        : {\n            done: true,\n          };\n    },\n  };\n}\n\nconst it = makeIterator([\"yo\", \"ya\"]);\n\nconsole.log(it.next().value); // 'yo'\nconsole.log(it.next().value); // 'ya'\nconsole.log(it.next().done); // true\n
\n
\n

Infinite iterator

\n
\n

js

\n
function idMaker() {\n  let index = 0;\n  return {\n    next() {\n      return {\n        value: index++,\n        done: false,\n      };\n    },\n  };\n}\n\nconst it = idMaker();\n\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// ...\n
\n

Defining an iterable with a generator

\n
\n

js

\n
function* makeSimpleGenerator(array) {\n  let nextIndex = 0;\n  while (nextIndex < array.length) {\n    yield array[nextIndex++];\n  }\n}\n\nconst gen = makeSimpleGenerator([\"yo\", \"ya\"]);\n\nconsole.log(gen.next().value); // 'yo'\nconsole.log(gen.next().value); // 'ya'\nconsole.log(gen.next().done); // true\n\nfunction* idMaker() {\n  let index = 0;\n  while (true) {\n    yield index++;\n  }\n}\n\nconst it = idMaker();\n\nconsole.log(it.next().value); // 0\nconsole.log(it.next().value); // 1\nconsole.log(it.next().value); // 2\n// ...\n
\n

Defining an iterable with a class

\n
\n

State encapsulation can be done with private properties as well.

\n

js

\n
class SimpleClass {\n  #data;\n\n  constructor(data) {\n    this.#data = data;\n  }\n\n  [Symbol.iterator]() {\n    // Use a new index for each iterator. This makes multiple\n    // iterations over the iterable safe for non-trivial cases,\n    // such as use of break or nested looping over the same iterable.\n    let index = 0;\n\n    return {\n      // Note: using an arrow function allows `this` to point to the\n      // one of `[@@iterator]()` instead of `next()`\n      next: () => {\n        if (index < this.#data.length) {\n          return { value: this.#data[index++], done: false };\n        } else {\n          return { done: true };\n        }\n      },\n    };\n  }\n}\n\nconst simple = new SimpleClass([1, 2, 3, 4, 5]);\n\nfor (const val of simple) {\n  console.log(val); // 1 2 3 4 5\n}\n
\n
\n

Overriding built-in iterables

\n
\n

For example, a String is a built-in iterable object:

\n

js

\n
const someString = \"hi\";\nconsole.log(typeof someString[Symbol.iterator]); // \"function\"\n
\n

String's default iterator returns the string's code points one by one:

\n

js

\n
const iterator = someString[Symbol.iterator]();\nconsole.log(`${iterator}`); // \"[object String Iterator]\"\n\nconsole.log(iterator.next()); // { value: \"h\", done: false }\nconsole.log(iterator.next()); // { value: \"i\", done: false }\nconsole.log(iterator.next()); // { value: undefined, done: true }\n
\n

You can redefine the iteration behavior by supplying our own @@iterator:

\n

js

\n
// need to construct a String object explicitly to avoid auto-boxing\nconst someString = new String(\"hi\");\n\nsomeString[Symbol.iterator] = function () {\n  return {\n    // this is the iterator object, returning a single element (the string \"bye\")\n    next() {\n      return this._first\n        ? { value: \"bye\", done: (this._first = false) }\n        : { done: true };\n    },\n    _first: true,\n  };\n};\n
\n

Notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol:

\n

js

\n
console.log([...someString]); // [\"bye\"]\nconsole.log(`${someString}`); // \"hi\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-iteration
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\n

\n
\n", + "trailing_commas": "

Trailing commas

\n

Trailing commas (sometimes called \"final commas\") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome.

JavaScript has allowed trailing commas in array literals since the beginning. Trailing commas are now also allowed in object literals, function parameters, named imports, named exports, and more.

JSON, however, disallows all trailing commas.

\n
\n

Description

\n
\n

JavaScript allows trailing commas wherever a comma-separated list of values is accepted and more values may be expected after the last item. This includes:

In all these cases, the trailing comma is entirely optional and doesn't change the program's semantics in any way.

It is particular useful when adding, removing, or reordering items in a list that spans multiple lines, because it reduces the number of lines that need to be changed, which helps with both editing and reviewing the diff.

\n

diff

\n
 [\n   \"foo\",\n+   \"baz\",\n   \"bar\",\n-   \"baz\",\n ]\n
\n
\n

Examples

\n

Trailing commas in literals

\n
\n

Arrays

JavaScript ignores trailing commas in arrays literals:

\n

js

\n
const arr = [\n  1,\n  2,\n  3,\n];\n\narr; // [1, 2, 3]\narr.length; // 3\n
\n

If more than one trailing comma is used, an elision (or hole) is produced. An array with holes is called sparse (a dense array has no holes). When iterating arrays for example with Array.prototype.forEach() or Array.prototype.map(), array holes are skipped. Sparse arrays are generally unfavorable, so you should avoid having multiple trailing commas.

\n

js

\n
const arr = [1, 2, 3, , ,];\narr.length; // 5\n
\n

Objects

Trailing commas in object literals are legal as well:

\n

js

\n
const object = {\n  foo: \"bar\",\n  baz: \"qwerty\",\n  age: 42,\n};\n
\n
\n

Trailing commas in functions

\n
\n

Trailing commas are also allowed in function parameter lists.

Parameter definitions

The following function definition pairs are legal and equivalent to each other. Trailing commas don't affect the length property of function declarations or their arguments object.

\n

js

\n
function f(p) {}\nfunction f(p,) {}\n\n(p) => {};\n(p,) => {};\n
\n

The trailing comma also works with method definitions for classes or objects:

\n

js

\n
class C {\n  one(a,) {}\n  two(a, b,) {}\n}\n\nconst obj = {\n  one(a,) {},\n  two(a, b,) {},\n};\n
\n

Function calls

The following function invocation pairs are legal and equivalent to each other.

\n

js

\n
f(p);\nf(p,);\n\nMath.max(10, 20);\nMath.max(10, 20,);\n
\n

Illegal trailing commas

Function parameter definitions or function invocations only containing a comma will throw a SyntaxError. Furthermore, when using rest parameters, trailing commas are not allowed:

\n

js

\n
function f(,) {} // SyntaxError: missing formal parameter\n(,) => {};       // SyntaxError: expected expression, got ','\nf(,)             // SyntaxError: expected expression, got ','\n\nfunction f(...p,) {} // SyntaxError: parameter after rest parameter\n(...p,) => {}        // SyntaxError: expected closing parenthesis, got ','\n
\n
\n

Trailing commas in destructuring

\n
\n

A trailing comma is also allowed on the left-hand side when using destructuring assignment:

\n

js

\n
// array destructuring with trailing comma\n[a, b,] = [1, 2];\n\n// object destructuring with trailing comma\nconst o = {\n  p: 42,\n  q: true,\n};\nconst { p, q, } = o;\n
\n

Again, when using a rest element, a SyntaxError will be thrown:

\n

js

\n
const [a, ...b,] = [1, 2, 3];\n// SyntaxError: rest element may not have a trailing comma\n
\n
\n

Trailing commas in JSON

\n
\n

As JSON is based on a very restricted subset of JavaScript syntax, trailing commas are not allowed in JSON.

Both lines will throw a SyntaxError:

\n

js

\n
JSON.parse(\"[1, 2, 3, 4, ]\");\nJSON.parse('{\"foo\" : 1, }');\n// SyntaxError JSON.parse: unexpected character\n// at line 1 column 14 of the JSON data\n
\n

Omit the trailing commas to parse the JSON correctly:

\n

js

\n
JSON.parse(\"[1, 2, 3, 4 ]\");\nJSON.parse('{\"foo\" : 1 }');\n
\n
\n

Trailing commas in named imports and named exports

\n
\n

Trailing commas are valid in named imports and named exports.

Named imports

\n

js

\n
import {\n  A,\n  B,\n  C,\n} from \"D\";\n\nimport { X, Y, Z, } from \"W\";\n\nimport { A as B, C as D, E as F, } from \"Z\";\n
\n

Named exports

\n

js

\n
export {\n  A,\n  B,\n  C,\n};\n\nexport { A, B, C, };\n\nexport { A as B, C as D, E as F, };\n
\n
\n

Quantifier prefix

\n
\n

Note: The trailing comma in a quantifier actually changes its semantics from matching \"exactly n\" to matching \"at least n\".

\n

js

\n
/x{2}/; // Exactly 2 occurrences of \"x\"; equivalent to /xx/\n/x{2,}/; // At least 2 occurrences of \"x\"; equivalent to /xx+/\n/x{2,4}/; // 2 to 4 occurrences of \"x\"; equivalent to /xxx?x?/\n
\n
\n

Specifications

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# prod-Elision
ECMAScript Language Specification
# prod-ObjectLiteral
ECMAScript Language Specification
# prod-ArrayLiteral
ECMAScript Language Specification
# prod-Arguments
ECMAScript Language Specification
# prod-FormalParameters
ECMAScript Language Specification
# prod-CoverParenthesizedExpressionAndArrowParameterList
ECMAScript Language Specification
# prod-NamedImports
ECMAScript Language Specification
# prod-NamedExports
ECMAScript Language Specification
# prod-QuantifierPrefix
ECMAScript Language Specification
# prod-annexB-InvalidBracedQuantifier
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Trailing_commas112199.514.418410.111.01.00.10.0
trailing_commas_in_dynamic_import9191NoNoNo159191NoNo1516.01.1717.5.016.15.0–17.0.0
16.14.0–16.15.0The second parameter no longer throws a parser error, but the --experimental-json-modules flag is still needed to load JSON modules.
\n
trailing_commas_in_functions581452No451058585243107.01.08.0.0
trailing_commas_in_object_literals112199.534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas\n

\n
\n", + "errors": "

JavaScript error reference

\n

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the Error object, and has a name and a message.

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

For a beginner's introductory tutorial on fixing JavaScript errors, see What went wrong? Troubleshooting JavaScript.

\n
\n

List of errors

\n
\n

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

\n\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors\n

\n
\n", + "strict_mode": "

Strict mode

\n

Note: Sometimes you'll see the default, non-strict mode referred to as sloppy mode. This isn't an official term, but be aware of it, just in case.

JavaScript's strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of \"sloppy mode\". Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

Strict mode makes several changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMAScript.
\n
\n

Invoking strict mode

\n

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, Function code, event handler attributes, strings passed to setTimeout(), and related functions are either function bodies or entire scripts, and invoking strict mode in them works as expected.

Strict mode for scripts

\n
\n

To invoke strict mode for an entire script, put the exact statement \"use strict\"; (or 'use strict';) before any other statements.

\n

js

\n
// Whole-script strict mode syntax\n\"use strict\";\nconst v = \"Hi! I'm a strict mode script!\";\n
\n
\n

Strict mode for functions

\n
\n

Likewise, to invoke strict mode for a function, put the exact statement \"use strict\"; (or 'use strict';) in the function's body before any other statements.

\n

js

\n
function myStrictFunction() {\n  // Function-level strict mode syntax\n  \"use strict\";\n  function nested() {\n    return \"And so am I!\";\n  }\n  return `Hi! I'm a strict mode function! ${nested()}`;\n}\nfunction myNotStrictFunction() {\n  return \"I'm not strict.\";\n}\n
\n

The \"use strict\" directive can only be applied to the body of functions with simple parameters. Using \"use strict\" in functions with rest, default, or destructured parameters is a syntax error.

\n

js

\n
function sum(a = 1, b = 2) {\n  // SyntaxError: \"use strict\" not allowed in function with default parameter\n  \"use strict\";\n  return a + b;\n}\n
\n
\n

Strict mode for modules

\n
\n

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

\n

js

\n
function myStrictFunction() {\n  // because this is a module, I'm strict by default\n}\nexport default myStrictFunction;\n
\n
\n

Strict mode for classes

\n
\n

All parts of a class's body are strict mode code, including both class declarations and class expressions.

\n

js

\n
class C1 {\n  // All code here is evaluated in strict mode\n  test() {\n    delete Object.prototype;\n  }\n}\nnew C1().test(); // TypeError, because test() is in strict mode\n\nconst C2 = class {\n  // All code here is evaluated in strict mode\n};\n\n// Code here may not be in strict mode\ndelete Object.prototype; // Will not throw error\n
\n
\n

Changes in strict mode

\n
\n

Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories:

\n

Converting mistakes into errors

\n
\n

Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they're discovered and promptly fixed.

Assigning to undeclared variables

Strict mode makes it impossible to accidentally create global variables. In sloppy mode, mistyping a variable in an assignment creates a new property on the global object and continues to \"work\". Assignments which would accidentally create global variables throw an error in strict mode:

\n

js

\n
\"use strict\";\nlet mistypeVariable;\n\n// Assuming no global variable mistypeVarible exists\n// this line throws a ReferenceError due to the\n// misspelling of \"mistypeVariable\" (lack of an \"a\")\nmistypeVarible = 17;\n
\n

Failing to assign to object properties

Strict mode makes assignments which would otherwise silently fail to throw an exception. There are three ways to fail a property assignment:

For example, NaN is a non-writable global variable. In sloppy mode, assigning to NaN does nothing; the developer receives no failure feedback. In strict mode, assigning to NaN throws an exception.

\n

js

\n
\"use strict\";\n\n// Assignment to a non-writable global\nundefined = 5; // TypeError\nInfinity = 5; // TypeError\n\n// Assignment to a non-writable property\nconst obj1 = {};\nObject.defineProperty(obj1, \"x\", { value: 42, writable: false });\nobj1.x = 9; // TypeError\n\n// Assignment to a getter-only property\nconst obj2 = {\n  get x() {\n    return 17;\n  },\n};\nobj2.x = 5; // TypeError\n\n// Assignment to a new property on a non-extensible object\nconst fixed = {};\nObject.preventExtensions(fixed);\nfixed.newProp = \"ohai\"; // TypeError\n
\n

Failing to delete object properties

Attempts to delete a non-configurable or otherwise undeletable (e.g. it's intercepted by a proxy's deleteProperty handler which returns false) property throw in strict mode (where before the attempt would have no effect):

\n

js

\n
\"use strict\";\ndelete Object.prototype; // TypeError\ndelete [].length; // TypeError\n
\n

Strict mode also forbids deleting plain names. delete name in strict mode is a syntax error:

\n

js

\n
\"use strict\";\n\nvar x;\ndelete x; // syntax error\n
\n

If the name is a configurable global property, prefix it with globalThis to delete it.

\n

js

\n
\"use strict\";\n\ndelete globalThis.x;\n
\n

Duplicate parameter names

Strict mode requires that function parameter names be unique. In sloppy mode, the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments, so they're not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode, duplicate argument names are a syntax error:

\n

js

\n
function sum(a, a, c) {\n  // syntax error\n  \"use strict\";\n  return a + a + c; // wrong if this code ran\n}\n
\n

Legacy octal literals

Strict mode forbids a 0-prefixed octal literal or octal escape sequence. In sloppy mode, a number beginning with a 0, such as 0644, is interpreted as an octal number (0644 === 420), if all digits are smaller than 8. Novice developers sometimes believe a leading-zero prefix has no semantic meaning, so they might use it as an alignment device — but this changes the number's meaning! A leading-zero syntax for the octal is rarely useful and can be mistakenly used, so strict mode makes it a syntax error:

\n

js

\n
\"use strict\";\nconst sum =\n  015 + // syntax error\n  197 +\n  142;\n
\n

The standardized way to denote octal literals is via the 0o prefix. For example:

\n

js

\n
const sumWithOctal = 0o10 + 8;\nconsole.log(sumWithOctal); // 16\n
\n

Octal escape sequences, such as \"\\45\", which is equal to \"%\", can be used to represent characters by extended-ASCII character code numbers in octal. In strict mode, this is a syntax error. More formally, it's disallowed to have \\ followed by any decimal digit other than 0, or \\0 followed by a decimal digit; for example \\9 and \\07.

Setting properties on primitive values

Strict mode forbids setting properties on primitive values. Accessing a property on a primitive implicitly creates a wrapper object that's unobservable, so in sloppy mode, setting properties is ignored (no-op). In strict mode, a TypeError is thrown.

\n

js

\n
\"use strict\";\n\nfalse.true = \"\"; // TypeError\n(14).sailing = \"home\"; // TypeError\n\"with\".you = \"far away\"; // TypeError\n
\n

Duplicate property names

Duplicate property names used to be considered a SyntaxError in strict mode. With the introduction of computed property names, making duplication possible at runtime, this restriction was removed in ES2015.

\n

js

\n
\"use strict\";\nconst o = { p: 1, p: 2 }; // syntax error prior to ECMAScript 2015\n
\n

Note: Making code that used to error become non-errors is always considered backwards-compatible. This is a good part of the language being strict about throwing errors: it leaves room for future semantic changes.

\n

Simplifying scope management

\n
\n

Strict mode simplifies how variable names map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that variable X is stored in that location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform until runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.

Removal of the with statement

Strict mode prohibits with. The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime; it's impossible to know which beforehand. Strict mode makes with a syntax error, so there's no chance for a name in a with to refer to an unknown location at runtime:

\n

js

\n
\"use strict\";\nconst x = 17;\nwith (obj) {\n  // Syntax error\n  // If this weren't strict mode, would this be const x, or\n  // would it instead be obj.x? It's impossible in general\n  // to say without running the code, so the name can't be\n  // optimized.\n  x;\n}\n
\n

The simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with.

Non-leaking eval

In strict mode, eval does not introduce new variables into the surrounding scope. In sloppy mode, eval(\"var x;\") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval, every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode, eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable:

\n

js

\n
var x = 17;\nvar evalX = eval(\"'use strict'; var x = 42; x;\");\nconsole.assert(x === 17);\nconsole.assert(evalX === 42);\n
\n

Whether the string passed to eval() is evaluated in strict mode depends on how eval() is invoked (direct eval or indirect eval).

Block-scoped function declarations

The JavaScript language specification, since its start, had not allowed function declarations nested in block statements. However, it was so intuitive that most browsers implemented it as an extension grammar. Unfortunately, the implementations' semantics diverged, and it became impossible for the language specification to reconcile all implementations. Therefore, block-scoped function declarations are only explicitly specified in strict mode (whereas they were once disallowed in strict mode), while sloppy mode behavior remains divergent among browsers.

\n

Making eval and arguments simpler

\n
\n

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in sloppy mode: eval to add or remove bindings and to change binding values, and arguments syncing named arguments with its indexed properties. Strict mode makes great strides toward treating eval and arguments as keywords.

Preventing binding or assigning eval and arguments

The names eval and arguments can't be bound or assigned in language syntax. All these attempts to do so are syntax errors:

\n

js

\n
\"use strict\";\neval = 17;\narguments++;\n++eval;\nconst obj = { set p(arguments) {} };\nlet eval;\ntry {\n} catch (arguments) {}\nfunction x(eval) {}\nfunction arguments() {}\nconst y = function eval() {};\nconst f = new Function(\"arguments\", \"'use strict'; return 17;\");\n
\n

No syncing between parameters and arguments indices

Strict mode code doesn't sync indices of the arguments object with each parameter binding. In a sloppy mode function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted). arguments objects for strict mode functions store the original arguments when the function was invoked. arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

\n

js

\n
function f(a) {\n  \"use strict\";\n  a = 42;\n  return [a, arguments[0]];\n}\nconst pair = f(17);\nconsole.assert(pair[0] === 42);\nconsole.assert(pair[1] === 17);\n
\n
\n

\"Securing\" JavaScript

\n
\n

Strict mode makes it easier to write \"secure\" JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user's private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript's flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has a considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.

No this substitution

The value passed as this to a function in strict mode is not forced into being an object (a.k.a. \"boxed\"). For a sloppy mode function, this is always an object: either the provided object, if called with an object-valued this; or the boxed value of this, if called with a primitive as this; or the global object, if called with undefined or null as this. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that \"secure\" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this is undefined instead of globalThis:

\n

js

\n
\"use strict\";\nfunction fun() {\n  return this;\n}\nconsole.assert(fun() === undefined);\nconsole.assert(fun.call(2) === 2);\nconsole.assert(fun.apply(null) === null);\nconsole.assert(fun.call(undefined) === undefined);\nconsole.assert(fun.bind(true)() === true);\n
\n

Removal of stack-walking properties

In strict mode it's no longer possible to \"walk\" the JavaScript stack. Many implementations used to implement some extension features that make it possible to detect the upstream caller of a function. When a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. Both extensions are problematic for \"secure\" JavaScript because they allow \"secured\" code to access \"privileged\" functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved:

\n

js

\n
function restricted() {\n  \"use strict\";\n  restricted.caller; // throws a TypeError\n  restricted.arguments; // throws a TypeError\n}\nfunction privilegedInvoker() {\n  return restricted();\n}\nprivilegedInvoker();\n
\n

Similarly, arguments.callee is no longer supported. In sloppy mode, arguments.callee refers to the enclosing function. This use case is weak: name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws an error when set or retrieved:

\n

js

\n
\"use strict\";\nconst f = function () {\n  return arguments.callee;\n};\nf(); // throws a TypeError\n
\n
\n

Future-proofing JavaScript

\n
\n

Extra reserved words

Reserved words are identifiers that can't be used as variable names. Strict mode reserves some more names than sloppy mode, some of which are already used in the language, and some of which are reserved for the future to make future syntax extensions easier to implement.

\n

Transitioning to strict mode

\n
\n

Strict mode has been designed so that the transition to it can be made gradually. It is possible to change each file individually and even to transition code to strict mode down to the function granularity.

You can migrate a codebase to strict mode by first adding \"use strict\" to a piece of source code, and then fixing all execution errors, while watching out for semantic differences.

\n

Syntax errors

\n
\n

When adding 'use strict';, the following cases will throw a SyntaxError before the script is executing:

These errors are good, because they reveal plain errors or bad practices. They occur before the code is running, so they are easily discoverable as long as the code gets parsed by the runtime.

\n

New runtime errors

\n
\n

JavaScript used to silently fail in contexts where what was done should be an error. Strict mode throws in such cases. If your code base contains such cases, testing will be necessary to be sure nothing is broken. You can screen for such errors at the function granularity level.

\n

Semantic differences

\n
\n

These differences are very subtle differences. It's possible that a test suite doesn't catch this kind of subtle difference. Careful review of your code base will probably be necessary to be sure these differences don't affect the semantics of your code. Fortunately, this careful review can be done gradually down the function granularity.

this

In sloppy mode, function calls like f() would pass the global object as the this value. In strict mode, it is now undefined. When a function was called with call or apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or replacement.

arguments

In sloppy mode, modifying a value in the arguments object modifies the corresponding named argument. This made optimizations complicated for JavaScript engine and made code harder to read/understand. In strict mode, the arguments object is created and initialized with the same values than the named arguments, but changes to either the arguments object or the named arguments aren't reflected in one another.

eval

In strict mode code, eval doesn't create a new variable in the scope from which it was called. Also, of course, in strict mode, the string is evaluated with strict mode rules. Thorough testing will need to be performed to make sure nothing breaks. Not using eval if you don't really need it may be another pragmatic solution.

Block-scoped function declarations

In sloppy mode, a function declaration inside a block may be visible outside the block and even callable. In strict mode, a function declaration inside a block is only visible inside the block.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\n

\n
\n", + "global_objects/promise/any": "

Promise.any()

The Promise.any() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an AggregateError containing an array of rejection reasons.

\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.any(iterable)\n
\n

Parameters

\n
iterable

An iterable (such as an Array) of promises.

Return value

\n
\n

A Promise that is:

\n

Description

\n
\n

The Promise.any() method is one of the promise concurrency methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one.

Unlike Promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an empty iterable, since, truthfully, the iterable contains no items that fulfill. You may compare Promise.any() and Promise.all() with Array.prototype.some() and Array.prototype.every().

Also, unlike Promise.race(), which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value. This method ignores all rejected promises up until the first promise that fulfills.

\n

Examples

\n

Using Promise.any()

\n
\n

Promise.any() fulfills with the first promise to fulfill, even if a promise rejects first. This is in contrast to Promise.race(), which fulfills or rejects with the first promise to settle.

\n

js

\n
const pErr = new Promise((resolve, reject) => {\n  reject(\"Always fails\");\n});\n\nconst pSlow = new Promise((resolve, reject) => {\n  setTimeout(resolve, 500, \"Done eventually\");\n});\n\nconst pFast = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, \"Done quick\");\n});\n\nPromise.any([pErr, pSlow, pFast]).then((value) => {\n  console.log(value);\n  // pFast fulfills first\n});\n// Logs:\n// Done quick\n
\n
\n

Rejections with AggregateError

\n
\n

Promise.any() rejects with an AggregateError if no promise fulfills.

\n

js

\n
const failure = new Promise((resolve, reject) => {\n  reject(\"Always fails\");\n});\n\nPromise.any([failure]).catch((err) => {\n  console.log(err);\n});\n// AggregateError: No Promise in Promise.any was resolved\n
\n
\n

Displaying the first image loaded

\n
\n

In this example, we have a function that fetches an image and returns a blob. We use Promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved).

\n

js

\n
async function fetchAndDecode(url, description) {\n  const res = await fetch(url);\n  if (!res.ok) {\n    throw new Error(`HTTP error! status: ${res.status}`);\n  }\n  const data = await res.blob();\n  return [data, description];\n}\n\nconst coffee = fetchAndDecode(\"coffee.jpg\", \"Coffee\");\nconst tea = fetchAndDecode(\"tea.jpg\", \"Tea\");\n\nPromise.any([coffee, tea])\n  .then(([blob, description]) => {\n    const objectURL = URL.createObjectURL(blob);\n    const image = document.createElement(\"img\");\n    image.src = objectURL;\n    image.alt = description;\n    document.body.appendChild(image);\n  })\n  .catch((e) => {\n    console.error(e);\n  });\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.any
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
any858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any\n

\n
\n", + "global_objects/aggregateerror/aggregateerror": "

AggregateError() constructor

The AggregateError() constructor creates AggregateError objects.

\n

Syntax

\n
\n
\n

js

\n
new AggregateError(errors)\nnew AggregateError(errors, message)\nnew AggregateError(errors, message, options)\n\nAggregateError(errors)\nAggregateError(errors, message)\nAggregateError(errors, message, options)\n
\n

Note: AggregateError() can be called with or without new. Both create a new AggregateError instance.

\n

Parameters

\n
errors

An iterable of errors, may not actually be Error instances.

\nmessage Optional\n

An optional human-readable description of the aggregate error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

Examples

\n

Creating an AggregateError

\n
\n

js

\n
try {\n  throw new AggregateError([new Error(\"some error\")], \"Hello\");\n} catch (e) {\n  console.log(e instanceof AggregateError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"AggregateError\"\n  console.log(e.errors); // [ Error: \"some error\" ]\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-aggregate-error-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AggregateError858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError/AggregateError\n

\n
\n", + "global_objects/object/constructor": "

Object.prototype.constructor

\n

The constructor data property of an Object instance returns a reference to the constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Note: This is a property of JavaScript objects. For the constructor method in classes, see its own reference page.

\n
\n

Value

\n
\n

A reference to the constructor function that created the instance object.

\n
Property attributes of Object.prototype.constructor\n
Writable yes
Enumerable no
Configurable yes

Note: This property is created by default on the prototype property of every constructor function and is inherited by all objects created by that constructor.

\n

Description

\n
\n

Any object (with the exception of null prototype objects) will have a constructor property on its [[Prototype]]. Objects created with literals will also have a constructor property that points to the constructor type for that object — for example, array literals create Array objects, and object literals create plain objects.

\n

js

\n
const o1 = {};\no1.constructor === Object; // true\n\nconst o2 = new Object();\no2.constructor === Object; // true\n\nconst a1 = [];\na1.constructor === Array; // true\n\nconst a2 = new Array();\na2.constructor === Array; // true\n\nconst n = 3;\nn.constructor === Number; // true\n
\n

Note that constructor usually comes from the constructor's prototype property. If you have a longer prototype chain, you can usually expect every object in the chain to have a constructor property.

\n

js

\n
const o = new TypeError(); // Inheritance: TypeError -> Error -> Object\nconst proto = Object.getPrototypeOf;\nproto(o).constructor === TypeError; // true\nproto(proto(o)).constructor === Error; // true\nproto(proto(proto(o))).constructor === Object; // true\n
\n
\n

Examples

\n

Displaying the constructor of an object

\n
\n

The following example creates a constructor (Tree) and an object of that type (theTree). The example then displays the constructor property for the object theTree.

\n

js

\n
function Tree(name) {\n  this.name = name;\n}\n\nconst theTree = new Tree(\"Redwood\");\nconsole.log(`theTree.constructor is ${theTree.constructor}`);\n
\n

This example displays the following output:

theTree.constructor is function Tree(name) {\n  this.name = name;\n}\n
\n

Assigning the constructor property to an object

\n
\n

One can assign the constructor property of non-primitives.

\n

js

\n
const arr = [];\narr.constructor = String;\narr.constructor === String; // true\narr instanceof String; // false\narr instanceof Array; // true\n\nconst foo = new Foo();\nfoo.constructor = \"bar\";\nfoo.constructor === \"bar\"; // true\n\n// etc.\n
\n

This does not overwrite the old constructor property — it was originally present on the instance's [[Prototype]], not as its own property.

\n

js

\n
const arr = [];\nObject.hasOwn(arr, \"constructor\"); // false\nObject.hasOwn(Object.getPrototypeOf(arr), \"constructor\"); // true\n\narr.constructor = String;\nObject.hasOwn(arr, \"constructor\"); // true — the instance property shadows the one on its prototype\n
\n

But even when Object.getPrototypeOf(a).constructor is re-assigned, it won't change other behaviors of the object. For example, the behavior of instanceof is controlled by Symbol.hasInstance, not constructor:

\n

js

\n
const arr = [];\narr.constructor = String;\narr instanceof String; // false\narr instanceof Array; // true\n
\n

There is nothing protecting the constructor property from being re-assigned or shadowed, so using it to detect the type of a variable should usually be avoided in favor of less fragile ways like instanceof and Symbol.toStringTag for objects, or typeof for primitives.

\n

Changing the constructor of a constructor function's prototype

\n
\n

Every constructor has a prototype property, which will become the instance's [[Prototype]] when called via the new operator. ConstructorFunction.prototype.constructor will therefore become a property on the instance's [[Prototype]], as previously demonstrated.

However, if ConstructorFunction.prototype is re-assigned, the constructor property will be lost. For example, the following is a common way to create an inheritance pattern:

\n

js

\n
function Parent() {\n  // …\n}\nParent.prototype.parentMethod = function () {};\n\nfunction Child() {\n  Parent.call(this); // Make sure everything is initialized properly\n}\n// Pointing the [[Prototype]] of Child.prototype to Parent.prototype\nChild.prototype = Object.create(Parent.prototype);\n
\n

The constructor of instances of Child will be Parent due to Child.prototype being re-assigned.

This is usually not a big deal — the language almost never reads the constructor property of an object. The only exception is when using @@species to create new instances of a class, but such cases are rare, and you should be using the extends syntax to subclass builtins anyway.

However, ensuring that Child.prototype.constructor always points to Child itself is crucial when some caller is using constructor to access the original class from an instance. Take the following case: the object has the create() method to create itself.

\n

js

\n
function Parent() {\n  // …\n}\nfunction CreatedConstructor() {\n  Parent.call(this);\n}\n\nCreatedConstructor.prototype = Object.create(Parent.prototype);\n\nCreatedConstructor.prototype.create = function () {\n  return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // TypeError: new CreatedConstructor().create().create is undefined, since constructor === Parent\n
\n

In the example above, an exception is thrown, since the constructor links to Parent. To avoid this, just assign the necessary constructor you are going to use.

\n

js

\n
function Parent() {\n  // …\n}\nfunction CreatedConstructor() {\n  // …\n}\n\nCreatedConstructor.prototype = Object.create(Parent.prototype, {\n  // Return original constructor to Child\n  constructor: {\n    value: CreatedConstructor,\n    enumerable: false, // Make it non-enumerable, so it won't appear in `for...in` loop\n    writable: true,\n    configurable: true,\n  },\n});\n\nCreatedConstructor.prototype.create = function () {\n  return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // it's pretty fine\n
\n

Note that when manually adding the constructor property, it's crucial to make the property non-enumerable, so constructor won't be visited in for...in loops — as it normally isn't.

If the code above looks like too much boilerplate, you may also consider using Object.setPrototypeOf() to manipulate the prototype chain.

\n

js

\n
function Parent() {\n  // …\n}\nfunction CreatedConstructor() {\n  // …\n}\n\nObject.setPrototypeOf(CreatedConstructor.prototype, Parent.prototype);\n\nCreatedConstructor.prototype.create = function () {\n  return new this.constructor();\n};\n\nnew CreatedConstructor().create().create(); // still works without re-creating constructor property\n
\n

Object.setPrototypeOf() comes with its potential performance downsides because all previously created objects involved in the prototype chain have to be re-compiled; but if the above initialization code happens before Parent or CreatedConstructor are constructed, the effect should be minimal.

Let's consider one more involved case.

\n

js

\n
function ParentWithStatic() {}\n\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\n  return this.startPosition;\n};\n\nfunction Child(x, y) {\n  this.position = { x, y };\n}\n\nChild.prototype = Object.create(ParentWithStatic.prototype, {\n  // Return original constructor to Child\n  constructor: {\n    value: Child,\n    enumerable: false,\n    writable: true,\n    configurable: true,\n  },\n});\n\nChild.prototype.getOffsetByInitialPosition = function () {\n  const position = this.position;\n  // Using this.constructor, in hope that getStartPosition exists as a static method\n  const startPosition = this.constructor.getStartPosition();\n\n  return {\n    offsetX: startPosition.x - position.x,\n    offsetY: startPosition.y - position.y,\n  };\n};\n\nnew Child(1, 1).getOffsetByInitialPosition();\n// Error: this.constructor.getStartPosition is undefined, since the\n// constructor is Child, which doesn't have the getStartPosition static method\n
\n

For this example to work properly, we can reassign the Parent's static properties to Child:

\n

js

\n
// …\nObject.assign(Child, ParentWithStatic); // Notice that we assign it before we create() a prototype below\nChild.prototype = Object.create(ParentWithStatic.prototype, {\n  // Return original constructor to Child\n  constructor: {\n    value: Child,\n    enumerable: false,\n    writable: true,\n    configurable: true,\n  },\n});\n// …\n
\n

But even better, we can make the constructor functions themselves extend each other, as classes' extends do.

\n

js

\n
function ParentWithStatic() {}\n\nParentWithStatic.startPosition = { x: 0, y: 0 }; // Static member property\nParentWithStatic.getStartPosition = function () {\n  return this.startPosition;\n};\n\nfunction Child(x, y) {\n  this.position = { x, y };\n}\n\n// Properly create inheritance!\nObject.setPrototypeOf(Child.prototype, ParentWithStatic.prototype);\nObject.setPrototypeOf(Child, ParentWithStatic);\n\nChild.prototype.getOffsetByInitialPosition = function () {\n  const position = this.position;\n  const startPosition = this.constructor.getStartPosition();\n\n  return {\n    offsetX: startPosition.x - position.x,\n    offsetY: startPosition.y - position.y,\n  };\n};\n\nconsole.log(new Child(1, 1).getOffsetByInitialPosition()); // { offsetX: -1, offsetY: -1 }\n
\n

Again, using Object.setPrototypeOf() may have adverse performance effects, so make sure it happens immediately after the constructor declaration and before any instances are created — to avoid objects being \"tainted\".

Note: Manually updating or setting the constructor can lead to different and sometimes confusing consequences. To prevent this, just define the role of constructor in each specific case. In most cases, constructor is not used and reassigning it is not necessary.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
constructor11218414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor\n

\n
\n", + "global_objects/error/name": "

Error.prototype.name

The name data property of Error.prototype is shared by all Error instances. It represents the name for the type of error. For Error.prototype.name, the initial value is \"Error\". Subclasses like TypeError and SyntaxError provide their own name properties.

\n

Value

\n
\n

A string. For Error.prototype.name, the initial value is \"Error\".

\n
Property attributes of Error.prototype.name\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n

By default, Error instances are given the name \"Error\". The name property, in addition to the message property, is used by the Error.prototype.toString() method to create a string representation of the error.

Examples

\n

Throwing a custom error

\n
\n

js

\n
const e = new Error(\"Malformed input\"); // e.name is 'Error'\n\ne.name = \"ParseError\";\nthrow e;\n// e.toString() would return 'ParseError: Malformed input'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-error.prototype.name
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
name11216414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name\n

\n
\n", + "global_objects/aggregateerror/errors": "

AggregateError: errors

The errors data property of an AggregateError instance contains an array representing the errors that were aggregated.

\n

Value

\n
\n

An Array containing values in the same order as the iterable passed as the first argument of the AggregateError() constructor.

\n
Property attributes of AggregateError: errors\n
Writable yes
Enumerable no
Configurable yes
\n

Examples

\n

Using errors

\n
\n

js

\n
try {\n  throw new AggregateError(\n    // An iterable of errors\n    new Set([new Error(\"some error\"), new Error(\"another error\")]),\n    \"Multiple errors thrown\",\n  );\n} catch (err) {\n  console.log(err.errors);\n  // [\n  //   Error: some error,\n  //   Error: another error\n  // ]\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-aggregate-error
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
errors858579No7114858579601414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError/errors\n

\n
\n", + "global_objects/number/positive_infinity": "

Number.POSITIVE_INFINITY

The Number.POSITIVE_INFINITY static data property represents the positive Infinity value.

\n

Try it

\n

Value

\n
\n

The same as the value of the global Infinity property.

\n
Property attributes of Number.POSITIVE_INFINITY\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The Number.POSITIVE_INFINITY value behaves slightly differently than mathematical infinity:

You might use the Number.POSITIVE_INFINITY property to indicate an error condition that returns a finite number in case of success. Note, however, that NaN would be more appropriate in such a case.

Because POSITIVE_INFINITY is a static property of Number, you always use it as Number.POSITIVE_INFINITY, rather than as a property of a number value.

\n

Examples

\n

Using POSITIVE_INFINITY

\n
\n

In the following example, the variable bigNumber is assigned a value that is larger than the maximum value. When the if statement executes, bigNumber has the value Infinity, so bigNumber is set to a more manageable value before continuing.

\n

js

\n
let bigNumber = Number.MAX_VALUE * 2;\n\nif (bigNumber === Number.POSITIVE_INFINITY) {\n  bigNumber = returnFinite();\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.positive_infinity
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
POSITIVE_INFINITY11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY\n

\n
\n", + "global_objects/number/negative_infinity": "

Number.NEGATIVE_INFINITY

The Number.NEGATIVE_INFINITY static data property represents the negative Infinity value.

\n

Try it

\n

Value

\n
\n

The same as the negative value of the global Infinity property.

\n
Property attributes of Number.NEGATIVE_INFINITY\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The Number.NEGATIVE_INFINITY value behaves slightly differently than mathematical infinity:

You might use the Number.NEGATIVE_INFINITY property to indicate an error condition that returns a finite number in case of success. Note, however, that NaN would be more appropriate in such a case.

Because NEGATIVE_INFINITY is a static property of Number, you always use it as Number.NEGATIVE_INFINITY, rather than as a property of a number value.

\n

Examples

\n

Using NEGATIVE_INFINITY

\n
\n

In the following example, the variable smallNumber is assigned a value that is smaller than the minimum value. When the if statement executes, smallNumber has the value -Infinity, so smallNumber is set to a more manageable value before continuing.

\n

js

\n
let smallNumber = -Number.MAX_VALUE * 2;\n\nif (smallNumber === Number.NEGATIVE_INFINITY) {\n  smallNumber = returnFinite();\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.negative_infinity
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
NEGATIVE_INFINITY11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY\n

\n
\n", + "global_objects/number/isfinite": "

Number.isFinite()

The Number.isFinite() static method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive Infinity, negative Infinity, nor NaN.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.isFinite(value)\n
\n

Parameters

\n
value

The value to be tested for finiteness.

Return value

\n

The boolean value true if the given value is a finite number. Otherwise false.

Examples

\n

Using isFinite()

\n
\n

js

\n
Number.isFinite(Infinity); // false\nNumber.isFinite(NaN); // false\nNumber.isFinite(-Infinity); // false\n\nNumber.isFinite(0); // true\nNumber.isFinite(2e64); // true\n
\n

Difference between Number.isFinite() and global isFinite()

\n
\n

In comparison to the global isFinite() function, this method doesn't first convert the parameter to a number. This means only values of the type number and are finite return true, and non-numbers always return false.

\n

js

\n
isFinite(\"0\"); // true; coerced to number 0\nNumber.isFinite(\"0\"); // false\nisFinite(null); // true; coerced to number 0\nNumber.isFinite(null); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.isfinite
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isFinite191216No1594.425161491.51.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite\n

\n
\n", + "global_objects/number/nan": "

Number.NaN

The Number.NaN static data property represents Not-A-Number, which is equivalent to NaN. For more information about the behaviors of NaN, see the description for the global property.

\n

Try it

\n

Value

\n
\n

The number value NaN.

\n
Property attributes of Number.NaN\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because NaN is a static property of Number, you always use it as Number.NaN, rather than as a property of a number value.

Examples

\n

Checking whether values are numeric

\n
\n

js

\n
function sanitize(x) {\n  if (isNaN(x)) {\n    return Number.NaN;\n  }\n  return x;\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.nan
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
NaN11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN\n

\n
\n", + "global_objects/number/isnan": "

Number.isNaN()

The Number.isNaN() static method determines whether the passed value is the number value NaN, and returns false if the input is not of the Number type. It is a more robust version of the original, global isNaN() function.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.isNaN(value)\n
\n

Parameters

\n
value

The value to be tested for NaN.

Return value

\n

The boolean value true if the given value is a number with value NaN. Otherwise, false.

Description

\n
\n

The function Number.isNaN() provides a convenient way to check for equality with NaN. Note that you cannot test for equality with NaN using either the == or === operators, because unlike all other value comparisons in JavaScript, these evaluate to false whenever one operand is NaN, even if the other operand is also NaN.

Since x !== x is only true for NaN among all possible JavaScript values, Number.isNaN(x) can also be replaced with a test for x !== x, despite the latter being less readable.

As opposed to the global isNaN() function, the Number.isNaN() method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to NaN but aren't actually the same value as NaN. This also means that only values of the Number type that are also NaN return true.

\n

Examples

\n

Using isNaN()

\n
\n

js

\n
Number.isNaN(NaN); // true\nNumber.isNaN(Number.NaN); // true\nNumber.isNaN(0 / 0); // true\nNumber.isNaN(37); // false\n
\n

Difference between Number.isNaN() and global isNaN()

\n
\n

Number.isNaN() doesn't attempt to convert the parameter to a number, so non-numbers always return false. The following are all false:

\n

js

\n
Number.isNaN(\"NaN\");\nNumber.isNaN(undefined);\nNumber.isNaN({});\nNumber.isNaN(\"blabla\");\nNumber.isNaN(true);\nNumber.isNaN(null);\nNumber.isNaN(\"37\");\nNumber.isNaN(\"37.37\");\nNumber.isNaN(\"\");\nNumber.isNaN(\" \");\n
\n

The global isNaN() coerces its parameter to a number:

\n

js

\n
isNaN(\"NaN\"); // true\nisNaN(undefined); // true\nisNaN({}); // true\nisNaN(\"blabla\"); // true\nisNaN(true); // false, this is coerced to 1\nisNaN(null); // false, this is coerced to 0\nisNaN(\"37\"); // false, this is coerced to 37\nisNaN(\"37.37\"); // false, this is coerced to 37.37\nisNaN(\"\"); // false, this is coerced to 0\nisNaN(\" \"); // false, this is coerced to 0\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.isnan
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isNaN251215No1594.425151491.51.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN\n

\n
\n", + "global_objects/array/indexof": "

Array.prototype.indexOf()

The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.

\n

Try it

\n

Syntax

\n
\n

js

\n
indexOf(searchElement)\nindexOf(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

Element to locate in the array.

\nfromIndex Optional\n

Zero-based index at which to start searching, converted to an integer.

  • Negative index counts back from the end of the array — if fromIndex < 0, fromIndex + array.length is used. Note, the array is still searched from front to back in this case.
  • If fromIndex < -array.length or fromIndex is omitted, 0 is used, causing the entire array to be searched.
  • If fromIndex >= array.length, the array is not searched and -1 is returned.

Return value

\n

The first index of searchElement in the array; -1 if not found.

Description

\n
\n

The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN.

The indexOf() method skips empty slots in sparse arrays.

The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Using indexOf()

\n
\n

The following example uses indexOf() to locate values in an array.

\n

js

\n
const array = [2, 9, 9];\narray.indexOf(2); // 0\narray.indexOf(7); // -1\narray.indexOf(9, 2); // 2\narray.indexOf(2, -1); // -1\narray.indexOf(2, -3); // 0\n
\n

You cannot use indexOf() to search for NaN.

\n

js

\n
const array = [NaN];\narray.indexOf(NaN); // -1\n
\n
\n

Finding all the occurrences of an element

\n
\n

js

\n
const indices = [];\nconst array = [\"a\", \"b\", \"a\", \"c\", \"a\", \"d\"];\nconst element = \"a\";\nlet idx = array.indexOf(element);\nwhile (idx !== -1) {\n  indices.push(idx);\n  idx = array.indexOf(element, idx + 1);\n}\nconsole.log(indices);\n// [0, 2, 4]\n
\n

Finding if an element exists in the array or not and updating the array

\n
\n

js

\n
function updateVegetablesCollection(veggies, veggie) {\n  if (veggies.indexOf(veggie) === -1) {\n    veggies.push(veggie);\n    console.log(`New veggies collection is: ${veggies}`);\n  } else {\n    console.log(`${veggie} already exists in the veggies collection.`);\n  }\n}\n\nconst veggies = [\"potato\", \"tomato\", \"chillies\", \"green-pepper\"];\n\nupdateVegetablesCollection(veggies, \"spinach\");\n// New veggies collection is: potato,tomato,chillies,green-pepper,spinach\nupdateVegetablesCollection(veggies, \"spinach\");\n// spinach already exists in the veggies collection.\n
\n

Using indexOf() on sparse arrays

\n
\n

You cannot use indexOf() to search for empty slots in sparse arrays.

\n

js

\n
console.log([1, , 3].indexOf(undefined)); // -1\n
\n
\n

Calling indexOf() on non-array objects

\n
\n

The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 5, // ignored by indexOf() since length is 3\n};\nconsole.log(Array.prototype.indexOf.call(arrayLike, 2));\n// 0\nconsole.log(Array.prototype.indexOf.call(arrayLike, 5));\n// -1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.indexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
indexOf1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\n

\n
\n", + "global_objects/array/lastindexof": "

Array.prototype.lastIndexOf()

The lastIndexOf() method of Array instances returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

\n

Try it

\n

Syntax

\n
\n

js

\n
lastIndexOf(searchElement)\nlastIndexOf(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

Element to locate in the array.

\nfromIndex Optional\n

Zero-based index at which to start searching backwards, converted to an integer.

  • Negative index counts back from the end of the array — if fromIndex < 0, fromIndex + array.length is used.
  • If fromIndex < -array.length, the array is not searched and -1 is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so searchElement is never found.
  • If fromIndex >= array.length or fromIndex is omitted, array.length - 1 is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.

Return value

\n

The last index of searchElement in the array; -1 if not found.

Description

\n
\n

The lastIndexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so lastIndexOf() always returns -1 when searchElement is NaN.

The lastIndexOf() method skips empty slots in sparse arrays.

The lastIndexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Using lastIndexOf()

\n
\n

The following example uses lastIndexOf() to locate values in an array.

\n

js

\n
const numbers = [2, 5, 9, 2];\nnumbers.lastIndexOf(2); // 3\nnumbers.lastIndexOf(7); // -1\nnumbers.lastIndexOf(2, 3); // 3\nnumbers.lastIndexOf(2, 2); // 0\nnumbers.lastIndexOf(2, -2); // 0\nnumbers.lastIndexOf(2, -1); // 3\n
\n

You cannot use lastIndexOf() to search for NaN.

\n

js

\n
const array = [NaN];\narray.lastIndexOf(NaN); // -1\n
\n
\n

Finding all the occurrences of an element

\n
\n

The following example uses lastIndexOf to find all the indices of an element in a given array, using push() to add them to another array as they are found.

\n

js

\n
const indices = [];\nconst array = [\"a\", \"b\", \"a\", \"c\", \"a\", \"d\"];\nconst element = \"a\";\nlet idx = array.lastIndexOf(element);\nwhile (idx !== -1) {\n  indices.push(idx);\n  idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;\n}\n\nconsole.log(indices);\n// [4, 2, 0]\n
\n

Note that we have to handle the case idx === 0 separately here because the element will always be found regardless of the fromIndex parameter if it is the first element of the array. This is different from the indexOf() method.

\n

Using lastIndexOf() on sparse arrays

\n
\n

You cannot use lastIndexOf() to search for empty slots in sparse arrays.

\n

js

\n
console.log([1, , 3].lastIndexOf(undefined)); // -1\n
\n
\n

Calling lastIndexOf() on non-array objects

\n
\n

The lastIndexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 2,\n  3: 5, // ignored by lastIndexOf() since length is 3\n};\nconsole.log(Array.prototype.lastIndexOf.call(arrayLike, 2));\n// 2\nconsole.log(Array.prototype.lastIndexOf.call(arrayLike, 5));\n// -1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.lastindexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastIndexOf1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf\n

\n
\n", + "global_objects/array/includes": "

Array.prototype.includes()

The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.

\n

Try it

\n

Syntax

\n
\n

js

\n
includes(searchElement)\nincludes(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

The value to search for.

\nfromIndex Optional\n

Zero-based index at which to start searching, converted to an integer.

  • Negative index counts back from the end of the array — if fromIndex < 0, fromIndex + array.length is used. However, the array is still searched from front to back in this case.
  • If fromIndex < -array.length or fromIndex is omitted, 0 is used, causing the entire array to be searched.
  • If fromIndex >= array.length, the array is not searched and false is returned.

Return value

\n

A boolean value which is true if the value searchElement is found within the array (or the part of the array indicated by the index fromIndex, if specified).

Description

\n
\n

The includes() method compares searchElement to elements of the array using the SameValueZero algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, -0 is equal to 0), but false is not considered to be the same as 0. NaN can be correctly searched for.

When used on sparse arrays, the includes() method iterates empty slots as if they have the value undefined.

The includes() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Using includes()

\n
\n

js

\n
[1, 2, 3].includes(2); // true\n[1, 2, 3].includes(4); // false\n[1, 2, 3].includes(3, 3); // false\n[1, 2, 3].includes(3, -1); // true\n[1, 2, NaN].includes(NaN); // true\n[\"1\", \"2\", \"3\"].includes(3); // false\n
\n

fromIndex is greater than or equal to the array length

\n
\n

If fromIndex is greater than or equal to the length of the array, false is returned. The array will not be searched.

\n

js

\n
const arr = [\"a\", \"b\", \"c\"];\n\narr.includes(\"c\", 3); // false\narr.includes(\"c\", 100); // false\n
\n
\n

Computed index is less than 0

\n
\n

If fromIndex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for searchElement. If the computed index is less than or equal to 0, the entire array will be searched.

\n

js

\n
// array length is 3\n// fromIndex is -100\n// computed index is 3 + (-100) = -97\n\nconst arr = [\"a\", \"b\", \"c\"];\n\narr.includes(\"a\", -100); // true\narr.includes(\"b\", -100); // true\narr.includes(\"c\", -100); // true\narr.includes(\"a\", -2); // false\n
\n
\n

Using includes() on sparse arrays

\n
\n

You can search for undefined in a sparse array and get true.

\n

js

\n
console.log([1, , 3].includes(undefined)); // true\n
\n
\n

Calling includes() on non-array objects

\n
\n

The includes() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 1, // ignored by includes() since length is 3\n};\nconsole.log(Array.prototype.includes.call(arrayLike, 2));\n// true\nconsole.log(Array.prototype.includes.call(arrayLike, 1));\n// false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.includes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
includes471443No3494747433495.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\n

\n
\n", + "operators/null": "

null

The null value represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

\n

Try it

\n

Syntax

\n
\n

js

\n
null\n
\n

Description

\n
\n

The value null is written with a literal: null. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

\n

js

\n
// foo does not exist. It is not defined and has never been initialized:\nfoo; //ReferenceError: foo is not defined\n
\n
\n

js

\n
// foo is known to exist now but it has no type or value:\nconst foo = null;\nfoo; //null\n
\n
\n

Examples

\n

Difference between null and undefined\n

\n
\n

When checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion.

\n

js

\n
typeof null; // \"object\" (not \"null\" for legacy reasons)\ntypeof undefined; // \"undefined\"\nnull === undefined; // false\nnull == undefined; // true\nnull === null; // true\nnull == null; // true\n!null; // true\nNumber.isNaN(1 + null); // false\nNumber.isNaN(1 + undefined); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-null-value
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
null11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null\n

\n
\n", + "global_objects/number/number": "

Number() constructor

The Number() constructor creates Number objects. When called as a function, it returns primitive values of type Number.

\n

Syntax

\n
\n
\n

js

\n
new Number(value)\nNumber(value)\n
\n

Note: Number() can be called with or without new, but with different effects. See Return value.

\n

Parameters

\n
value

The numeric value of the object being created.

Return value

\n
\n

When Number is called as a constructor (with new), it creates a Number object, which is not a primitive.

When Number is called as a function, it coerces the parameter to a number primitive. BigInts are converted to numbers. If the value can't be converted, it returns NaN.

Warning: You should rarely find yourself using Number as a constructor.

\n

Examples

\n

Creating Number objects

\n
\n

js

\n
const a = new Number(\"123\"); // a === 123 is false\nconst b = Number(\"123\"); // b === 123 is true\na instanceof Number; // is true\nb instanceof Number; // is false\ntypeof a; // \"object\"\ntypeof b; // \"number\"\n
\n

Using Number() to convert a BigInt to a number

\n
\n

Number() is the only case where a BigInt can be converted to a number without throwing, because it's very explicit.

\n

js

\n
+1n; // TypeError: Cannot convert a BigInt value to a number\n0 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions\n
\n
\n

js

\n
Number(1n); // 1\n
\n

Note that this may result in loss of precision, if the BigInt is too large to be safely represented.

\n

js

\n
BigInt(Number(2n ** 54n + 1n)) === 2n ** 54n + 1n; // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Number11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number\n

\n
\n", + "global_objects/number/max_value": "

Number.MAX_VALUE

The Number.MAX_VALUE static data property represents the maximum numeric value representable in JavaScript.

\n

Try it

\n

Value

\n
\n

21024 - 2971, or approximately 1.7976931348623157E+308.

\n
Property attributes of Number.MAX_VALUE\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Values larger than MAX_VALUE are represented as Infinity and will lose their actual value.

Because MAX_VALUE is a static property of Number, you always use it as Number.MAX_VALUE, rather than as a property of a number value.

\n

Examples

\n

Using MAX_VALUE

\n
\n

The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE, the func1 function is called; otherwise, the func2 function is called.

\n

js

\n
if (num1 * num2 <= Number.MAX_VALUE) {\n  func1();\n} else {\n  func2();\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.max_value
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
MAX_VALUE11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE\n

\n
\n", + "global_objects/bigint/bigint": "

BigInt() constructor

The BigInt() function returns primitive values of type BigInt.

\n

Syntax

\n
\n
\n

js

\n
BigInt(value)\n
\n

Note: BigInt() can only be called without new. Attempting to construct it with new throws a TypeError.

\n

Parameters

\n
value

The value to be converted to a BigInt value. It may be a string, an integer, a boolean, or another BigInt.

Return value

\n

A BigInt value. Number values must be integers and are converted to BigInts. The boolean value true becomes 1n, and false becomes 0n. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with 0b, 0o, or 0x.

Exceptions

\n
RangeError

Thrown if the parameter is a non-integral number.

TypeError

Thrown in one of the following cases:

  • The parameter cannot be converted to a primitive.
  • After conversion to a primitive, the result is undefined, null, symbol.
SyntaxError

Thrown if the parameter is a string that cannot be parsed as a BigInt.

Examples

\n

Using BigInt() to convert a number to a BigInt

\n
\n

BigInt() is the only case where a number can be converted to a BigInt without throwing, because it's very explicit. However, only integers are allowed.

\n

js

\n
BigInt(123); // 123n\nBigInt(123.3); // RangeError: The number 123.3 cannot be converted to a BigInt because it is not an integer\n
\n
\n

Using string values

\n
\n

js

\n
BigInt(\"123\"); // 123n\nBigInt(\"0b10101\"); // 21n, which is 10101 in binary\nBigInt(\"0o123\"); // 83n, which is 123 in octal\nBigInt(\"0x123\"); // 291n, which is 123 in hexadecimal\nBigInt(\"  123  \"); // 123n, leading and trailing whitespaces are allowed\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigInt677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt\n

\n
\n", + "global_objects/number/parsefloat": "

Number.parseFloat()

The Number.parseFloat() static method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.parseFloat(string)\n
\n

Parameters

\n
string

The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

Return value

\n
\n

A floating point number parsed from the given string.

Or NaN when the first non-whitespace character cannot be converted to a number.

\n

Examples

\n

Number.parseFloat vs. parseFloat

\n
\n

This method has the same functionality as the global parseFloat() function:

\n

js

\n
Number.parseFloat === parseFloat; // true\n
\n

Its purpose is modularization of globals.

See parseFloat() for more detail and examples.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.parsefloat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parseFloat341225No2193734252192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat\n

\n
\n", + "global_objects/number/parseint": "

Number.parseInt()

The Number.parseInt() static method parses a string argument and returns an integer of the specified radix or base.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.parseInt(string)\nNumber.parseInt(string, radix)\n
\n

Parameters

\n
string

The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

\nradix Optional\n

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string.

If radix is undefined or 0, it is assumed to be 10 except when the number begins with the code unit pairs 0x or 0X, in which case a radix of 16 is assumed.

Return value

\n
\n

An integer parsed from the given string.

If the radix is smaller than 2 or bigger than 36, or the first non-whitespace character cannot be converted to a number, NaN is returned.

\n

Examples

\n

Number.parseInt vs. parseInt

\n
\n

This method has the same functionality as the global parseInt() function:

\n

js

\n
Number.parseInt === parseInt; // true\n
\n

Its purpose is modularization of globals. Please see parseInt() for more detail and examples.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.parseint
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parseInt341225No2193734252192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt\n

\n
\n", + "global_objects/number/tofixed": "

Number.prototype.toFixed()

The toFixed() method of Number values formats this number using fixed-point notation.

\n

Try it

\n

Syntax

\n
\n

js

\n
toFixed()\ntoFixed(digits)\n
\n

Parameters

\n
\ndigits Optional\n

The number of digits to appear after the decimal point; should be a value between 0 and 100, inclusive. If this argument is omitted, it is treated as 0.

Return value

\n

A string representing the given number using fixed-point notation.

Exceptions

\n
RangeError

Thrown if digits is not between 0 and 100 (inclusive).

TypeError

Thrown if this method is invoked on an object that is not a Number.

Description

\n
\n

The toFixed() method returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

If the absolute value of numObj is greater or equal to 1021, this method uses the same algorithm as Number.prototype.toString() and returns a string in exponential notation. toFixed() returns \"Infinity\", \"NaN\", or \"-Infinity\" if the value of numObj is non-finite.

The output of toFixed() may be more precise than toString() for some values, because toString() only prints enough significant digits to distinguish the number from adjacent number values. For example:

\n

js

\n
(1000000000000000128).toString(); // '1000000000000000100'\n(1000000000000000128).toFixed(0); // '1000000000000000128'\n
\n

However, choosing a digits precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example:

\n

js

\n
(0.3).toFixed(50); // '0.29999999999999998889776975374843459576368331909180'\n
\n
\n

Examples

\n

Using toFixed()

\n
\n

js

\n
const numObj = 12345.6789;\n\nnumObj.toFixed(); // '12346'; rounding, no fractional part\nnumObj.toFixed(1); // '12345.7'; it rounds up\nnumObj.toFixed(6); // '12345.678900'; additional zeros\n(1.23e20).toFixed(2); // '123000000000000000000.00'\n(1.23e-10).toFixed(2); // '0.00'\n(2.34).toFixed(1); // '2.3'\n(2.35).toFixed(1); // '2.4'; it rounds up\n(2.55).toFixed(1); // '2.5'\n// it rounds down as it can't be represented exactly by a float and the\n// closest representable float is lower\n(2.449999999999999999).toFixed(1); // '2.5'\n// it rounds up as it's less than Number.EPSILON away from 2.45.\n// This literal actually encodes the same number value as 2.45\n\n(6.02 * 10 ** 23).toFixed(50); // 6.019999999999999e+23; large numbers still use exponential notation\n
\n

Using toFixed() with negative numbers

\n
\n

Because member access has higher precedence than unary minus, you need to group the negative number expression to get a string.

\n

js

\n
-2.34.toFixed(1); // -2.3, a number\n(-2.34).toFixed(1); // '-2.3'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.tofixed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toFixed11215.5724.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed\n

\n
\n", + "global_objects/math/trunc": "

Math.trunc()

The Math.trunc() static method returns the integer part of a number by removing any fractional digits.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.trunc(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The integer part of x.

Description

\n
\n

Unlike the other three Math methods: Math.floor(), Math.ceil() and Math.round(), the way Math.trunc() works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.

Because trunc() is a static method of Math, you always use it as Math.trunc(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.trunc()

\n
\n

js

\n
Math.trunc(-Infinity); // -Infinity\nMath.trunc(\"-1.123\"); // -1\nMath.trunc(-0.123); // -0\nMath.trunc(-0); // -0\nMath.trunc(0); // 0\nMath.trunc(0.123); // 0\nMath.trunc(13.37); // 13\nMath.trunc(42.84); // 42\nMath.trunc(Infinity); // Infinity\n
\n

Using bitwise no-ops to truncate numbers

\n
\n

Warning: This is not a polyfill for Math.trunc() because of non-negligible edge cases.

Bitwise operations convert their operands to 32-bit integers, which people have historically taken advantage of to truncate float-point numbers. Common techniques include:

\n

js

\n
const original = 3.14;\nconst truncated1 = ~~original; // Double negation\nconst truncated2 = original & -1; // Bitwise AND with -1\nconst truncated3 = original | 0; // Bitwise OR with 0\nconst truncated4 = original ^ 0; // Bitwise XOR with 0\nconst truncated5 = original >> 0; // Bitwise shifting by 0\n
\n

Beware that this is essentially toInt32, which is not the same as Math.trunc. When the value does not satisfy -231 - 1 < value < 231 (-2147483649 < value < 2147483648), the conversion would overflow.

\n

js

\n
const a = ~~2147483648; // -2147483648\nconst b = ~~-2147483649; // 2147483647\nconst c = ~~4294967296; // 0\n
\n

Only use ~~ as a substitution for Math.trunc() when you are confident that the range of input falls within the range of 32-bit integers.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.trunc
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
trunc381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc\n

\n
\n", + "global_objects/number/tostring": "

Number.prototype.toString()

The toString() method of Number values returns a string representing this number value.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\ntoString(radix)\n
\n

Parameters

\n
\nradix Optional\n

An integer in the range 2 through 36 specifying the base to use for representing the number value. Defaults to 10.

Return value

\n

A string representing the specified number value.

Exceptions

\n
RangeError

Thrown if radix is less than 2 or greater than 36.

Description

\n
\n

The Number object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For Number values, the toString method returns a string representation of the value in the specified radix.

For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a through f are used.

If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a - sign, not the two's complement of the number value.

Both 0 and -0 have \"0\" as their string representation. Infinity returns \"Infinity\" and NaN returns \"NaN\".

If the number is not a whole number, the decimal point . is used to separate the decimal places. Scientific notation is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent.

\n

js

\n
console.log((10 ** 21.5).toString()); // \"3.1622776601683794e+21\"\nconsole.log((10 ** 21.5).toString(8)); // \"526665530627250154000000\"\n
\n

The toString() method requires its this value to be a Number primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to number values.

Because Number doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a Number object is used in a context expecting a string, such as in a template literal. However, Number primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

\n

js

\n
Number.prototype.toString = () => \"Overridden\";\nconsole.log(`${1}`); // \"1\"\nconsole.log(`${new Number(1)}`); // \"Overridden\"\n
\n
\n

Examples

\n

Using toString()

\n
\n

js

\n
const count = 10;\nconsole.log(count.toString()); // \"10\"\n\nconsole.log((17).toString()); // \"17\"\nconsole.log((17.2).toString()); // \"17.2\"\n\nconst x = 6;\nconsole.log(x.toString(2)); // \"110\"\nconsole.log((254).toString(16)); // \"fe\"\nconsole.log((-10).toString(2)); // \"-1010\"\nconsole.log((-0xff).toString(2)); // \"-11111111\"\n
\n

Converting radix of number strings

\n
\n

If you have a string representing a number in a non-decimal radix, you can use parseInt() and toString() to convert it to a different radix.

\n

js

\n
const hex = \"CAFEBABE\";\nconst bin = parseInt(hex, 16).toString(2); // \"11001010111111101011101010111110\"\n
\n

Beware of loss of precision: if the original number string is too large (larger than Number.MAX_SAFE_INTEGER, for example), you should use a BigInt instead. However, the BigInt constructor only has support for strings representing number literals (i.e. strings starting with 0b, 0o, 0x). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString\n

\n
\n", + "global_objects/number/issafeinteger": "

Number.isSafeInteger()

The Number.isSafeInteger() static method determines whether the provided value is a number that is a safe integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.isSafeInteger(testValue)\n
\n

Parameters

\n
testValue

The value to be tested for being a safe integer.

Return value

\n

The boolean value true if the given value is a number that is a safe integer. Otherwise false.

Description

\n
\n

The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that:

For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is not a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding.

Handling values larger or smaller than ~9 quadrillion with full precision requires using an arbitrary precision arithmetic library. See What Every Programmer Needs to Know about Floating Point Arithmetic for more information on floating point representations of numbers.

For larger integers, consider using the BigInt type.

\n

Examples

\n

Using isSafeInteger()

\n
\n

js

\n
Number.isSafeInteger(3); // true\nNumber.isSafeInteger(2 ** 53); // false\nNumber.isSafeInteger(2 ** 53 - 1); // true\nNumber.isSafeInteger(NaN); // false\nNumber.isSafeInteger(Infinity); // false\nNumber.isSafeInteger(\"3\"); // false\nNumber.isSafeInteger(3.1); // false\nNumber.isSafeInteger(3.0); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.issafeinteger
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isSafeInteger341232No2193734322192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger\n

\n
\n", + "global_objects/object/valueof": "

Object.prototype.valueOf()

The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n
\n

The this value, converted to an object.

Note: In order for valueOf to be useful during type conversion, it must return a primitive. Because all primitive types have their own valueOf() methods, calling aPrimitiveValue.valueOf() generally does not invoke Object.prototype.valueOf().

\n

Description

\n
\n

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

This method is called in priority by numeric conversion and primitive conversion, but string conversion calls toString() in priority, and toString() is very likely to return a string value (even for the Object.prototype.toString() base implementation), so valueOf() is usually not called in this case.

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the toString() method. The Object.prototype.valueOf() base implementation is deliberately useless: by returning an object, its return value will never be used by any primitive conversion algorithm. Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override valueOf() to call a custom method, so that your custom object can be converted to a primitive value. Generally, valueOf() is used to return a value that is most meaningful for the object — unlike toString(), it does not need to be a string. Alternatively, you can add a @@toPrimitive method, which allows even more control over the conversion process, and will always be preferred over valueOf or toString for any type conversion.

\n

Examples

\n

Using valueOf()

\n
\n

The base valueOf() method returns the this value itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.

\n

js

\n
const obj = { foo: 1 };\nconsole.log(obj.valueOf() === obj); // true\n\nconsole.log(Object.prototype.valueOf.call(\"primitive\"));\n// [String: 'primitive'] (a wrapper object)\n
\n
\n

Overriding valueOf for custom objects

\n
\n

You can create a function to be called in place of the default valueOf method. Your function should take no arguments, since it won't be passed any when called during type conversion.

For example, you can add a valueOf method to your custom class Box.

\n

js

\n
class Box {\n  #value;\n  constructor(value) {\n    this.#value = value;\n  }\n  valueOf() {\n    return this.#value;\n  }\n}\n
\n

With the preceding code in place, any time an object of type Box is used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.

\n

js

\n
const box = new Box(123);\nconsole.log(box + 456); // 579\nconsole.log(box == 123); // true\n
\n

An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows:

\n

js

\n
box.valueOf();\n
\n
\n

Using unary plus on objects

\n
\n

Unary plus performs number coercion on its operand, which, for most objects without @@toPrimitive, means calling its valueOf(). However, if the object doesn't have a custom valueOf() method, the base implementation will cause valueOf() to be ignored and the return value of toString() to be used instead.

\n

js

\n
+new Date(); // the current timestamp; same as new Date().getTime()\n+{}; // NaN (toString() returns \"[object Object]\")\n+[]; // 0 (toString() returns an empty string list)\n+[1]; // 1 (toString() returns \"1\")\n+[1, 2]; // NaN (toString() returns \"1,2\")\n+new Set([1]); // NaN (toString() returns \"[object Set]\")\n+{ valueOf: () => 42 }; // 42\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf\n

\n
\n", + "global_objects/string/towellformed": "

String.prototype.toWellFormed()

The toWellFormed() method of String values returns a string where all lone surrogates of this string are replaced with the Unicode replacement character U+FFFD.

\n

Syntax

\n
\n

js

\n
toWellFormed()\n
\n

Parameters

\n

None.

Return value

\n

A new string that is a copy of this string, with all lone surrogates replaced with the Unicode replacement character U+FFFD. If str is well formed, a new string is still returned (essentially a copy of str).

Description

\n
\n

Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of surrogate pairs, which is introduced in detail in the UTF-16 characters, Unicode code points, and grapheme clusters section.

toWellFormed() iterates through the code units of this string, and replaces any lone surrogates with the Unicode replacement character U+FFFD . This ensures that the returned string is well-formed and can be used in functions that expect well-formed strings, such as encodeURI. Compared to a custom implementation, toWellFormed() is more efficient, as engines can directly access the internal representation of strings.

When ill-formed strings are used in certain contexts, such as TextEncoder, they are automatically converted to well-formed strings using the same replacement character. When lone surrogates are rendered, they are also rendered as the replacement character (a diamond with a question mark inside).

\n

Examples

\n

Using toWellFormed()

\n
\n

js

\n
const strings = [\n  // Lone leading surrogate\n  \"ab\\uD800\",\n  \"ab\\uD800c\",\n  // Lone trailing surrogate\n  \"\\uDFFFab\",\n  \"c\\uDFFFab\",\n  // Well-formed\n  \"abc\",\n  \"ab\\uD83D\\uDE04c\",\n];\n\nfor (const str of strings) {\n  console.log(str.toWellFormed());\n}\n// Logs:\n// \"ab�\"\n// \"ab�c\"\n// \"�ab\"\n// \"c�ab\"\n// \"abc\"\n// \"ab😄c\"\n
\n

Avoiding errors in encodeURI()

\n
\n

encodeURI throws an error if the string passed is not well-formed. This can be avoided by using toWellFormed() to convert the string to a well-formed string first.

\n

js

\n
const illFormed = \"https://example.com/search?q=\\uD800\";\n\ntry {\n  encodeURI(illFormed);\n} catch (e) {\n  console.log(e); // URIError: URI malformed\n}\n\nconsole.log(encodeURI(illFormed.toWellFormed())); // \"https://example.com/search?q=%EF%BF%BD\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.towellformed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toWellFormed111111119No9716.4111111119No16.422.01.3220.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toWellFormed\n

\n
\n", + "global_objects/string/iswellformed": "

String.prototype.isWellFormed()

The isWellFormed() method of String values returns a boolean indicating whether this string contains any lone surrogates.

\n

Syntax

\n
\n

js

\n
isWellFormed()\n
\n

Parameters

\n

None.

Return value

\n

Returns true if this string does not contain any lone surrogates, false otherwise.

Description

\n
\n

Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of surrogate pairs, which is introduced in detail in the UTF-16 characters, Unicode code points, and grapheme clusters section.

isWellFormed() allows you to test whether a string is well-formed (i.e. does not contain any lone surrogates). Compared to a custom implementation, isWellFormed() is more efficient, as engines can directly access the internal representation of strings. If you need to convert a string to a well-formed string, use the toWellFormed() method. isWellFormed() allows you to handle ill-formed strings differently from well-formed strings, such as throwing an error or marking it as invalid.

\n

Examples

\n

Using isWellFormed()

\n
\n

js

\n
const strings = [\n  // Lone leading surrogate\n  \"ab\\uD800\",\n  \"ab\\uD800c\",\n  // Lone trailing surrogate\n  \"\\uDFFFab\",\n  \"c\\uDFFFab\",\n  // Well-formed\n  \"abc\",\n  \"ab\\uD83D\\uDE04c\",\n];\n\nfor (const str of strings) {\n  console.log(str.isWellFormed());\n}\n// Logs:\n// false\n// false\n// false\n// false\n// true\n// true\n
\n

Avoiding errors in encodeURI()

\n
\n

encodeURI throws an error if the string passed is not well-formed. This can be avoided by using isWellFormed() to test the string before passing it to encodeURI().

\n

js

\n
const illFormed = \"https://example.com/search?q=\\uD800\";\n\ntry {\n  encodeURI(illFormed);\n} catch (e) {\n  console.log(e); // URIError: URI malformed\n}\n\nif (illFormed.isWellFormed()) {\n  console.log(encodeURI(illFormed));\n} else {\n  console.warn(\"Ill-formed strings encountered.\"); // Ill-formed strings encountered.\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.iswellformed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isWellFormed111111119No9716.4111111119No16.422.01.3220.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/isWellFormed\n

\n
\n", + "global_objects/object/object": "

Object() constructor

The Object() constructor turns the input into an object. Its behavior depends on the input's type.

\n

Syntax

\n
\n
\n

js

\n
new Object()\nnew Object(value)\n\nObject()\nObject(value)\n
\n

Note: Object() can be called with or without new, but sometimes with different effects. See Return value.

\n

Parameters

\n
\nvalue Optional\n

Any value.

Return value

\n
\n

When the Object() constructor itself is called or constructed, its return value is an object:

When Object() is constructed but new.target is not the Object constructor itself, the behavior is slightly different — it initializes a new object with new.target.prototype as its prototype. Any argument value is ignored. This may happen, for example, when Object() is implicitly called via super() in the constructor of a class that extends Object. In this case, even if you pass a number to super(), the this value inside the constructor does not become a Number instance.

\n

Examples

\n

Creating a new Object

\n
\n

js

\n
const o = new Object();\no.foo = 42;\n\nconsole.log(o);\n// { foo: 42 }\n
\n

Using Object given undefined and null types

\n
\n

The following examples store an empty Object object in o:

\n

js

\n
const o = new Object();\n
\n
\n

js

\n
const o = new Object(undefined);\n
\n
\n

js

\n
const o = new Object(null);\n
\n
\n

Obtaining wrapper objects for BigInt and Symbol

\n
\n

The BigInt() and Symbol() constructors throw an error when called with new, to prevent the common mistake of creating a wrapper object instead of the primitive value. The only way to create a wrapper object for these types is to call Object() with them:

\n

js

\n
const numberObj = new Number(1);\nconsole.log(typeof numberObj); // \"object\"\n\nconst bigintObj = Object(1n);\nconsole.log(typeof bigintObj); // \"object\"\n\nconst symbolObj = Object(Symbol(\"foo\"));\nconsole.log(typeof symbolObj); // \"object\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Object11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object\n

\n
\n", + "global_objects/object/setprototypeof": "

Object.setPrototypeOf()

\n

The Object.setPrototypeOf() static method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. You can read more in JavaScript engine fundamentals: optimizing prototypes.

Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Object.setPrototypeOf(obj, prototype)\n
\n

Parameters

\n
obj

The object which is to have its prototype set.

prototype

The object's new prototype (an object or null).

Return value

\n

The specified object.

Exceptions

\n
TypeError

Thrown in one of the following cases:

  • The obj parameter is undefined or null.
  • The obj parameter is non-extensible, or it's an immutable prototype exotic object, such as Object.prototype or window. However, the error is not thrown if the new prototype is the same value as the original prototype of obj.
  • The prototype parameter is not an object or null.

Description

\n
\n

Object.setPrototypeOf() is generally considered the proper way to set the prototype of an object. You should always use it in favor of the deprecated Object.prototype.__proto__ accessor.

If the obj parameter is not an object (e.g. number, string, etc.), this method does nothing — without coercing it to an object or attempting to set its prototype — and directly returns obj as a primitive value. If prototype is the same value as the prototype of obj, then obj is directly returned, without causing a TypeError even when obj has immutable prototype.

For security concerns, there are certain built-in objects that are designed to have an immutable prototype. This prevents prototype pollution attacks, especially proxy-related ones. The core language only specifies Object.prototype as an immutable prototype exotic object, whose prototype is always null. In browsers, window and location are two other very common examples.

\n

js

\n
Object.isExtensible(Object.prototype); // true; you can add more properties\nObject.setPrototypeOf(Object.prototype, {}); // TypeError: Immutable prototype object '#<Object>' cannot have their prototype set\nObject.setPrototypeOf(Object.prototype, null); // No error; the prototype of `Object.prototype` is already `null`\n
\n
\n

Examples

\n

Pseudoclassical inheritance using Object.setPrototypeOf()

\n
\n

Inheritance in JS using classes.

\n

js

\n
class Human {}\nclass SuperHero extends Human {}\n\nconst superMan = new SuperHero();\n
\n

However, if we want to implement subclasses without using class, we can do the following:

\n

js

\n
function Human(name, level) {\n  this.name = name;\n  this.level = level;\n}\n\nfunction SuperHero(name, level) {\n  Human.call(this, name, level);\n}\n\nObject.setPrototypeOf(SuperHero.prototype, Human.prototype);\n\n// Set the `[[Prototype]]` of `SuperHero.prototype`\n// to `Human.prototype`\n// To set the prototypal inheritance chain\n\nHuman.prototype.speak = function () {\n  return `${this.name} says hello.`;\n};\n\nSuperHero.prototype.fly = function () {\n  return `${this.name} is flying.`;\n};\n\nconst superMan = new SuperHero(\"Clark Kent\", 1);\n\nconsole.log(superMan.fly());\nconsole.log(superMan.speak());\n
\n

The similarity between classical inheritance (with classes) and pseudoclassical inheritance (with constructors' prototype property) as done above is mentioned in Inheritance chains.

Since function constructors' prototype property is writable, you can reassign it to a new object created with Object.create() to achieve the same inheritance chain as well. There are caveats to watch out when using create(), such as remembering to re-add the constructor property.

In the example below, which also uses classes, SuperHero is made to inherit from Human without using extends by using setPrototypeOf() instead.

Warning: It is not advisable to use setPrototypeOf() instead of extends due to performance and readability reasons.

\n

js

\n
class Human {}\nclass SuperHero {}\n\n// Set the instance properties\nObject.setPrototypeOf(SuperHero.prototype, Human.prototype);\n\n// Hook up the static properties\nObject.setPrototypeOf(SuperHero, Human);\n\nconst superMan = new SuperHero();\n
\n

Subclassing without extends is mentioned in ES-6 subclassing.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.setprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setPrototypeOf341231112193734312192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf\n

\n
\n", + "global_objects/object/tostring": "

Object.prototype.toString()

The toString() method of Object instances returns a string representing this object. This method is meant to be overridden by derived objects for custom type coercion logic.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

By default toString() takes no parameters. However, objects that inherit from Object may override it with their own implementations that do take parameters. For example, the Number.prototype.toString() and BigInt.prototype.toString() methods take an optional radix parameter.

Return value

\n

A string representing the object.

Description

\n
\n

JavaScript calls the toString method to convert an object to a primitive value. You rarely need to invoke the toString method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

This method is called in priority by string conversion, but numeric conversion and primitive conversion call valueOf() in priority. However, because the base valueOf() method returns an object, the toString() method is usually called in the end, unless the object overrides valueOf(). For example, +[1] returns 1, because its toString() method returns \"1\", which is then converted to a number.

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the toString() method. When you create a custom object, you can override toString() to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a @@toPrimitive method, which allows even more control over the conversion process, and will always be preferred over valueOf or toString for any type conversion.

To use the base Object.prototype.toString() with an object that has it overridden (or to invoke it on null or undefined), you need to call Function.prototype.call() or Function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisArg).

\n

js

\n
const arr = [1, 2, 3];\n\narr.toString(); // \"1,2,3\"\nObject.prototype.toString.call(arr); // \"[object Array]\"\n
\n

Object.prototype.toString() returns \"[object Type]\", where Type is the object type. If the object has a Symbol.toStringTag property whose value is a string, that value will be used as the Type. Many built-in objects, including Map and Symbol, have a Symbol.toStringTag. Some objects predating ES6 do not have Symbol.toStringTag, but have a special tag nonetheless. They include (the tag is the same as the type name given below):

The arguments object returns \"[object Arguments]\". Everything else, including user-defined classes, unless with a custom Symbol.toStringTag, will return \"[object Object]\".

Object.prototype.toString() invoked on null and undefined returns [object Null] and [object Undefined], respectively.

\n

Examples

\n

Overriding toString for custom objects

\n
\n

You can create a function to be called in place of the default toString() method. The toString() function you create should return a string value. If it returns an object and the method is called implicitly during type conversion, then its result is ignored and the value of a related method, valueOf(), is used instead, or a TypeError is thrown if none of these methods return a primitive.

The following code defines a Dog class.

\n

js

\n
class Dog {\n  constructor(name, breed, color, sex) {\n    this.name = name;\n    this.breed = breed;\n    this.color = color;\n    this.sex = sex;\n  }\n}\n
\n

If you call the toString() method, either explicitly or implicitly, on an instance of Dog, it returns the default value inherited from Object:

\n

js

\n
const theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\n\ntheDog.toString(); // \"[object Object]\"\n`${theDog}`; // \"[object Object]\"\n
\n

The following code overrides the default toString() method. This method generates a string containing the name, breed, color, and sex of the object.

\n

js

\n
class Dog {\n  constructor(name, breed, color, sex) {\n    this.name = name;\n    this.breed = breed;\n    this.color = color;\n    this.sex = sex;\n  }\n  toString() {\n    return `Dog ${this.name} is a ${this.sex}${this.color}${this.breed}`;\n  }\n}\n
\n

With the preceding code in place, any time an instance of Dog is used in a string context, JavaScript automatically calls the toString() method.

\n

js

\n
const theDog = new Dog(\"Gabby\", \"Lab\", \"chocolate\", \"female\");\n\n`${theDog}`; // \"Dog Gabby is a female chocolate Lab\"\n
\n
\n

Using toString() to detect object class

\n
\n

toString() can be used with every object and (by default) allows you to get its class.

\n

js

\n
const toString = Object.prototype.toString;\n\ntoString.call(new Date()); // [object Date]\ntoString.call(new String()); // [object String]\n// Math has its Symbol.toStringTag\ntoString.call(Math); // [object Math]\n\ntoString.call(undefined); // [object Undefined]\ntoString.call(null); // [object Null]\n
\n

Using toString() in this way is unreliable; objects can change the behavior of Object.prototype.toString() by defining a Symbol.toStringTag property, leading to unexpected results. For example:

\n

js

\n
const myDate = new Date();\nObject.prototype.toString.call(myDate); // [object Date]\n\nmyDate[Symbol.toStringTag] = \"myDate\";\nObject.prototype.toString.call(myDate); // [object myDate]\n\nDate.prototype[Symbol.toStringTag] = \"prototype polluted\";\nObject.prototype.toString.call(new Date()); // [object prototype polluted]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString\n

\n
\n", + "global_objects/object/tolocalestring": "

Object.prototype.toLocaleString()

The toLocaleString() method of Object instances returns a string representing this object. This method is meant to be overridden by derived objects for locale-specific purposes.

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\n
\n

Parameters

\n

None. However, all objects that override this method are expected to accept at most two parameters, corresponding to locales and options, such as Date.prototype.toLocaleString. The parameter positions should not be used for any other purpose.

Return value

\n

The return value of calling this.toString().

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the toLocaleString() method. Object's toLocaleString returns the result of calling this.toString().

This function is provided to give objects a generic toLocaleString method, even though not all may use it. In the core language, these built-in objects override toLocaleString to provide locale-specific formatting:

\n

Examples

\n

Using the base toLocaleString() method

\n
\n

The base toLocaleString() method simply calls toString().

\n

js

\n
const obj = {\n  toString() {\n    return \"My Object\";\n  },\n};\nconsole.log(obj.toLocaleString()); // \"My Object\"\n
\n
\n

Array toLocaleString() override

\n
\n

Array.prototype.toLocaleString() is used to print array values as a string by invoking each element's toLocaleString() method and joining the results with a locale-specific separator. For example:

\n

js

\n
const testArray = [4, 7, 10];\n\nconst euroPrices = testArray.toLocaleString(\"fr\", {\n  style: \"currency\",\n  currency: \"EUR\",\n});\n// \"4,00 €,7,00 €,10,00 €\"\n
\n
\n

Date toLocaleString() override

\n
\n

Date.prototype.toLocaleString() is used to print out date displays more suitable for specific locales. For example:

\n

js

\n
const testDate = new Date();\n// \"Fri May 29 2020 18:04:24 GMT+0100 (British Summer Time)\"\n\nconst deDate = testDate.toLocaleString(\"de\");\n// \"29.5.2020, 18:04:24\"\n\nconst frDate = testDate.toLocaleString(\"fr\");\n// \"29/05/2020, 18:04:24\"\n
\n
\n

Number toLocaleString() override

\n
\n

Number.prototype.toLocaleString() is used to print out number displays more suitable for specific locales, e.g. with the correct separators. For example:

\n

js

\n
const testNumber = 2901234564;\n// \"2901234564\"\n\nconst deNumber = testNumber.toLocaleString(\"de\");\n// \"2.901.234.564\"\n\nconst frNumber = testNumber.toLocaleString(\"fr\");\n// \"2 901 234 564\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString\n

\n
\n", + "global_objects/object/__definegetter__": "

Object.prototype.__defineGetter__()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: This feature is deprecated in favor of defining getters using the object initializer syntax or the Object.defineProperty() API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The __defineGetter__() method of Object instances binds an object's property to a function to be called when that property is looked up.

\n
\n

Syntax

\n
\n

js

\n
__defineGetter__(prop, func)\n
\n

Parameters

\n
prop

A string containing the name of the property that the getter func is bound to.

func

A function to be bound to a lookup of the specified property.

Return value

\n

None (undefined).

Exceptions

\n
TypeError

Thrown if func is not a function.

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the __defineGetter__() method. This method allows a getter to be defined on a pre-existing object. This is equivalent to Object.defineProperty(obj, prop, { get: func, configurable: true, enumerable: true }), which means the property is enumerable and configurable, and any existing setter, if present, is preserved.

__defineGetter__() is defined in the spec as \"normative optional\", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements __defineGetter__(), it also needs to implement the __lookupGetter__(), __lookupSetter__(), and __defineSetter__() methods.

\n

Examples

\n

Using __defineGetter__()

\n
\n

js

\n
const o = {};\no.__defineGetter__(\"gimmeFive\", function () {\n  return 5;\n});\nconsole.log(o.gimmeFive); // 5\n
\n

Defining a getter property in standard ways

\n
\n

You can use the get syntax to define a getter when the object is first initialized.

\n

js

\n
const o = {\n  get gimmeFive() {\n    return 5;\n  },\n};\nconsole.log(o.gimmeFive); // 5\n
\n

You may also use Object.defineProperty() to define a getter on an object after it's been created. Compared to __defineGetter__(), this method allows you to control the getter's enumerability and configurability, as well as defining symbol properties. The Object.defineProperty() method also works with null-prototype objects, which don't inherit from Object.prototype and therefore don't have the __defineGetter__() method.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"gimmeFive\", {\n  get() {\n    return 5;\n  },\n  configurable: true,\n  enumerable: true,\n});\nconsole.log(o.gimmeFive); // 5\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.__defineGetter__
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
__defineGetter__112
1Starting with Firefox 48, this method can no longer be called at the global scope without any object. A TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case.
119.534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__\n

\n
\n", + "global_objects/object/__definesetter__": "

Object.prototype.__defineSetter__()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: This feature is deprecated in favor of defining setters using the object initializer syntax or the Object.defineProperty() API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The __defineSetter__() method of Object instances binds an object's property to a function to be called when an attempt is made to set that property.

\n
\n

Syntax

\n
\n

js

\n
__defineSetter__(prop, func)\n
\n

Parameters

\n
prop

A string containing the name of the property that the setter func is bound to.

func

A function to be called when there is an attempt to set the specified property. This function receives the following parameter:

val

The value attempted to be assigned to prop.

Return value

\n

None (undefined).

Exceptions

\n
TypeError

Thrown if func is not a function.

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the __defineSetter__() method. This method allows a setter to be defined on a pre-existing object. This is equivalent to Object.defineProperty(obj, prop, { set: func, configurable: true, enumerable: true }), which means the property is enumerable and configurable, and any existing getter, if present, is preserved.

__defineSetter__() is defined in the spec as \"normative optional\", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements __defineSetter__(), it also needs to implement the __lookupGetter__(), __lookupSetter__(), and __defineGetter__() methods.

\n

Examples

\n

Using __defineSetter__()

\n
\n

js

\n
const o = {};\no.__defineSetter__(\"value\", function (val) {\n  this.anotherValue = val;\n});\no.value = 5;\nconsole.log(o.value); // undefined\nconsole.log(o.anotherValue); // 5\n
\n

Defining a setter property in standard ways

\n
\n

You can use the set syntax to define a setter when the object is first initialized.

\n

js

\n
const o = {\n  set value(val) {\n    this.anotherValue = val;\n  },\n};\no.value = 5;\nconsole.log(o.value); // undefined\nconsole.log(o.anotherValue); // 5\n
\n

You may also use Object.defineProperty() to define a setter on an object after it's been created. Compared to __defineSetter__(), this method allows you to control the setter's enumerability and configurability, as well as defining symbol properties. The Object.defineProperty() method also works with null-prototype objects, which don't inherit from Object.prototype and therefore don't have the __defineSetter__() method.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"value\", {\n  set(val) {\n    this.anotherValue = val;\n  },\n  configurable: true,\n  enumerable: true,\n});\no.value = 5;\nconsole.log(o.value); // undefined\nconsole.log(o.anotherValue); // 5\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.__defineSetter__
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
__defineSetter__112
1Starting with Firefox 48, this method can no longer be called at the global scope without any object. A TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case.
119.534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__\n

\n
\n", + "global_objects/object/__lookupgetter__": "

Object.prototype.__lookupGetter__()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: This feature is deprecated in favor of the Object.getOwnPropertyDescriptor() API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The __lookupGetter__() method of Object instances returns the function bound as a getter to the specified property.

\n
\n

Syntax

\n
\n

js

\n
__lookupGetter__(prop)\n
\n

Parameters

\n
prop

A string containing the name of the property whose getter should be returned.

Return value

\n

The function bound as a getter to the specified property. Returns undefined if no such property is found, or the property is a data property.

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the __lookupGetter__() method. If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupGetter__() can be used to obtain a reference to the getter function.

__lookupGetter__() walks up the prototype chain to find the specified property. If any object along the prototype chain has the specified own property, the get attribute of the property descriptor for that property is returned. If that property is a data property, undefined is returned. If the property is not found along the entire prototype chain, undefined is also returned.

__lookupGetter__() is defined in the spec as \"normative optional\", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements __lookupGetter__(), it also needs to implement the __lookupSetter__(), __defineGetter__(), and __defineSetter__() methods.

\n

Examples

\n

Using __lookupGetter__()

\n
\n

js

\n
const obj = {\n  get foo() {\n    return Math.random() > 0.5 ? \"foo\" : \"bar\";\n  },\n};\n\nobj.__lookupGetter__(\"foo\");\n// [Function: get foo]\n
\n

Looking up a property's getter in the standard way

\n
\n

You should use the Object.getOwnPropertyDescriptor() API to look up a property's getter. Compared to __lookupGetter__(), this method allows looking up symbol properties. The Object.getOwnPropertyDescriptor() method also works with null-prototype objects, which don't inherit from Object.prototype and therefore don't have the __lookupGetter__() method. If __lookupGetter__()'s behavior of walking up the prototype chain is important, you may implement it yourself with Object.getPrototypeOf().

\n

js

\n
const obj = {\n  get foo() {\n    return Math.random() > 0.5 ? \"foo\" : \"bar\";\n  },\n};\n\nObject.getOwnPropertyDescriptor(obj, \"foo\").get;\n// [Function: get foo]\n
\n
\n

js

\n
const obj2 = {\n  __proto__: {\n    get foo() {\n      return Math.random() > 0.5 ? \"foo\" : \"bar\";\n    },\n  },\n};\n\nfunction findGetter(obj, prop) {\n  while (obj) {\n    const desc = Object.getOwnPropertyDescriptor(obj, prop);\n    if (desc) {\n      return desc.get;\n    }\n    obj = Object.getPrototypeOf(obj);\n  }\n}\n\nconsole.log(findGetter(obj2, \"foo\")); // [Function: get foo]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.__lookupGetter__
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
__lookupGetter__1121119.534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__\n

\n
\n", + "global_objects/object/__lookupsetter__": "

Object.prototype.__lookupSetter__()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: This feature is deprecated in favor of the Object.getOwnPropertyDescriptor() API. This method's behavior is only specified for web compatibility, and is not required to be implemented in any platform. It may not work everywhere.

The __lookupSetter__() method of Object instances returns the function bound as a setter to the specified property.

\n
\n

Syntax

\n
\n

js

\n
__lookupSetter__(prop)\n
\n

Parameters

\n
prop

A string containing the name of the property whose setter should be returned.

Return value

\n

The function bound as a setter to the specified property. Returns undefined if no such property is found, or the property is a data property.

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the __lookupSetter__() method. If a setter has been defined for an object's property, it's not possible to reference the setter function through that property, because that property only calls the function when it's being set. __lookupSetter__() can be used to obtain a reference to the setter function.

__lookupSetter__() walks up the prototype chain to find the specified property. If any object along the prototype chain has the specified own property, the set attribute of the property descriptor for that property is returned. If that property is a data property, undefined is returned. If the property is not found along the entire prototype chain, undefined is also returned.

__lookupSetter__() is defined in the spec as \"normative optional\", which means no implementation is required to implement this. However, all major browsers implement it, and due to its continued usage, it's unlikely to be removed. If a browser implements __lookupSetter__(), it also needs to implement the __lookupGetter__(), __defineGetter__(), and __defineSetter__() methods.

\n

Examples

\n

Using __lookupSetter__()

\n
\n

js

\n
const obj = {\n  set foo(value) {\n    this.bar = value;\n  },\n};\n\nobj.__lookupSetter__(\"foo\");\n// [Function: set foo]\n
\n

Looking up a property's setter in the standard way

\n
\n

You should use the Object.getOwnPropertyDescriptor() API to look up a property's setter. Compared to __lookupSetter__(), this method allows looking up symbol properties. The Object.getOwnPropertyDescriptor() method also works with null-prototype objects, which don't inherit from Object.prototype and therefore don't have the __lookupSetter__() method. If __lookupSetter__()'s behavior of walking up the prototype chain is important, you may implement it yourself with Object.getPrototypeOf().

\n

js

\n
const obj = {\n  set foo(value) {\n    this.bar = value;\n  },\n};\n\nObject.getOwnPropertyDescriptor(obj, \"foo\").set;\n// [Function: set foo]\n
\n
\n

js

\n
const obj2 = {\n  __proto__: {\n    set foo(value) {\n      this.bar = value;\n    },\n  },\n};\n\nfunction findSetter(obj, prop) {\n  while (obj) {\n    const desc = Object.getOwnPropertyDescriptor(obj, prop);\n    if (desc) {\n      return desc.set;\n    }\n    obj = Object.getPrototypeOf(obj);\n  }\n}\n\nconsole.log(findSetter(obj2, \"foo\")); // [Function: set foo]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.__lookupSetter__
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
__lookupSetter__1121119.534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__\n

\n
\n", + "global_objects/object/defineproperty": "

Object.defineProperty()

The Object.defineProperty() static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.defineProperty(obj, prop, descriptor)\n
\n

Parameters

\n
obj

The object on which to define the property.

prop

A string or Symbol specifying the key of the property to be defined or modified.

descriptor

The descriptor for the property being defined or modified.

Return value

\n

The object that was passed to the function, with the specified property added or modified.

Description

\n
\n

Object.defineProperty() allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in, Object.keys(), etc.), whose values may be changed and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using Object.defineProperty() are not writable, not enumerable, and not configurable. In addition, Object.defineProperty() uses the [[DefineOwnProperty]] internal method, instead of [[Set]], so it does not invoke setters, even when the property is already present.

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property with a value that may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

Both data and accessor descriptors are objects. They share the following optional keys (please note: the defaults mentioned here are in the case of defining properties using Object.defineProperty()):

configurable

when this is set to false,

  • the type of this property cannot be changed between data property and accessor property, and
  • the property may not be deleted, and
  • other attributes of its descriptor cannot be changed (however, if it's a data descriptor with writable: true, the value can be changed, and writable can be changed to false).

false

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object. false

A data descriptor also has the following optional keys:

value

The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). Defaults to undefined.

writable

true if the value associated with the property may be changed with an assignment operator. false

An accessor descriptor also has the following optional keys:

get

A function which serves as a getter for the property, or undefined if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. Defaults to undefined.

set

A function which serves as a setter for the property, or undefined if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned. Defaults to undefined.

If a descriptor doesn't have any of the value, writable, get, and set keys, it is treated as a data descriptor. If a descriptor has both [value or writable] and [get or set] keys, an exception is thrown.

These attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or create a null-prototype object.

\n

js

\n
const obj = {};\n// 1. Using a null prototype: no inherited properties\nconst descriptor = Object.create(null);\ndescriptor.value = \"static\";\n\n// not enumerable, not configurable, not writable as defaults\nObject.defineProperty(obj, \"key\", descriptor);\n\n// 2. Being explicit by using a throw-away object literal with all attributes present\nObject.defineProperty(obj, \"key2\", {\n  enumerable: false,\n  configurable: false,\n  writable: false,\n  value: \"static\",\n});\n\n// 3. Recycling same object\nfunction withValue(value) {\n  const d =\n    withValue.d ||\n    (withValue.d = {\n      enumerable: false,\n      writable: false,\n      configurable: false,\n      value,\n    });\n\n  // avoiding duplicate operation for assigning value\n  if (d.value !== value) d.value = value;\n\n  return d;\n}\n// and\nObject.defineProperty(obj, \"key\", withValue(\"static\"));\n\n// if freeze is available, prevents adding or\n// removing the object prototype properties\n// (value, get, set, enumerable, writable, configurable)\n(Object.freeze || Object)(Object.prototype);\n
\n

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the property's current configuration.

If the old descriptor had its configurable attribute set to false, the property is said to be non-configurable. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with writable: true, it is possible to modify the value and change the writable attribute from true to false. A TypeError is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted), except when defining a value same as the original value on a data property.

When the current property is configurable, defining an attribute to undefined effectively deletes it. For example, if o.k is an accessor property, Object.defineProperty(o, \"k\", { set: undefined }) will remove the setter, making k only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to undefined). It is possible to toggle between data and accessor property by giving a descriptor of a different \"flavor\". For example, if the new descriptor is a data descriptor (with value or writable), the original descriptor's get and set attributes will both be dropped.

\n

Examples

\n

Creating a property

\n
\n

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor and default values for those fields are inputted.

\n

js

\n
const o = {}; // Creates a new object\n\n// Example of an object property added\n// with defineProperty with a data property descriptor\nObject.defineProperty(o, \"a\", {\n  value: 37,\n  writable: true,\n  enumerable: true,\n  configurable: true,\n});\n// 'a' property exists in the o object and its value is 37\n\n// Example of an object property added\n// with defineProperty with an accessor property descriptor\nlet bValue = 38;\nObject.defineProperty(o, \"b\", {\n  get() {\n    return bValue;\n  },\n  set(newValue) {\n    bValue = newValue;\n  },\n  enumerable: true,\n  configurable: true,\n});\no.b; // 38\n// 'b' property exists in the o object and its value is 38\n// The value of o.b is now always identical to bValue,\n// unless o.b is redefined\n\n// You cannot try to mix both:\nObject.defineProperty(o, \"conflict\", {\n  value: 0x9f91102,\n  get() {\n    return 0xdeadbeef;\n  },\n});\n// throws a TypeError: value appears\n// only in data descriptors,\n// get appears only in accessor descriptors\n
\n
\n

Modifying a property

\n
\n

When modifying an existing property, the current property configuration determines if the operator succeeds, does nothing, or throws a TypeError.

Writable attribute

When the writable property attribute is false, the property is said to be \"non-writable\". It cannot be reassigned. Trying to write to a non-writable property doesn't change it and results in an error in strict mode.

\n

js

\n
const o = {}; // Creates a new object\n\nObject.defineProperty(o, \"a\", {\n  value: 37,\n  writable: false,\n});\n\nconsole.log(o.a); // 37\no.a = 25; // No error thrown\n// (it would throw in strict mode,\n// even if the value had been the same)\nconsole.log(o.a); // 37; the assignment didn't work\n\n// strict mode\n(() => {\n  \"use strict\";\n  const o = {};\n  Object.defineProperty(o, \"b\", {\n    value: 2,\n    writable: false,\n  });\n  o.b = 3; // throws TypeError: \"b\" is read-only\n  return o.b; // returns 2 without the line above\n})();\n
\n

Enumerable attribute

The enumerable property attribute defines whether the property is considered by Object.assign() or the spread operator. For non-Symbol properties, it also defines whether it shows up in a for...in loop and Object.keys() or not. For more information, see Enumerability and ownership of properties.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"a\", {\n  value: 1,\n  enumerable: true,\n});\nObject.defineProperty(o, \"b\", {\n  value: 2,\n  enumerable: false,\n});\nObject.defineProperty(o, \"c\", {\n  value: 3,\n}); // enumerable defaults to false\no.d = 4; // enumerable defaults to true when creating a property by setting it\nObject.defineProperty(o, Symbol.for(\"e\"), {\n  value: 5,\n  enumerable: true,\n});\nObject.defineProperty(o, Symbol.for(\"f\"), {\n  value: 6,\n  enumerable: false,\n});\n\nfor (const i in o) {\n  console.log(i);\n}\n// Logs 'a' and 'd' (always in that order)\n\nObject.keys(o); // ['a', 'd']\n\no.propertyIsEnumerable(\"a\"); // true\no.propertyIsEnumerable(\"b\"); // false\no.propertyIsEnumerable(\"c\"); // false\no.propertyIsEnumerable(\"d\"); // true\no.propertyIsEnumerable(Symbol.for(\"e\")); // true\no.propertyIsEnumerable(Symbol.for(\"f\")); // false\n\nconst p = { ...o };\np.a; // 1\np.b; // undefined\np.c; // undefined\np.d; // 4\np[Symbol.for(\"e\")]; // 5\np[Symbol.for(\"f\")]; // undefined\n
\n

Configurable attribute

The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than value and writable) can be changed.

This example illustrates a non-configurable accessor property.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"a\", {\n  get() {\n    return 1;\n  },\n  configurable: false,\n});\n\nObject.defineProperty(o, \"a\", {\n  configurable: true,\n}); // throws a TypeError\nObject.defineProperty(o, \"a\", {\n  enumerable: true,\n}); // throws a TypeError\nObject.defineProperty(o, \"a\", {\n  set() {},\n}); // throws a TypeError (set was undefined previously)\nObject.defineProperty(o, \"a\", {\n  get() {\n    return 1;\n  },\n}); // throws a TypeError\n// (even though the new get does exactly the same thing)\nObject.defineProperty(o, \"a\", {\n  value: 12,\n}); // throws a TypeError\n// ('value' can be changed when 'configurable' is false, but only when the property is a writable data property)\n\nconsole.log(o.a); // 1\ndelete o.a; // Nothing happens; throws an error in strict mode\nconsole.log(o.a); // 1\n
\n

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

This example illustrates a non-configurable but writable data property. The property's value can still be changed, and writable can still be toggled from true to false.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"b\", {\n  writable: true,\n  configurable: false,\n});\nconsole.log(o.b); // undefined\nObject.defineProperty(o, \"b\", {\n  value: 1,\n}); // Even when configurable is false, because the object is writable, we may still replace the value\nconsole.log(o.b); // 1\no.b = 2; // We can change the value with assignment operators as well\nconsole.log(o.b); // 2\n// Toggle the property's writability\nObject.defineProperty(o, \"b\", {\n  writable: false,\n});\nObject.defineProperty(o, \"b\", {\n  value: 1,\n}); // TypeError: because the property is neither writable nor configurable, it cannot be modified\n// At this point, there's no way to further modify 'b'\n// or restore its writability\n
\n

This example illustrates a configurable but non-writable data property. The property's value may still be replaced with defineProperty (but not with assignment operators), and writable may be toggled.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"b\", {\n  writable: false,\n  configurable: true,\n});\nObject.defineProperty(o, \"b\", {\n  value: 1,\n}); // We can replace the value with defineProperty\nconsole.log(o.b); // 1\no.b = 2; // throws TypeError in strict mode: cannot change a non-writable property's value with assignment\n
\n

This example illustrates a non-configurable and non-writable data property. There's no way to update any attribute of the property, including its value.

\n

js

\n
const o = {};\nObject.defineProperty(o, \"b\", {\n  writable: false,\n  configurable: false,\n});\nObject.defineProperty(o, \"b\", {\n  value: 1,\n}); // TypeError: the property cannot be modified because it is neither writable nor configurable.\n
\n
\n

Adding properties and default values

\n
\n

It is important to consider the way default values of attributes are applied. There is often a difference between using property accessors to assign a value and using Object.defineProperty(), as shown in the example below.

\n

js

\n
const o = {};\n\no.a = 1;\n// is equivalent to:\nObject.defineProperty(o, \"a\", {\n  value: 1,\n  writable: true,\n  configurable: true,\n  enumerable: true,\n});\n\n// On the other hand,\nObject.defineProperty(o, \"a\", { value: 1 });\n// is equivalent to:\nObject.defineProperty(o, \"a\", {\n  value: 1,\n  writable: false,\n  configurable: false,\n  enumerable: false,\n});\n
\n
\n

Custom setters and getters

\n
\n

The example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

\n

js

\n
function Archiver() {\n  let temperature = null;\n  const archive = [];\n\n  Object.defineProperty(this, \"temperature\", {\n    get() {\n      console.log(\"get!\");\n      return temperature;\n    },\n    set(value) {\n      temperature = value;\n      archive.push({ val: temperature });\n    },\n  });\n\n  this.getArchive = () => archive;\n}\n\nconst arc = new Archiver();\narc.temperature; // 'get!'\narc.temperature = 11;\narc.temperature = 13;\narc.getArchive(); // [{ val: 11 }, { val: 13 }]\n
\n

In this example, a getter always returns the same value.

\n

js

\n
const pattern = {\n  get() {\n    return \"I always return this string, whatever you have assigned\";\n  },\n  set() {\n    this.myname = \"this is my name string\";\n  },\n};\n\nfunction TestDefineSetAndGet() {\n  Object.defineProperty(this, \"myproperty\", pattern);\n}\n\nconst instance = new TestDefineSetAndGet();\ninstance.myproperty = \"test\";\nconsole.log(instance.myproperty);\n// I always return this string, whatever you have assigned\n\nconsole.log(instance.myname); // this is my name string\n
\n
\n

Inheritance of properties

\n
\n

If an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

\n

js

\n
function MyClass() {}\n\nlet value;\nObject.defineProperty(MyClass.prototype, \"x\", {\n  get() {\n    return value;\n  },\n  set(x) {\n    value = x;\n  },\n});\n\nconst a = new MyClass();\nconst b = new MyClass();\na.x = 1;\nconsole.log(b.x); // 1\n
\n

This can be fixed by storing the value in another property. In get and set methods, this points to the object which is used to access or modify the property.

\n

js

\n
function MyClass() {}\n\nObject.defineProperty(MyClass.prototype, \"x\", {\n  get() {\n    return this.storedX;\n  },\n  set(x) {\n    this.storedX = x;\n  },\n});\n\nconst a = new MyClass();\nconst b = new MyClass();\na.x = 1;\nconsole.log(b.x); // undefined\n
\n

Unlike accessor properties, data properties are always set on the object itself, not on a prototype. However, if a non-writable data property is inherited, it is still prevented from being modified on the object.

\n

js

\n
function MyClass() {}\n\nMyClass.prototype.x = 1;\nObject.defineProperty(MyClass.prototype, \"y\", {\n  writable: false,\n  value: 1,\n});\n\nconst a = new MyClass();\na.x = 2;\nconsole.log(a.x); // 2\nconsole.log(MyClass.prototype.x); // 1\na.y = 2; // Ignored, throws in strict mode\nconsole.log(a.y); // 1\nconsole.log(MyClass.prototype.y); // 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.defineproperty
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
defineProperty51249
8In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9.
\n
11.6
5.1Also supported in Safari 5, but not on DOM objects.
4.418412
6Also supported in Safari for iOS 4.2, but not on DOM objects.
1.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\n

\n
\n", + "global_objects/object/getownpropertydescriptor": "

Object.getOwnPropertyDescriptor()

The Object.getOwnPropertyDescriptor() static method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.getOwnPropertyDescriptor(obj, prop)\n
\n

Parameters

\n
obj

The object in which to look for the property.

prop

The name or Symbol of the property whose description is to be retrieved.

Return value

\n

A property descriptor of the given property if it exists on the object, undefined otherwise.

Description

\n
\n

This method permits examination of the precise description of a property. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty().

A property descriptor is a record with some of the following attributes:

value

The value associated with the property (data descriptors only).

writable

true if and only if the value associated with the property may be changed (data descriptors only).

get

A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only).

set

A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only).

configurable

true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object.

\n

Examples

\n

Using Object.getOwnPropertyDescriptor()

\n
\n

js

\n
let o, d;\n\no = {\n  get foo() {\n    return 17;\n  },\n};\nd = Object.getOwnPropertyDescriptor(o, \"foo\");\nconsole.log(d);\n// {\n//   configurable: true,\n//   enumerable: true,\n//   get: [Function: get foo],\n//   set: undefined\n// }\n\no = { bar: 42 };\nd = Object.getOwnPropertyDescriptor(o, \"bar\");\nconsole.log(d);\n// {\n//   configurable: true,\n//   enumerable: true,\n//   value: 42,\n//   writable: true\n// }\n\no = { [Symbol.for(\"baz\")]: 73 };\nd = Object.getOwnPropertyDescriptor(o, Symbol.for(\"baz\"));\nconsole.log(d);\n// {\n//   configurable: true,\n//   enumerable: true,\n//   value: 73,\n//   writable: true\n// }\n\no = {};\nObject.defineProperty(o, \"qux\", {\n  value: 8675309,\n  writable: false,\n  enumerable: false,\n});\nd = Object.getOwnPropertyDescriptor(o, \"qux\");\nconsole.log(d);\n// {\n//   value: 8675309,\n//   writable: false,\n//   enumerable: false,\n//   configurable: false\n// }\n
\n

Non-object coercion

\n
\n

In ES5, if the first argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object first argument will be coerced to an object at first.

\n

js

\n
Object.getOwnPropertyDescriptor(\"foo\", 0);\n// TypeError: \"foo\" is not an object  // ES5 code\n\nObject.getOwnPropertyDescriptor(\"foo\", 0);\n// Object returned by ES2015 code: {\n//   configurable: false,\n//   enumerable: true,\n//   value: \"f\",\n//   writable: false\n// }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.getownpropertydescriptor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertyDescriptor51249
8In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9.
\n
1254.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor\n

\n
\n", + "global_objects/object/proto": "

Object.prototype.__proto__

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to the time spent in the obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. You can read more in JavaScript engine fundamentals: optimizing prototypes.

Note: The use of __proto__ is controversial and discouraged. Its existence and exact behavior have only been standardized as a legacy feature to ensure web compatibility, while it presents several security issues and footguns. For better support, prefer Object.getPrototypeOf()/Reflect.getPrototypeOf() and Object.setPrototypeOf()/Reflect.setPrototypeOf() instead.

The __proto__ accessor property of Object instances exposes the [[Prototype]] (either an object or null) of this object.

The __proto__ property can also be used in an object literal definition to set the object [[Prototype]] on creation, as an alternative to Object.create(). See: object initializer / literal syntax. That syntax is standard and optimized for in implementations, and quite different from Object.prototype.__proto__.

\n
\n

Syntax

\n
\n

js

\n
obj.__proto__\n
\n

Return value

\n

If used as a getter, returns the object's [[Prototype]].

Exceptions

\n
TypeError

Thrown if attempting to set the prototype of a non-extensible object or an immutable prototype exotic object, such as Object.prototype or window.

Description

\n
\n

The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal (unless you use the prototype setter syntax), this value is Object.prototype. For objects created using array literals, this value is Array.prototype. For functions, this value is Function.prototype. You can read more about the prototype chain in Inheritance and the prototype chain.

The __proto__ setter allows the [[Prototype]] of an object to be mutated. The value provided must be an object or null. Providing any other value will do nothing.

Unlike Object.getPrototypeOf() and Object.setPrototypeOf(), which are always available on Object as static properties and always reflect the [[Prototype]] internal property, the __proto__ property doesn't always exist as a property on all objects, and as a result doesn't reflect [[Prototype]] reliably.

The __proto__ property is a simple accessor property on Object.prototype consisting of a getter and setter function. A property access for __proto__ that eventually consults Object.prototype will find this property, but an access that does not consult Object.prototype will not. If some other __proto__ property is found before Object.prototype is consulted, that property will hide the one found on Object.prototype.

null-prototype objects don't inherit any property from Object.prototype, including the __proto__ accessor property, so if you try to read __proto__ on such an object, the value is always undefined regardless of the object's actual [[Prototype]], and any assignment to __proto__ would create a new property called __proto__ instead of setting the object's prototype. Furthermore, __proto__ can be redefined as an own property on any object instance through Object.defineProperty() without triggering the setter. In this case, __proto__ will no longer be an accessor for [[Prototype]]. Therefore, always prefer Object.getPrototypeOf() and Object.setPrototypeOf() for setting and getting the [[Prototype]] of an object.

\n

Examples

\n

Using __proto__

\n
\n
\n

js

\n
function Circle() {}\nconst shape = {};\nconst circle = new Circle();\n\n// Set the object prototype.\n// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.\nshape.__proto__ = circle;\n\n// Get the object prototype\nconsole.log(shape.__proto__ === Circle); // false\n
\n
\n

js

\n
const ShapeA = function () {};\nconst ShapeB = {\n  a() {\n    console.log(\"aaa\");\n  },\n};\n\nShapeA.prototype.__proto__ = ShapeB;\nconsole.log(ShapeA.prototype.__proto__); // { a: [Function: a] }\n\nconst shapeA = new ShapeA();\nshapeA.a(); // aaa\nconsole.log(ShapeA.prototype === shapeA.__proto__); // true\n
\n
\n

js

\n
const ShapeC = function () {};\nconst ShapeD = {\n  a() {\n    console.log(\"a\");\n  },\n};\n\nconst shapeC = new ShapeC();\nshapeC.__proto__ = ShapeD;\nshapeC.a(); // a\nconsole.log(ShapeC.prototype === shapeC.__proto__); // false\n
\n
\n

js

\n
function Test() {}\nTest.prototype.myName = function () {\n  console.log(\"myName\");\n};\n\nconst test = new Test();\nconsole.log(test.__proto__ === Test.prototype); // true\ntest.myName(); // myName\n\nconst obj = {};\nobj.__proto__ = Test.prototype;\nobj.myName(); // myName\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.__proto__
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
proto11211110.534.41841111.0No0.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto\n

\n
\n", + "global_objects/object/getprototypeof": "

Object.getPrototypeOf()

The Object.getPrototypeOf() static method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.getPrototypeOf(obj)\n
\n

Parameters

\n
obj

The object whose prototype is to be returned.

Return value

\n

The prototype of the given object, which may be null.

Examples

\n

Using getPrototypeOf

\n
\n

js

\n
const proto = {};\nconst obj = Object.create(proto);\nObject.getPrototypeOf(obj) === proto; // true\n
\n

Non-object coercion

\n
\n

In ES5, it will throw a TypeError exception if the obj parameter isn't an object. In ES2015, the parameter will be coerced to an Object.

\n

js

\n
Object.getPrototypeOf(\"foo\");\n// TypeError: \"foo\" is not an object (ES5 code)\nObject.getPrototypeOf(\"foo\");\n// String.prototype                  (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.getprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getPrototypeOf5123.5912.154.418412.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf\n

\n
\n", + "global_objects/object/propertyisenumerable": "

Object.prototype.propertyIsEnumerable()

The propertyIsEnumerable() method of Object instances returns a boolean indicating whether the specified property is this object's enumerable own property.

\n

Try it

\n

Syntax

\n
\n

js

\n
propertyIsEnumerable(prop)\n
\n

Parameters

\n
prop

The name of the property to test. Can be a string or a Symbol.

Return value

\n

A boolean value indicating whether the specified property is enumerable and is the object's own property.

Description

\n
\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the propertyIsEnumerable() method. This method determines if the specified property, string or symbol, is an enumerable own property of the object. If the object does not have the specified property, this method returns false.

This method is equivalent to Object.getOwnPropertyDescriptor(obj, prop)?.enumerable ?? false.

\n

Examples

\n

Using propertyIsEnumerable()

\n
\n

The following example shows the use of propertyIsEnumerable() on objects and arrays.

\n

js

\n
const o = {};\nconst a = [];\no.prop = \"is enumerable\";\na[0] = \"is enumerable\";\n\no.propertyIsEnumerable(\"prop\"); // true\na.propertyIsEnumerable(0); // true\n
\n
\n

User-defined vs. built-in objects

\n
\n

Most built-in properties are non-enumerable by default, while user-created object properties are often enumerable, unless explicitly designated otherwise.

\n

js

\n
const a = [\"is enumerable\"];\n\na.propertyIsEnumerable(0); // true\na.propertyIsEnumerable(\"length\"); // false\n\nMath.propertyIsEnumerable(\"random\"); // false\nglobalThis.propertyIsEnumerable(\"Math\"); // false\n
\n
\n

Direct vs. inherited properties

\n
\n

Only enumerable own properties cause propertyIsEnumerable() to return true, although all enumerable properties, including inherited ones, are visited by the for...in loop.

\n

js

\n
const o1 = {\n  enumerableInherited: \"is enumerable\",\n};\nObject.defineProperty(o1, \"nonEnumerableInherited\", {\n  value: \"is non-enumerable\",\n  enumerable: false,\n});\nconst o2 = {\n  // o1 is the prototype of o2\n  __proto__: o1,\n  enumerableOwn: \"is enumerable\",\n};\nObject.defineProperty(o2, \"nonEnumerableOwn\", {\n  value: \"is non-enumerable\",\n  enumerable: false,\n});\n\no2.propertyIsEnumerable(\"enumerableInherited\"); // false\no2.propertyIsEnumerable(\"nonEnumerableInherited\"); // false\no2.propertyIsEnumerable(\"enumerableOwn\"); // true\no2.propertyIsEnumerable(\"nonEnumerableOwn\"); // false\n
\n
\n

Testing symbol properties

\n
\n

Symbol properties are also supported by propertyIsEnumerable(). Note that most enumeration methods only visit string properties; enumerability of symbol properties is only useful when using Object.assign() or spread syntax. For more information, see Enumerability and ownership of properties.

\n

js

\n
const sym = Symbol(\"enumerable\");\nconst sym2 = Symbol(\"non-enumerable\");\nconst o = {\n  [sym]: \"is enumerable\",\n};\nObject.defineProperty(o, sym2, {\n  value: \"is non-enumerable\",\n  enumerable: false,\n});\n\no.propertyIsEnumerable(sym); // true\no.propertyIsEnumerable(sym2); // false\n
\n
\n

Usage with null-prototype objects

\n
\n

Because null-prototype objects do not inherit from Object.prototype, they do not inherit the propertyIsEnumerable() method. You must call Object.prototype.propertyIsEnumerable with the object as this instead.

\n

js

\n
const o = {\n  __proto__: null,\n  enumerableOwn: \"is enumerable\",\n};\n\no.propertyIsEnumerable(\"enumerableOwn\"); // TypeError: o.propertyIsEnumerable is not a function\nObject.prototype.propertyIsEnumerable.call(o, \"enumerableOwn\"); // true\n
\n

Alternatively, you may use Object.getOwnPropertyDescriptor() instead, which also helps to distinguish between non-existent properties and actually non-enumerable properties.

\n

js

\n
const o = {\n  __proto__: null,\n  enumerableOwn: \"is enumerable\",\n};\n\nObject.getOwnPropertyDescriptor(o, \"enumerableOwn\")?.enumerable; // true\nObject.getOwnPropertyDescriptor(o, \"nonExistent\")?.enumerable; // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.propertyisenumerable
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
propertyIsEnumerable11215.5434.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable\n

\n
\n", + "global_objects/object/hasownproperty": "

Object.prototype.hasOwnProperty()

\n

The hasOwnProperty() method of Object instances returns a boolean indicating whether this object has the specified property as its own property (as opposed to inheriting it).

Note: Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
hasOwnProperty(prop)\n
\n

Parameters

\n
prop

The String name or Symbol of the property to test.

Return value

\n

Returns true if the object has the specified property as own property; false otherwise.

Description

\n
\n

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype chain.

The method can be called on most JavaScript objects, because most objects descend from Object, and hence inherit its methods. For example Array is an Object, so you can use hasOwnProperty() method to check whether an index exists:

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Watermelon\", \"Orange\"];\nfruits.hasOwnProperty(3); // true ('Orange')\nfruits.hasOwnProperty(4); // false - not defined\n
\n

The method will not be available in objects where it is reimplemented, or on null-prototype objects (as these don't inherit from Object.prototype). Examples for these cases are given below.

\n

Examples

\n

Using hasOwnProperty to test for an own property's existence

\n
\n

The following code shows how to determine whether the example object contains a property named prop.

\n

js

\n
const example = {};\nexample.hasOwnProperty(\"prop\"); // false\n\nexample.prop = \"exists\";\nexample.hasOwnProperty(\"prop\"); // true - 'prop' has been defined\n\nexample.prop = null;\nexample.hasOwnProperty(\"prop\"); // true - own property exists with value of null\n\nexample.prop = undefined;\nexample.hasOwnProperty(\"prop\"); // true - own property exists with value of undefined\n
\n
\n

Direct vs. inherited properties

\n
\n

The following example differentiates between direct properties and properties inherited through the prototype chain:

\n

js

\n
const example = {};\nexample.prop = \"exists\";\n\n// `hasOwnProperty` will only return true for direct properties:\nexample.hasOwnProperty(\"prop\"); // true\nexample.hasOwnProperty(\"toString\"); // false\nexample.hasOwnProperty(\"hasOwnProperty\"); // false\n\n// The `in` operator will return true for direct or inherited properties:\n\"prop\" in example; // true\n\"toString\" in example; // true\n\"hasOwnProperty\" in example; // true\n
\n
\n

Iterating over the properties of an object

\n
\n

The following example shows how to iterate over the enumerable properties of an object without executing on inherited properties.

\n

js

\n
const buz = {\n  fog: \"stack\",\n};\n\nfor (const name in buz) {\n  if (buz.hasOwnProperty(name)) {\n    console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);\n  } else {\n    console.log(name); // toString or something else\n  }\n}\n
\n

Note that the for...in loop only iterates enumerable items: the absence of non-enumerable properties emitted from the loop does not imply that hasOwnProperty itself is confined strictly to enumerable items (as with Object.getOwnPropertyNames()).

\n

Using hasOwnProperty as a property name

\n
\n

JavaScript does not protect the property name hasOwnProperty; an object that has a property with this name may return incorrect results:

\n

js

\n
const foo = {\n  hasOwnProperty() {\n    return false;\n  },\n  bar: \"Here be dragons\",\n};\n\nfoo.hasOwnProperty(\"bar\"); // re-implementation always returns false\n
\n

The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty:

\n

js

\n
const foo = { bar: \"Here be dragons\" };\n\n// Use Object.hasOwn() method - recommended\nObject.hasOwn(foo, \"bar\"); // true\n\n// Use the hasOwnProperty property from the Object prototype\nObject.prototype.hasOwnProperty.call(foo, \"bar\"); // true\n\n// Use another Object's hasOwnProperty\n// and call it with 'this' set to foo\n({}).hasOwnProperty.call(foo, \"bar\"); // true\n
\n

Note that in the first two cases there are no newly created objects.

\n

Objects created with Object.create(null)

\n
\n

null-prototype objects do not inherit from Object.prototype, making hasOwnProperty() inaccessible.

\n

js

\n
const foo = Object.create(null);\nfoo.prop = \"exists\";\nfoo.hasOwnProperty(\"prop\"); // Uncaught TypeError: foo.hasOwnProperty is not a function\n
\n

The solutions in this case are the same as for the previous section: use Object.hasOwn() by preference, otherwise use an external object's hasOwnProperty().

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.hasownproperty
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hasOwnProperty11215.5534.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\n

\n
\n", + "global_objects/object/hasown": "

Object.hasOwn()

\n

The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.

Note: Object.hasOwn() is intended as a replacement for Object.prototype.hasOwnProperty().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Object.hasOwn(obj, prop)\n
\n

Parameters

\n
obj

The JavaScript object instance to test.

prop

The String name or Symbol of the property to test.

Return value

\n

true if the specified object has directly defined the specified property. Otherwise false

Description

\n
\n

The Object.hasOwn() method returns true if the specified property is a direct property of the object — even if the property value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype chain.

It is recommended over Object.prototype.hasOwnProperty() because it works for null-prototype objects and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.

\n

Examples

\n

Using hasOwn to test for a property's existence

\n
\n

The following code shows how to determine whether the example object contains a property named prop.

\n

js

\n
const example = {};\nObject.hasOwn(example, \"prop\"); // false - 'prop' has not been defined\n\nexample.prop = \"exists\";\nObject.hasOwn(example, \"prop\"); // true - 'prop' has been defined\n\nexample.prop = null;\nObject.hasOwn(example, \"prop\"); // true - own property exists with value of null\n\nexample.prop = undefined;\nObject.hasOwn(example, \"prop\"); // true - own property exists with value of undefined\n
\n
\n

Direct vs. inherited properties

\n
\n

The following example differentiates between direct properties and properties inherited through the prototype chain:

\n

js

\n
const example = {};\nexample.prop = \"exists\";\n\n// `hasOwn` will only return true for direct properties:\nObject.hasOwn(example, \"prop\"); // true\nObject.hasOwn(example, \"toString\"); // false\nObject.hasOwn(example, \"hasOwnProperty\"); // false\n\n// The `in` operator will return true for direct or inherited properties:\n\"prop\" in example; // true\n\"toString\" in example; // true\n\"hasOwnProperty\" in example; // true\n
\n
\n

Iterating over the properties of an object

\n
\n

To iterate over the enumerable properties of an object, you should use:

\n

js

\n
const example = { foo: true, bar: true };\nfor (const name of Object.keys(example)) {\n  // …\n}\n
\n

But if you need to use for...in, you can use Object.hasOwn() to skip the inherited properties:

\n

js

\n
const example = { foo: true, bar: true };\nfor (const name in example) {\n  if (Object.hasOwn(example, name)) {\n    // …\n  }\n}\n
\n
\n

Checking if an Array index exists

\n
\n

The elements of an Array are defined as direct properties, so you can use hasOwn() method to check whether a particular index exists:

\n

js

\n
const fruits = [\"Apple\", \"Banana\", \"Watermelon\", \"Orange\"];\nObject.hasOwn(fruits, 3); // true ('Orange')\nObject.hasOwn(fruits, 4); // false - not defined\n
\n
\n

Problematic cases for hasOwnProperty

\n
\n

This section demonstrates that hasOwn() is immune to the problems that affect hasOwnProperty. Firstly, it can be used with objects that have reimplemented hasOwnProperty():

\n

js

\n
const foo = {\n  hasOwnProperty() {\n    return false;\n  },\n  bar: \"The dragons be out of office\",\n};\n\nif (Object.hasOwn(foo, \"bar\")) {\n  console.log(foo.bar); // true - re-implementation of hasOwnProperty() does not affect Object\n}\n
\n

It can also be used with null-prototype objects. These do not inherit from Object.prototype, and so hasOwnProperty() is inaccessible.

\n

js

\n
const foo = Object.create(null);\nfoo.prop = \"exists\";\nif (Object.hasOwn(foo, \"prop\")) {\n  console.log(foo.prop); // true - works irrespective of how the object is created.\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.hasown
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hasOwn939392No7915.49393926615.417.01.1316.9.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn\n

\n
\n", + "global_objects/object/isprototypeof": "

Object.prototype.isPrototypeOf()

\n

The isPrototypeOf() method of Object instances checks if this object exists in another object's prototype chain.

Note: isPrototypeOf() differs from the instanceof operator. In the expression object instanceof AFunction, object's prototype chain is checked against AFunction.prototype, not against AFunction itself.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
isPrototypeOf(object)\n
\n

Parameters

\n
object

The object whose prototype chain will be searched.

Return value

\n

A boolean indicating whether the calling object (this) lies in the prototype chain of object. Directly returns false when object is not an object (i.e. a primitive).

Exceptions

\n
TypeError

Thrown if this is null or undefined (because it can't be converted to an object).

Description

\n

All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the isPrototypeOf() method. This method allows you to check whether or not the object exists within another object's prototype chain. If the object passed as the parameter is not an object (i.e. a primitive), the method directly returns false. Otherwise, the this value is converted to an object, and the prototype chain of object is searched for the this value, until the end of the chain is reached or the this value is found.

Examples

\n

Using isPrototypeOf()

\n
\n

This example demonstrates that Baz.prototype, Bar.prototype, Foo.prototype and Object.prototype exist in the prototype chain for object baz:

\n

js

\n
class Foo {}\nclass Bar extends Foo {}\nclass Baz extends Bar {}\n\nconst foo = new Foo();\nconst bar = new Bar();\nconst baz = new Baz();\n\n// prototype chains:\n// foo: Foo --> Object\n// bar: Bar --> Foo --> Object\n// baz: Baz --> Bar --> Foo --> Object\nconsole.log(Baz.prototype.isPrototypeOf(baz)); // true\nconsole.log(Baz.prototype.isPrototypeOf(bar)); // false\nconsole.log(Baz.prototype.isPrototypeOf(foo)); // false\nconsole.log(Bar.prototype.isPrototypeOf(baz)); // true\nconsole.log(Bar.prototype.isPrototypeOf(foo)); // false\nconsole.log(Foo.prototype.isPrototypeOf(baz)); // true\nconsole.log(Foo.prototype.isPrototypeOf(bar)); // true\nconsole.log(Object.prototype.isPrototypeOf(baz)); // true\n
\n

The isPrototypeOf() method — along with the instanceof operator — comes in particularly handy if you have code that can only function when dealing with objects descended from a specific prototype chain; e.g., to guarantee that certain methods or properties will be present on that object.

For example, to execute some code that's only safe to run if a baz object has Foo.prototype in its prototype chain, you can do this:

\n

js

\n
if (Foo.prototype.isPrototypeOf(baz)) {\n  // do something safe\n}\n
\n

However, Foo.prototype existing in baz's prototype chain doesn't imply baz was created using Foo as its constructor. For example, baz could be directly assigned with Foo.prototype as its prototype. In this case, if your code reads private fields of Foo from baz, it would still fail:

\n

js

\n
class Foo {\n  #value = \"foo\";\n  static getValue(x) {\n    return x.#value;\n  }\n}\n\nconst baz = { __proto__: Foo.prototype };\n\nif (Foo.prototype.isPrototypeOf(baz)) {\n  console.log(Foo.getValue(baz)); // TypeError: Cannot read private member #value from an object whose class did not declare it\n}\n
\n

The same applies to instanceof. If you need to read private fields in a secure way, offer a branded check method using in instead.

\n

js

\n
class Foo {\n  #value = \"foo\";\n  static getValue(x) {\n    return x.#value;\n  }\n  static isFoo(x) {\n    return #value in x;\n  }\n}\n\nconst baz = { __proto__: Foo.prototype };\n\nif (Foo.isFoo(baz)) {\n  // Doesn't run, because baz is not a Foo\n  console.log(Foo.getValue(baz));\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.prototype.isprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isPrototypeOf11219434.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf\n

\n
\n", + "global_objects/function/call": "

Function.prototype.call()

The call() method of Function instances calls this function with a given this value and arguments provided individually.

\n

Try it

\n

Syntax

\n
\n

js

\n
call(thisArg)\ncall(thisArg, arg1)\ncall(thisArg, arg1, arg2)\ncall(thisArg, arg1, arg2, /* …, */ argN)\n
\n

Parameters

\n
thisArg

The value to use as this when calling func. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

\narg1, …, argN Optional\n

Arguments for the function.

Return value

\n

The result of calling the function with the specified this value and arguments.

Description

\n
\n

Note: This function is almost identical to apply(), except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array — for example, func.call(this, \"eat\", \"bananas\") vs. func.apply(this, [\"eat\", \"bananas\"]).

Normally, when calling a function, the value of this inside the function is the object that the function was accessed on. With call(), you can assign an arbitrary value as this when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

Warning: Do not use call() to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means new.target is undefined, and classes throw an error because they can't be called without new. Use Reflect.construct() or extends instead.

\n

Examples

\n

Using call() to invoke a function and specifying the this value

\n
\n

In the example below, when we call greet, the value of this will be bound to object obj, even when greet is not a method of obj.

\n

js

\n
function greet() {\n  console.log(this.animal, \"typically sleep between\", this.sleepDuration);\n}\n\nconst obj = {\n  animal: \"cats\",\n  sleepDuration: \"12 and 16 hours\",\n};\n\ngreet.call(obj); // cats typically sleep between 12 and 16 hours\n
\n
\n

Using call() to invoke a function without specifying the first argument

\n
\n

If the first thisArg parameter is omitted, it defaults to undefined. In non-strict mode, the this value is then substituted with globalThis (which is akin to the global object).

\n

js

\n
globalThis.globProp = \"Wisen\";\n\nfunction display() {\n  console.log(`globProp value is ${this.globProp}`);\n}\n\ndisplay.call(); // Logs \"globProp value is Wisen\"\n
\n

In strict mode, the value of this is not substituted, so it stays as undefined.

\n

js

\n
\"use strict\";\n\nglobalThis.globProp = \"Wisen\";\n\nfunction display() {\n  console.log(`globProp value is ${this.globProp}`);\n}\n\ndisplay.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined\n
\n
\n

Transforming methods to utility functions

\n
\n

call() is almost equivalent to a normal function call, except that this is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling array.map(callback), you use map(array, callback), which avoids mutating Array.prototype, and allows you to use map with array-like objects that are not arrays (for example, arguments).

Take Array.prototype.slice(), for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

\n

js

\n
const slice = Array.prototype.slice;\n\n// ...\n\nslice.call(arguments);\n
\n

Note that you can't save slice.call and call it as a plain function, because the call() method also reads its this value, which is the function it should call. In this case, you can use bind() to bind the value of this for call(). In the following piece of code, slice() is a bound version of Function.prototype.call(), with the this value bound to Array.prototype.slice(). This means that additional call() calls can be eliminated:

\n

js

\n
// Same as \"slice\" in the previous example\nconst unboundSlice = Array.prototype.slice;\nconst slice = Function.prototype.call.bind(unboundSlice);\n\n// ...\n\nslice(arguments);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function.prototype.call
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
call11215.5414.418410.111.01.0
0.10.0When calling this method, thisArg does not default to the global object.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\n

\n
\n", + "global_objects/map/delete": "

Map.prototype.delete()

The delete() method of Map instances removes the specified element from this map by key.

\n

Try it

\n

Syntax

\n
\n

js

\n
mapInstance.delete(key)\n
\n

Parameters

\n
key

The key of the element to remove from the Map object.

Return value

\n

true if an element in the Map object existed and has been removed, or false if the element does not exist.

Examples

\n

Using delete()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"bar\", \"foo\");\n\nconsole.log(myMap.delete(\"bar\")); // Returns true. Successfully removed.\nconsole.log(myMap.has(\"bar\")); // Returns false. The \"bar\" element is no longer present.\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.delete
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
delete381213112583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete\n

\n
\n", + "global_objects/object/create": "

Object.create()

The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.create(proto)\nObject.create(proto, propertiesObject)\n
\n

Parameters

\n
proto

The object which should be the prototype of the newly-created object.

\npropertiesObject Optional\n

If specified and not undefined, an object whose enumerable own properties specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties().

Return value

\n

A new object with the specified prototype object and properties.

Exceptions

\n
TypeError

Thrown if proto is neither null nor an Object.

Examples

\n

Classical inheritance with Object.create()

\n
\n

Below is an example of how to use Object.create() to achieve classical inheritance. This is for a single inheritance, which is all that JavaScript supports.

\n

js

\n
// Shape - superclass\nfunction Shape() {\n  this.x = 0;\n  this.y = 0;\n}\n\n// superclass method\nShape.prototype.move = function (x, y) {\n  this.x += x;\n  this.y += y;\n  console.info(\"Shape moved.\");\n};\n\n// Rectangle - subclass\nfunction Rectangle() {\n  Shape.call(this); // call super constructor.\n}\n\n// subclass extends superclass\nRectangle.prototype = Object.create(Shape.prototype, {\n  // If you don't set Rectangle.prototype.constructor to Rectangle,\n  // it will take the prototype.constructor of Shape (parent).\n  // To avoid that, we set the prototype.constructor to Rectangle (child).\n  constructor: {\n    value: Rectangle,\n    enumerable: false,\n    writable: true,\n    configurable: true,\n  },\n});\n\nconst rect = new Rectangle();\n\nconsole.log(\"Is rect an instance of Rectangle?\", rect instanceof Rectangle); // true\nconsole.log(\"Is rect an instance of Shape?\", rect instanceof Shape); // true\nrect.move(1, 1); // Logs 'Shape moved.'\n
\n

Note that there are caveats to watch out for using create(), such as re-adding the constructor property to ensure proper semantics. Although Object.create() is believed to have better performance than mutating the prototype with Object.setPrototypeOf(), the difference is in fact negligible if no instances have been created and property accesses haven't been optimized yet. In modern code, the class syntax should be preferred in any case.

\n

Using propertiesObject argument with Object.create()

\n
\n

Object.create() allows fine-tuned control over the object creation process. The object initializer syntax is, in fact, a syntax sugar of Object.create(). With Object.create(), we can create objects with a designated prototype and also some properties. Note that the second parameter maps keys to property descriptors — this means you can control each property's enumerability, configurability, etc. as well, which you can't do in object initializers.

\n

js

\n
o = {};\n// Is equivalent to:\no = Object.create(Object.prototype);\n\no = Object.create(Object.prototype, {\n  // foo is a regular data property\n  foo: {\n    writable: true,\n    configurable: true,\n    value: \"hello\",\n  },\n  // bar is an accessor property\n  bar: {\n    configurable: false,\n    get() {\n      return 10;\n    },\n    set(value) {\n      console.log(\"Setting `o.bar` to\", value);\n    },\n  },\n});\n\n// Create a new object whose prototype is a new, empty\n// object and add a single property 'p', with value 42.\no = Object.create({}, { p: { value: 42 } });\n
\n

With Object.create(), we can create an object with null as prototype. The equivalent syntax in object initializers would be the __proto__ key.

\n

js

\n
o = Object.create(null);\n// Is equivalent to:\no = { __proto__: null };\n
\n

By default properties are not writable, enumerable or configurable.

\n

js

\n
o.p = 24; // throws in strict mode\no.p; // 42\n\no.q = 12;\nfor (const prop in o) {\n  console.log(prop);\n}\n// 'q'\n\ndelete o.p;\n// false; throws in strict mode\n
\n

To specify a property with the same attributes as in an initializer, explicitly specify writable, enumerable and configurable.

\n

js

\n
o2 = Object.create(\n  {},\n  {\n    p: {\n      value: 42,\n      writable: true,\n      enumerable: true,\n      configurable: true,\n    },\n  },\n);\n// This is not equivalent to:\n// o2 = Object.create({ p: 42 })\n// which will create an object with prototype { p: 42 }\n
\n

You can use Object.create() to mimic the behavior of the new operator.

\n

js

\n
function Constructor() {}\no = new Constructor();\n// Is equivalent to:\no = Object.create(Constructor.prototype);\n
\n

Of course, if there is actual initialization code in the Constructor function, the Object.create() method cannot reflect it.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.create
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
create5124911.654.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\n

\n
\n", + "global_objects/object/groupby": "

Object.groupBy()

\n

Note: In some versions of some browsers, this method was implemented as the method Array.prototype.group(). Due to web compatibility issues, it is now implemented as a static method. Check the browser compatibility table for details.

The Object.groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group.

This method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use Map.groupBy() instead.

\n
\n

Syntax

\n
\n

js

\n
Object.groupBy(items, callbackFn)\n
\n

Parameters

\n
items

An iterable (such as an Array) whose elements will be grouped.

callbackFn

A function to execute for each element in the iterable. It should return a value that can get coerced into a property key (string or symbol) indicating the group of the current element. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

A null-prototype object with properties for all groups, each assigned to an array containing the elements of the associated group.

Description

\n
\n

Object.groupBy() calls a provided callbackFn function once for each element in an iterable. The callback function should return a string or symbol (values that are neither type are coerced to strings) indicating the group of the associated element. The values returned by callbackFn are used as keys for the object returned by Map.groupBy(). Each key has an associated array containing all the elements for which the callback returned the same value.

The elements in the returned object and the original iterable are the same (not deep copies). Changing the internal structure of the elements will be reflected in both the original iterable and the returned object.

\n

Examples

\n

Using Object.groupBy()

\n
\n

First we define an array containing objects representing an inventory of different foodstuffs. Each food has a type and a quantity.

\n

js

\n
const inventory = [\n  { name: \"asparagus\", type: \"vegetables\", quantity: 5 },\n  { name: \"bananas\", type: \"fruit\", quantity: 0 },\n  { name: \"goat\", type: \"meat\", quantity: 23 },\n  { name: \"cherries\", type: \"fruit\", quantity: 5 },\n  { name: \"fish\", type: \"meat\", quantity: 22 },\n];\n
\n

The code below groups the elements by the value of their type property.

\n

js

\n
const result = Object.groupBy(inventory, ({ type }) => type);\n\n/* Result is:\n{\n  vegetables: [\n    { name: 'asparagus', type: 'vegetables', quantity: 5 },\n  ],\n  fruit: [\n    { name: \"bananas\", type: \"fruit\", quantity: 0 },\n    { name: \"cherries\", type: \"fruit\", quantity: 5 }\n  ],\n  meat: [\n    { name: \"goat\", type: \"meat\", quantity: 23 },\n    { name: \"fish\", type: \"meat\", quantity: 22 }\n  ]\n}\n*/\n
\n

The arrow function just returns the type of each array element each time it is called. Note that the function argument { type } is a basic example of object destructuring syntax for function arguments. This unpacks the type property of an object passed as a parameter, and assigns it to a variable named type in the body of the function. This is a very succinct way to access the relevant values of elements within a function.

We can also create groups inferred from values in one or more properties of the elements. Below is a very similar example that puts the items into ok or restock groups based on the value of the quantity field.

\n

js

\n
function myCallback({ quantity }) {\n  return quantity > 5 ? \"ok\" : \"restock\";\n}\n\nconst result2 = Object.groupBy(inventory, myCallback);\n\n/* Result is:\n{\n  restock: [\n    { name: \"asparagus\", type: \"vegetables\", quantity: 5 },\n    { name: \"bananas\", type: \"fruit\", quantity: 0 },\n    { name: \"cherries\", type: \"fruit\", quantity: 5 }\n  ],\n  ok: [\n    { name: \"goat\", type: \"meat\", quantity: 23 },\n    { name: \"fish\", type: \"meat\", quantity: 22 }\n  ]\n}\n*/\n
\n
\n

Specifications

\n
\n\n\n
Specification
Array Grouping
# sec-object.groupby
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
groupBy117117119No10316.4–previewpreview117117119No16.4No1.37No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy\n

\n
\n", + "global_objects/regexp/exec": "

RegExp.prototype.exec()

The exec() method of RegExp instances executes a search with this regular expression for a match in a specified string and returns a result array, or null.

\n

Try it

\n

Syntax

\n
\n

js

\n
exec(str)\n
\n

Parameters

\n
str

The string against which to match the regular expression. All values are coerced to strings, so omitting it or passing undefined causes exec() to search for the string \"undefined\", which is rarely what you want.

Return value

\n
\n

If the match fails, the exec() method returns null, and sets the regex's lastIndex to 0.

If the match succeeds, the exec() method returns an array and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text. The array also has the following additional properties:

index

The 0-based index of the match in the string.

input

The original string that was matched against.

groups

A null-prototype object of named capturing groups, whose keys are the names, and values are the capturing groups, or undefined if no named capturing groups were defined. See capturing groups for more information.

\nindices Optional\n

This property is only present when the d flag is set. It is an array where each entry represents the bounds of a substring match. The index of each element in this array corresponds to the index of the respective substring match in the array returned by exec(). In other words, the first indices entry represents the entire match, the second indices entry represents the first capturing group, etc. Each entry itself is a two-element array, where the first number represents the match's start index, and the second number, its end index.

The indices array additionally has a groups property, which holds a null-prototype object of all named capturing groups. The keys are the names of the capturing groups, and each value is a two-element array, with the first number being the start index, and the second number being the end index of the capturing group. If the regular expression doesn't contain any named capturing groups, groups is undefined.

\n

Description

\n
\n

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with String.prototype.match().

When using exec(), the global flag has no effect when the sticky flag is set — the match is always sticky.

exec() is the primitive method of regexps. Many other regexp methods call exec() internally — including those called by string methods, like @@replace. While exec() itself is powerful (and is the most efficient), it often does not convey the intent most clearly.

\n

Examples

\n

Using exec()

\n
\n

Consider the following example:

\n

js

\n
// Match \"quick brown\" followed by \"jumps\", ignoring characters in between\n// Remember \"brown\" and \"jumps\"\n// Ignore case\nconst re = /quick\\s(?<color>brown).+?(jumps)/dgi;\nconst result = re.exec(\"The Quick Brown Fox Jumps Over The Lazy Dog\");\n
\n

The following table shows the state of result after running this script:

Property Value
[0] \"Quick Brown Fox Jumps\"
[1] \"Brown\"
[2] \"Jumps\"
index 4
indices \n[[4, 25], [10, 15], [20, 25]]
groups: { color: [10, 15 ]}\n
input \"The Quick Brown Fox Jumps Over The Lazy Dog\"
groups { color: \"brown\" }

In addition, re.lastIndex will be set to 25, due to this regex being global.

\n

Finding successive matches

\n
\n

If your regular expression uses the g flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). Note that the lastIndex property will not be reset when searching a different string, it will start its search at its existing lastIndex.

For example, assume you have this script:

\n

js

\n
const myRe = /ab*/g;\nconst str = \"abbcdefabh\";\nlet myArray;\nwhile ((myArray = myRe.exec(str)) !== null) {\n  let msg = `Found ${myArray[0]}. `;\n  msg += `Next match starts at ${myRe.lastIndex}`;\n  console.log(msg);\n}\n
\n

This script displays the following text:

Found abb. Next match starts at 3\nFound ab. Next match starts at 9\n

Warning: There are many pitfalls that can lead to this becoming an infinite loop!

  • Do not place the regular expression literal (or RegExp constructor) within the while condition — it will recreate the regex for every iteration and reset lastIndex.
  • Be sure that the global (g) flag is set, or lastIndex will never be advanced.
  • If the regex may match zero-length characters (e.g. /^/gm), increase its lastIndex manually each time to avoid being stuck in the same place.

You can usually replace this kind of code with String.prototype.matchAll() to make it less error-prone.

\n

Using exec() with RegExp literals

\n
\n

You can also use exec() without creating a RegExp object explicitly:

\n

js

\n
const matches = /(hello \\S+)/.exec(\"This is a hello world!\");\nconsole.log(matches[1]);\n
\n

This will log a message containing 'hello world!'.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype.exec
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
exec11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec\n

\n
\n", + "global_objects/array/@@unscopables": "

Array.prototype[@@unscopables]

The @@unscopables data property of Array.prototype is shared by all Array instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with statement-binding purposes.

\n

Value

\n
\n

A null-prototype object with property names given below and their values set to true.

\n
Property attributes of Array.prototype[@@unscopables]\n
Writable no
Enumerable no
Configurable yes
\n

Description

\n
\n

The default Array properties that are ignored for with statement-binding purposes are:

Array.prototype[@@unscopables] is an empty object only containing all the above property names with the value true. Its prototype is null, so Object.prototype properties like toString won't accidentally be made unscopable, and a toString() within the with statement will continue to be called on the array.

See Symbol.unscopables for how to set unscopable properties for your own objects.

\n

Examples

\n
\n

Imagine the keys.push('something') call below is in code that was written prior to ECMAScript 2015.

\n

js

\n
var keys = [];\n\nwith (Array.prototype) {\n  keys.push(\"something\");\n}\n
\n

When ECMAScript 2015 introduced the Array.prototype.keys() method, if the @@unscopables data property had not also been introduced, that keys.push('something') call would break — because the JavaScript runtime would have interpreted keys as being the Array.prototype.keys() method, rather than the keys array defined in the example code.

So the @@unscopables data property for Array.prototype causes the Array properties introduced in ECMAScript 2015 to be ignored for with statement-binding purposes — allowing code that was written prior to ECMAScript 2015 to continue working as expected, rather than breaking.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype-@@unscopables
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@unscopables381248No251038384825103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@unscopables\n

\n
\n", + "global_objects/object/keys": "

Object.keys()

The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.keys(obj)\n
\n

Parameters

\n
obj

An object.

Return value

\n

An array of strings representing the given object's own enumerable string-keyed property keys.

Description

\n
\n

Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys() is the same as that provided by a for...in loop.

If you need the property values, use Object.values() instead. If you need both the property keys and values, use Object.entries() instead.

\n

Examples

\n

Using Object.keys()

\n
\n
\n

js

\n
// Simple array\nconst arr = [\"a\", \"b\", \"c\"];\nconsole.log(Object.keys(arr)); // ['0', '1', '2']\n\n// Array-like object\nconst obj = { 0: \"a\", 1: \"b\", 2: \"c\" };\nconsole.log(Object.keys(obj)); // ['0', '1', '2']\n\n// Array-like object with random key ordering\nconst anObj = { 100: \"a\", 2: \"b\", 7: \"c\" };\nconsole.log(Object.keys(anObj)); // ['2', '7', '100']\n\n// getFoo is a non-enumerable property\nconst myObj = Object.create(\n  {},\n  {\n    getFoo: {\n      value() {\n        return this.foo;\n      },\n    },\n  },\n);\nmyObj.foo = 1;\nconsole.log(Object.keys(myObj)); // ['foo']\n
\n

If you want all string-keyed own properties, including non-enumerable ones, see Object.getOwnPropertyNames().

\n

Using Object.keys() on primitives

\n
\n

Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.

\n

js

\n
// Strings have indices as enumerable own properties\nconsole.log(Object.keys(\"foo\")); // ['0', '1', '2']\n\n// Other primitives have no own properties\nconsole.log(Object.keys(100)); // []\n
\n

Note: In ES5, passing a non-object to Object.keys() threw a TypeError.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.keys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keys512491254.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\n

\n
\n", + "global_objects/object/assign": "

Object.assign()

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.assign(target)\nObject.assign(target, source1)\nObject.assign(target, source1, source2)\nObject.assign(target, source1, source2, /* …, */ sourceN)\n
\n

Parameters

\n
target

The target object — what to apply the sources' properties to, which is returned after it is modified.

\nsource1, …, sourceN\n

The source object(s) — objects containing the properties you want to apply.

Return value

\n

The target object.

Description

\n
\n

Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.

Note: Object.assign() does not throw on null or undefined sources.

\n

Examples

\n

Cloning an object

\n
\n

js

\n
const obj = { a: 1 };\nconst copy = Object.assign({}, obj);\nconsole.log(copy); // { a: 1 }\n
\n

Warning for Deep Clone

\n
\n

For deep cloning, we need to use alternatives like structuredClone(), because Object.assign() copies property values.

If the source value is a reference to an object, it only copies the reference value.

\n

js

\n
const obj1 = { a: 0, b: { c: 0 } };\nconst obj2 = Object.assign({}, obj1);\nconsole.log(obj2); // { a: 0, b: { c: 0 } }\n\nobj1.a = 1;\nconsole.log(obj1); // { a: 1, b: { c: 0 } }\nconsole.log(obj2); // { a: 0, b: { c: 0 } }\n\nobj2.a = 2;\nconsole.log(obj1); // { a: 1, b: { c: 0 } }\nconsole.log(obj2); // { a: 2, b: { c: 0 } }\n\nobj2.b.c = 3;\nconsole.log(obj1); // { a: 1, b: { c: 3 } }\nconsole.log(obj2); // { a: 2, b: { c: 3 } }\n\n// Deep Clone\nconst obj3 = { a: 0, b: { c: 0 } };\nconst obj4 = structuredClone(obj3);\nobj3.a = 4;\nobj3.b.c = 4;\nconsole.log(obj4); // { a: 0, b: { c: 0 } }\n
\n
\n

Merging objects

\n
\n

js

\n
const o1 = { a: 1 };\nconst o2 = { b: 2 };\nconst o3 = { c: 3 };\n\nconst obj = Object.assign(o1, o2, o3);\nconsole.log(obj); // { a: 1, b: 2, c: 3 }\nconsole.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.\n
\n

Merging objects with same properties

\n
\n
\n

js

\n
const o1 = { a: 1, b: 1, c: 1 };\nconst o2 = { b: 2, c: 2 };\nconst o3 = { c: 3 };\n\nconst obj = Object.assign({}, o1, o2, o3);\nconsole.log(obj); // { a: 1, b: 2, c: 3 }\n
\n

The properties are overwritten by other objects that have the same properties later in the parameters order.

\n

Copying symbol-typed properties

\n
\n

js

\n
const o1 = { a: 1 };\nconst o2 = { [Symbol(\"foo\")]: 2 };\n\nconst obj = Object.assign({}, o1, o2);\nconsole.log(obj); // { a : 1, [Symbol(\"foo\")]: 2 } (cf. bug 1207182 on Firefox)\nObject.getOwnPropertySymbols(obj); // [Symbol(foo)]\n
\n

Properties on the prototype chain and non-enumerable properties cannot be copied

\n
\n

js

\n
const obj = Object.create(\n  // foo is on obj's prototype chain.\n  { foo: 1 },\n  {\n    bar: {\n      value: 2, // bar is a non-enumerable property.\n    },\n    baz: {\n      value: 3,\n      enumerable: true, // baz is an own enumerable property.\n    },\n  },\n);\n\nconst copy = Object.assign({}, obj);\nconsole.log(copy); // { baz: 3 }\n
\n

Primitives will be wrapped to objects

\n
\n

js

\n
const v1 = \"abc\";\nconst v2 = true;\nconst v3 = 10;\nconst v4 = Symbol(\"foo\");\n\nconst obj = Object.assign({}, v1, null, v2, undefined, v3, v4);\n// Primitives will be wrapped, null and undefined will be ignored.\n// Note, only string wrappers can have own enumerable properties.\nconsole.log(obj); // { \"0\": \"a\", \"1\": \"b\", \"2\": \"c\" }\n
\n

Exceptions will interrupt the ongoing copying task

\n
\n

js

\n
const target = Object.defineProperty({}, \"foo\", {\n  value: 1,\n  writable: false,\n}); // target.foo is a read-only property\n\nObject.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });\n// TypeError: \"foo\" is read-only\n// The Exception is thrown when assigning target.foo\n\nconsole.log(target.bar); // 2, the first source was copied successfully.\nconsole.log(target.foo2); // 3, the first property of the second source was copied successfully.\nconsole.log(target.foo); // 1, exception is thrown here.\nconsole.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.\nconsole.log(target.baz); // undefined, the third source will not be copied either.\n
\n

Copying accessors

\n
\n

js

\n
const obj = {\n  foo: 1,\n  get bar() {\n    return 2;\n  },\n};\n\nlet copy = Object.assign({}, obj);\nconsole.log(copy);\n// { foo: 1, bar: 2 }\n// The value of copy.bar is obj.bar's getter's return value.\n\n// This is an assign function that copies full descriptors\nfunction completeAssign(target, ...sources) {\n  sources.forEach((source) => {\n    const descriptors = Object.keys(source).reduce((descriptors, key) => {\n      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);\n      return descriptors;\n    }, {});\n\n    // By default, Object.assign copies enumerable Symbols, too\n    Object.getOwnPropertySymbols(source).forEach((sym) => {\n      const descriptor = Object.getOwnPropertyDescriptor(source, sym);\n      if (descriptor.enumerable) {\n        descriptors[sym] = descriptor;\n      }\n    });\n    Object.defineProperties(target, descriptors);\n  });\n  return target;\n}\n\ncopy = completeAssign({}, obj);\nconsole.log(copy);\n// { foo:1, get bar() { return 2 } }\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.assign
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
assign451234No3294545343295.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n

\n
\n", + "global_objects/object/defineproperties": "

Object.defineProperties()

The Object.defineProperties() static method defines new or modifies existing properties directly on an object, returning the object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.defineProperties(obj, props)\n
\n

Parameters

\n
obj

The object on which to define or modify properties.

props

An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in props must be either a data descriptor or an accessor descriptor; it cannot be both (see Object.defineProperty() for more details).

Data descriptors and accessor descriptors may optionally contain the following keys:

configurable

true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. false

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object. false

A data descriptor also has the following optional keys:

value

The value associated with the property. Can be any valid JavaScript value (number, object, function, etc.). Defaults to undefined.

writable

true if and only if the value associated with the property may be changed with an assignment operator. false

An accessor descriptor also has the following optional keys:

get

A function which serves as a getter for the property, or undefined if there is no getter. The function's return value will be used as the value of the property. Defaults to undefined.

set

A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults to undefined.

If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.

Return value

\n

The object that was passed to the function.

Examples

\n

Using Object.defineProperties

\n
\n

js

\n
const obj = {};\nObject.defineProperties(obj, {\n  property1: {\n    value: true,\n    writable: true,\n  },\n  property2: {\n    value: \"Hello\",\n    writable: false,\n  },\n  // etc. etc.\n});\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.defineproperties
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
defineProperties5124911.654.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties\n

\n
\n", + "global_objects/object/entries": "

Object.entries()

The Object.entries() static method returns an array of a given object's own enumerable string-keyed property key-value pairs.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.entries(obj)\n
\n

Parameters

\n
obj

An object.

Return value

\n

An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.

Description

\n
\n

Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.entries() is the same as that provided by a for...in loop.

If you only need the property keys, use Object.keys() instead. If you only need the property values, use Object.values() instead.

\n

Examples

\n

Using Object.entries()

\n
\n

js

\n
const obj = { foo: \"bar\", baz: 42 };\nconsole.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]\n\nconst arrayLike = { 0: \"a\", 1: \"b\", 2: \"c\" };\nconsole.log(Object.entries(arrayLike)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]\n\nconst randomKeyOrder = { 100: \"a\", 2: \"b\", 7: \"c\" };\nconsole.log(Object.entries(randomKeyOrder)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]\n\n// getFoo is a non-enumerable property\nconst myObj = Object.create(\n  {},\n  {\n    getFoo: {\n      value() {\n        return this.foo;\n      },\n    },\n  },\n);\nmyObj.foo = \"bar\";\nconsole.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]\n
\n

Using Object.entries() on primitives

\n
\n

Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.

\n

js

\n
// Strings have indices as enumerable own properties\nconsole.log(Object.entries(\"foo\")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]\n\n// Other primitives have no own properties\nconsole.log(Object.entries(100)); // []\n
\n
\n

Converting an Object to a Map

\n
\n

The Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

\n

js

\n
const obj = { foo: \"bar\", baz: 42 };\nconst map = new Map(Object.entries(obj));\nconsole.log(map); // Map(2) {\"foo\" => \"bar\", \"baz\" => 42}\n
\n
\n

Iterating through an Object

\n
\n

Using array destructuring, you can iterate through objects easily.

\n

js

\n
// Using for...of loop\nconst obj = { a: 5, b: 7, c: 9 };\nfor (const [key, value] of Object.entries(obj)) {\n  console.log(`${key}${value}`); // \"a 5\", \"b 7\", \"c 9\"\n}\n\n// Using array methods\nObject.entries(obj).forEach(([key, value]) => {\n  console.log(`${key}${value}`); // \"a 5\", \"b 7\", \"c 9\"\n});\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.entries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
entries541447No4110.15454474110.36.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n

\n
\n", + "global_objects/object/freeze": "

Object.freeze()

\n

The Object.freeze() static method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. freeze() returns the same object that was passed in.

Freezing an object is the highest integrity level that JavaScript provides.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Object.freeze(obj)\n
\n

Parameters

\n
obj

The object to freeze.

Return value

\n

The object that was passed to the function.

Description

\n
\n

Freezing an object is equivalent to preventing extensions and then changing all existing properties' descriptors' configurable to false — and for data properties, writable to false as well. Nothing can be added to or removed from the properties set of a frozen object. Any attempt to do so will fail, either silently or by throwing a TypeError exception (most commonly, but not exclusively, when in strict mode).

For data properties of a frozen object, their values cannot be changed since the writable and configurable attributes are set to false. Accessor properties (getters and setters) work the same — the property value returned by the getter may still change, and the setter can still be called without throwing errors when setting the property. Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.

freeze() returns the same object that was passed into the function. It does not create a frozen copy.

A TypedArray or a DataView with elements will cause a TypeError, as they are views over memory and will definitely cause other possible issues:

\n

js

\n
Object.freeze(new Uint8Array(0)); // No elements\n// Uint8Array []\n\nObject.freeze(new Uint8Array(1)); // Has elements\n// TypeError: Cannot freeze array buffer views with elements\n\nObject.freeze(new DataView(new ArrayBuffer(32))); // No elements\n// DataView {}\n\nObject.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)); // No elements\n// Float64Array []\n\nObject.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)); // Has elements\n// TypeError: Cannot freeze array buffer views with elements\n
\n

Note that as the standard three properties (buf.byteLength, buf.byteOffset and buf.buffer) are read-only (as are those of an ArrayBuffer or SharedArrayBuffer), there is no reason for attempting to freeze these properties.

Unlike Object.seal(), existing properties in objects frozen with Object.freeze() are made immutable and data properties cannot be re-assigned.

\n

Examples

\n

Freezing objects

\n
\n

js

\n
const obj = {\n  prop() {},\n  foo: \"bar\",\n};\n\n// Before freezing: new properties may be added,\n// and existing properties may be changed or removed\nobj.foo = \"baz\";\nobj.lumpy = \"woof\";\ndelete obj.prop;\n\n// Freeze.\nconst o = Object.freeze(obj);\n\n// The return value is just the same object we passed in.\no === obj; // true\n\n// The object has become frozen.\nObject.isFrozen(obj); // === true\n\n// Now any changes will fail\nobj.foo = \"quux\"; // silently does nothing\n// silently doesn't add the property\nobj.quaxxor = \"the friendly duck\";\n\n// In strict mode such attempts will throw TypeErrors\nfunction fail() {\n  \"use strict\";\n  obj.foo = \"sparky\"; // throws a TypeError\n  delete obj.foo; // throws a TypeError\n  delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added\n  obj.sparky = \"arf\"; // throws a TypeError\n}\n\nfail();\n\n// Attempted changes through Object.defineProperty;\n// both statements below throw a TypeError.\nObject.defineProperty(obj, \"ohai\", { value: 17 });\nObject.defineProperty(obj, \"foo\", { value: \"eit\" });\n\n// It's also impossible to change the prototype\n// both statements below will throw a TypeError.\nObject.setPrototypeOf(obj, { x: 20 });\nobj.__proto__ = { x: 20 };\n
\n

Freezing arrays

\n
\n
\n

js

\n
const a = [0];\nObject.freeze(a); // The array cannot be modified now.\n\na[0] = 1; // fails silently\n\n// In strict mode such attempt will throw a TypeError\nfunction fail() {\n  \"use strict\";\n  a[0] = 1;\n}\n\nfail();\n\n// Attempted to push\na.push(2); // throws a TypeError\n
\n

The object being frozen is immutable. However, it is not necessarily constant. The following example shows that a frozen object is not constant (freeze is shallow).

\n

js

\n
const obj1 = {\n  internal: {},\n};\n\nObject.freeze(obj1);\nobj1.internal.a = \"aValue\";\n\nobj1.internal.a; // 'aValue'\n
\n

To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. The object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.

What is \"shallow freeze\"?

The result of calling Object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.

\n

js

\n
const employee = {\n  name: \"Mayank\",\n  designation: \"Developer\",\n  address: {\n    street: \"Rohini\",\n    city: \"Delhi\",\n  },\n};\n\nObject.freeze(employee);\n\nemployee.name = \"Dummy\"; // fails silently in non-strict mode\nemployee.address.city = \"Noida\"; // attributes of child object can be modified\n\nconsole.log(employee.address.city); // \"Noida\"\n
\n

To make an object immutable, recursively freeze each non-primitive property (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered. An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling deepFreeze() recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as window.

\n

js

\n
function deepFreeze(object) {\n  // Retrieve the property names defined on object\n  const propNames = Reflect.ownKeys(object);\n\n  // Freeze properties before freezing self\n  for (const name of propNames) {\n    const value = object[name];\n\n    if ((value && typeof value === \"object\") || typeof value === \"function\") {\n      deepFreeze(value);\n    }\n  }\n\n  return Object.freeze(object);\n}\n\nconst obj2 = {\n  internal: {\n    a: null,\n  },\n};\n\ndeepFreeze(obj2);\n\nobj2.internal.a = \"anotherValue\"; // fails silently in non-strict mode\nobj2.internal.a; // null\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.freeze
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
freeze61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n

\n
\n", + "global_objects/object/fromentries": "

Object.fromEntries()

The Object.fromEntries() static method transforms a list of key-value pairs into an object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.fromEntries(iterable)\n
\n

Parameters

\n
iterable

An iterable, such as an Array or Map, containing a list of objects. Each object should have two properties:

0

A string or symbol representing the property key.

1

The property value.

Typically, this object is implemented as a two-element array, with the first element being the property key and the second element being the property value.

Return value

\n

A new object whose properties are given by the entries of the iterable.

Description

\n
\n

The Object.fromEntries() method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The iterable argument is expected to be an object that implements an @@iterator method. The method returns an iterator object that produces two-element array-like objects. The first element is a value that will be used as a property key, and the second element is the value to associate with that property key.

Object.fromEntries() performs the reverse of Object.entries(), except that Object.entries() only returns string-keyed properties, while Object.fromEntries() can also create symbol-keyed properties.

Note: Unlike Array.from(), Object.fromEntries() does not use the value of this, so calling it on another constructor does not create objects of that type.

\n

Examples

\n

Converting a Map to an Object

\n
\n

With Object.fromEntries, you can convert from Map to Object:

\n

js

\n
const map = new Map([\n  [\"foo\", \"bar\"],\n  [\"baz\", 42],\n]);\nconst obj = Object.fromEntries(map);\nconsole.log(obj); // { foo: \"bar\", baz: 42 }\n
\n
\n

Converting an Array to an Object

\n
\n

With Object.fromEntries, you can convert from Array to Object:

\n

js

\n
const arr = [\n  [\"0\", \"a\"],\n  [\"1\", \"b\"],\n  [\"2\", \"c\"],\n];\nconst obj = Object.fromEntries(arr);\nconsole.log(obj); // { 0: \"a\", 1: \"b\", 2: \"c\" }\n
\n
\n

Object transformations

\n
\n

With Object.fromEntries, its reverse method Object.entries(), and array manipulation methods, you are able to transform objects like this:

\n

js

\n
const object1 = { a: 1, b: 2, c: 3 };\n\nconst object2 = Object.fromEntries(\n  Object.entries(object1).map(([key, val]) => [key, val * 2]),\n);\n\nconsole.log(object2);\n// { a: 2, b: 4, c: 6 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.fromentries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fromEntries737963No6012.17373635212.211.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries\n

\n
\n", + "global_objects/object/getownpropertydescriptors": "

Object.getOwnPropertyDescriptors()

The Object.getOwnPropertyDescriptors() static method returns all own property descriptors of a given object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.getOwnPropertyDescriptors(obj)\n
\n

Parameters

\n
obj

The object for which to get all own property descriptors.

Return value

\n

An object containing all own property descriptors of an object. Might be an empty object, if there are no properties.

Description

\n
\n

This method permits examination of the precise description of all own properties of an object. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty().

A property descriptor is a record with some of the following attributes:

value

The value associated with the property (data descriptors only).

writable

true if and only if the value associated with the property may be changed (data descriptors only).

get

A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only).

set

A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only).

configurable

true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object.

\n

Examples

\n

Creating a shallow copy

\n
\n

Whereas the Object.assign() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and Object.create() for a shallow copy between two unknown objects:

\n

js

\n
Object.create(\n  Object.getPrototypeOf(obj),\n  Object.getOwnPropertyDescriptors(obj),\n);\n
\n
\n

Creating a subclass

\n
\n

A typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. This can get awkward especially for getters and setters. Instead, you can use this code to set the prototype:

\n

js

\n
function superclass() {}\nsuperclass.prototype = {\n  // Define the superclass constructor, methods, and properties here\n};\nfunction subclass() {}\nsubclass.prototype = Object.create(superclass.prototype, {\n  // Define the subclass constructor, methods, and properties here\n});\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.getownpropertydescriptors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertyDescriptors541550No411054545041106.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors\n

\n
\n", + "global_objects/object/getownpropertynames": "

Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.getOwnPropertyNames(obj)\n
\n

Parameters

\n
obj

The object whose enumerable and non-enumerable properties are to be returned.

Return value

\n

An array of strings that corresponds to the properties found directly in the given object.

Description

\n
\n

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in loop (or by Object.keys()) over the properties of the object. The non-negative integer keys of the object (both enumerable and non-enumerable) are added in ascending order to the array first, followed by the string keys in the order of insertion.

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be coerced to an object.

\n

js

\n
Object.getOwnPropertyNames(\"foo\");\n// TypeError: \"foo\" is not an object (ES5 code)\n\nObject.getOwnPropertyNames(\"foo\");\n// [\"0\", \"1\", \"2\", \"length\"]  (ES2015 code)\n
\n
\n

Examples

\n

Using Object.getOwnPropertyNames()

\n
\n
\n

js

\n
const arr = [\"a\", \"b\", \"c\"];\nconsole.log(Object.getOwnPropertyNames(arr).sort());\n// [\"0\", \"1\", \"2\", \"length\"]\n\n// Array-like object\nconst obj = { 0: \"a\", 1: \"b\", 2: \"c\" };\nconsole.log(Object.getOwnPropertyNames(obj).sort());\n// [\"0\", \"1\", \"2\"]\n\nObject.getOwnPropertyNames(obj).forEach((val, idx, array) => {\n  console.log(`${val} -> ${obj[val]}`);\n});\n// 0 -> a\n// 1 -> b\n// 2 -> c\n\n// non-enumerable property\nconst myObj = Object.create(\n  {},\n  {\n    getFoo: {\n      value() {\n        return this.foo;\n      },\n      enumerable: false,\n    },\n  },\n);\nmyObj.foo = 1;\n\nconsole.log(Object.getOwnPropertyNames(myObj).sort()); // [\"foo\", \"getFoo\"]\n
\n

If you want only the enumerable properties, see Object.keys() or use a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with Object.hasOwn()).

Items on the prototype chain are not listed:

\n

js

\n
function ParentClass() {}\nParentClass.prototype.inheritedMethod = function () {};\n\nfunction ChildClass() {\n  this.prop = 5;\n  this.method = function () {};\n}\nChildClass.prototype = new ParentClass();\nChildClass.prototype.prototypeMethod = function () {};\n\nconsole.log(Object.getOwnPropertyNames(new ChildClass()));\n// [\"prop\", \"method\"]\n
\n
\n

Get non-enumerable properties only

\n
\n

This uses the Array.prototype.filter() function to remove the enumerable keys (obtained with Object.keys()) from a list of all keys (obtained with Object.getOwnPropertyNames()) thus giving only the non-enumerable keys as output.

\n

js

\n
const target = myObject;\nconst enumAndNonenum = Object.getOwnPropertyNames(target);\nconst enumOnly = new Set(Object.keys(target));\nconst nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key));\n\nconsole.log(nonenumOnly);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.getownpropertynames
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertyNames512491254.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames\n

\n
\n", + "global_objects/object/getownpropertysymbols": "

Object.getOwnPropertySymbols()

The Object.getOwnPropertySymbols() static method returns an array of all symbol properties found directly upon a given object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.getOwnPropertySymbols(obj)\n
\n

Parameters

\n
obj

The object whose symbol properties are to be returned.

Return value

\n

An array of all symbol properties found directly upon the given object.

Description

\n
\n

Similar to Object.getOwnPropertyNames(), you can get all symbol properties of a given object as an array of symbols. Note that Object.getOwnPropertyNames() itself does not contain the symbol properties of an object and only the string properties.

As all objects have no own symbol properties initially, Object.getOwnPropertySymbols() returns an empty array unless you have set symbol properties on your object.

\n

Examples

\n

Using Object.getOwnPropertySymbols()

\n
\n

js

\n
const obj = {};\nconst a = Symbol(\"a\");\nconst b = Symbol.for(\"b\");\n\nobj[a] = \"localSymbol\";\nobj[b] = \"globalSymbol\";\n\nconst objectSymbols = Object.getOwnPropertySymbols(obj);\n\nconsole.log(objectSymbols.length); // 2\nconsole.log(objectSymbols); // [Symbol(a), Symbol(b)]\nconsole.log(objectSymbols[0]); // Symbol(a)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.getownpropertysymbols
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertySymbols381236No2593838362593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols\n

\n
\n", + "global_objects/object/is": "

Object.is()

The Object.is() static method determines whether two values are the same value.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.is(value1, value2)\n
\n

Parameters

\n
value1

The first value to compare.

value2

The second value to compare.

Return value

\n

A boolean indicating whether or not the two arguments are the same value.

Description

\n
\n

Object.is() determines whether two values are the same value. Two values are the same if one of the following holds:

Object.is() is not equivalent to the == operator. The == operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as \"\" == false being true), but Object.is() doesn't coerce either value.

Object.is() is also not equivalent to the === operator. The only difference between Object.is() and === is in their treatment of signed zeros and NaN values. The === operator (and the == operator) treats the number values -0 and +0 as equal, but treats NaN as not equal to each other.

\n

Examples

\n

Using Object.is()

\n
\n

js

\n
// Case 1: Evaluation result is the same as using ===\nObject.is(25, 25); // true\nObject.is(\"foo\", \"foo\"); // true\nObject.is(\"foo\", \"bar\"); // false\nObject.is(null, null); // true\nObject.is(undefined, undefined); // true\nObject.is(window, window); // true\nObject.is([], []); // false\nconst foo = { a: 1 };\nconst bar = { a: 1 };\nconst sameFoo = foo;\nObject.is(foo, foo); // true\nObject.is(foo, bar); // false\nObject.is(foo, sameFoo); // true\n\n// Case 2: Signed zero\nObject.is(0, -0); // false\nObject.is(+0, -0); // false\nObject.is(-0, -0); // true\n\n// Case 3: NaN\nObject.is(NaN, 0 / 0); // true\nObject.is(NaN, Number.NaN); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.is
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
is191222No1594.425221491.51.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n

\n
\n", + "global_objects/object/isextensible": "

Object.isExtensible()

The Object.isExtensible() static method determines if an object is extensible (whether it can have new properties added to it).

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.isExtensible(obj)\n
\n

Parameters

\n
obj

The object which should be checked.

Return value

\n

A Boolean indicating whether or not the given object is extensible.

Description

\n

Objects are extensible by default: they can have new properties added to them, and their [[Prototype]] can be re-assigned. An object can be marked as non-extensible using one of Object.preventExtensions(), Object.seal(), Object.freeze(), or Reflect.preventExtensions().

Examples

\n

Using Object.isExtensible

\n
\n

js

\n
// New objects are extensible.\nconst empty = {};\nObject.isExtensible(empty); // true\n\n// They can be made un-extensible\nObject.preventExtensions(empty);\nObject.isExtensible(empty); // false\n\n// Sealed objects are by definition non-extensible.\nconst sealed = Object.seal({});\nObject.isExtensible(sealed); // false\n\n// Frozen objects are also by definition non-extensible.\nconst frozen = Object.freeze({});\nObject.isExtensible(frozen); // false\n
\n

Non-object argument

\n
\n

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, it will return false without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

\n

js

\n
Object.isExtensible(1);\n// TypeError: 1 is not an object (ES5 code)\n\nObject.isExtensible(1);\n// false                         (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.isextensible
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isExtensible61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible\n

\n
\n", + "global_objects/object/isfrozen": "

Object.isFrozen()

The Object.isFrozen() static method determines if an object is frozen.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.isFrozen(obj)\n
\n

Parameters

\n
obj

The object which should be checked.

Return value

\n

A Boolean indicating whether or not the given object is frozen.

Description

\n

An object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable.

Examples

\n

Using Object.isFrozen

\n
\n

js

\n
// A new object is extensible, so it is not frozen.\nObject.isFrozen({}); // false\n\n// An empty object which is not extensible\n// is vacuously frozen.\nconst vacuouslyFrozen = Object.preventExtensions({});\nObject.isFrozen(vacuouslyFrozen); // true\n\n// A new object with one property is also extensible,\n// ergo not frozen.\nconst oneProp = { p: 42 };\nObject.isFrozen(oneProp); // false\n\n// Preventing extensions to the object still doesn't\n// make it frozen, because the property is still\n// configurable (and writable).\nObject.preventExtensions(oneProp);\nObject.isFrozen(oneProp); // false\n\n// Deleting that property makes the object vacuously frozen.\ndelete oneProp.p;\nObject.isFrozen(oneProp); // true\n\n// A non-extensible object with a non-writable\n// but still configurable property is not frozen.\nconst nonWritable = { e: \"plep\" };\nObject.preventExtensions(nonWritable);\nObject.defineProperty(nonWritable, \"e\", {\n  writable: false,\n}); // make non-writable\nObject.isFrozen(nonWritable); // false\n\n// Changing that property to non-configurable\n// then makes the object frozen.\nObject.defineProperty(nonWritable, \"e\", {\n  configurable: false,\n}); // make non-configurable\nObject.isFrozen(nonWritable); // true\n\n// A non-extensible object with a non-configurable\n// but still writable property also isn't frozen.\nconst nonConfigurable = { release: \"the kraken!\" };\nObject.preventExtensions(nonConfigurable);\nObject.defineProperty(nonConfigurable, \"release\", {\n  configurable: false,\n});\nObject.isFrozen(nonConfigurable); // false\n\n// Changing that property to non-writable\n// then makes the object frozen.\nObject.defineProperty(nonConfigurable, \"release\", {\n  writable: false,\n});\nObject.isFrozen(nonConfigurable); // true\n\n// A non-extensible object with a configurable\n// accessor property isn't frozen.\nconst accessor = {\n  get food() {\n    return \"yum\";\n  },\n};\nObject.preventExtensions(accessor);\nObject.isFrozen(accessor); // false\n\n// When we make that property non-configurable it becomes frozen.\nObject.defineProperty(accessor, \"food\", {\n  configurable: false,\n});\nObject.isFrozen(accessor); // true\n\n// But the easiest way for an object to be frozen\n// is if Object.freeze has been called on it.\nconst frozen = { 1: 81 };\nObject.isFrozen(frozen); // false\nObject.freeze(frozen);\nObject.isFrozen(frozen); // true\n\n// By definition, a frozen object is non-extensible.\nObject.isExtensible(frozen); // false\n\n// Also by definition, a frozen object is sealed.\nObject.isSealed(frozen); // true\n
\n

Non-object argument

\n
\n

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, it will return true without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

\n

js

\n
Object.isFrozen(1);\n// TypeError: 1 is not an object (ES5 code)\n\nObject.isFrozen(1);\n// true                          (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.isfrozen
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isFrozen61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen\n

\n
\n", + "global_objects/object/issealed": "

Object.isSealed()

The Object.isSealed() static method determines if an object is sealed.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.isSealed(obj)\n
\n

Parameters

\n
obj

The object which should be checked.

Return value

\n

A Boolean indicating whether or not the given object is sealed.

Description

\n

Returns true if the object is sealed, otherwise false. An object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable).

Examples

\n

Using Object.isSealed

\n
\n

js

\n
// Objects aren't sealed by default.\nconst empty = {};\nObject.isSealed(empty); // false\n\n// If you make an empty object non-extensible,\n// it is vacuously sealed.\nObject.preventExtensions(empty);\nObject.isSealed(empty); // true\n\n// The same is not true of a non-empty object,\n// unless its properties are all non-configurable.\nconst hasProp = { fee: \"fie foe fum\" };\nObject.preventExtensions(hasProp);\nObject.isSealed(hasProp); // false\n\n// But make them all non-configurable\n// and the object becomes sealed.\nObject.defineProperty(hasProp, \"fee\", {\n  configurable: false,\n});\nObject.isSealed(hasProp); // true\n\n// The easiest way to seal an object, of course,\n// is Object.seal.\nconst sealed = {};\nObject.seal(sealed);\nObject.isSealed(sealed); // true\n\n// A sealed object is, by definition, non-extensible.\nObject.isExtensible(sealed); // false\n\n// A sealed object might be frozen,\n// but it doesn't have to be.\nObject.isFrozen(sealed); // true\n// (all properties also non-writable)\n\nconst s2 = Object.seal({ p: 3 });\nObject.isFrozen(s2); // false\n// ('p' is still writable)\n\nconst s3 = Object.seal({\n  get p() {\n    return 0;\n  },\n});\nObject.isFrozen(s3); // true\n// (only configurability matters for accessor properties)\n
\n

Non-object argument

\n
\n

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, it will return true without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

\n

js

\n
Object.isSealed(1);\n// TypeError: 1 is not an object (ES5 code)\n\nObject.isSealed(1);\n// true                          (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.issealed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isSealed61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed\n

\n
\n", + "global_objects/object/preventextensions": "

Object.preventExtensions()

The Object.preventExtensions() static method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.preventExtensions(obj)\n
\n

Parameters

\n
obj

The object which should be made non-extensible.

Return value

\n

The object being made non-extensible.

Description

\n
\n

An object is extensible if new properties can be added to it. Object.preventExtensions() marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be deleted. Attempting to add new properties to a non-extensible object will fail, either silently or, in strict mode, throwing a TypeError.

Unlike Object.seal() and Object.freeze(), Object.preventExtensions() invokes an intrinsic JavaScript behavior and cannot be replaced with a composition of several other operations. It also has its Reflect counterpart (which only exists for intrinsic operations), Reflect.preventExtensions().

Object.preventExtensions() only prevents addition of own properties. Properties can still be added to the object prototype.

This method makes the [[Prototype]] of the target immutable; any [[Prototype]] re-assignment will throw a TypeError. This behavior is specific to the internal [[Prototype]] property; other properties of the target object will remain mutable.

There is no way to make an object extensible again once it has been made non-extensible.

\n

Examples

\n

Using Object.preventExtensions

\n
\n
\n

js

\n
// Object.preventExtensions returns the object\n// being made non-extensible.\nconst obj = {};\nconst obj2 = Object.preventExtensions(obj);\nobj === obj2; // true\n\n// Objects are extensible by default.\nconst empty = {};\nObject.isExtensible(empty); // true\n\n// They can be made un-extensible\nObject.preventExtensions(empty);\nObject.isExtensible(empty); // false\n\n// Object.defineProperty throws when adding\n// a new property to a non-extensible object.\nconst nonExtensible = { removable: true };\nObject.preventExtensions(nonExtensible);\nObject.defineProperty(nonExtensible, \"new\", {\n  value: 8675309,\n}); // throws a TypeError\n\n// In strict mode, attempting to add new properties\n// to a non-extensible object throws a TypeError.\nfunction fail() {\n  \"use strict\";\n  // throws a TypeError\n  nonExtensible.newProperty = \"FAIL\";\n}\nfail();\n
\n

A non-extensible object's prototype is immutable:

\n

js

\n
const fixed = Object.preventExtensions({});\n// throws a 'TypeError'.\nfixed.__proto__ = { oh: \"hai\" };\n
\n
\n

Non-object argument

\n
\n

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.

\n

js

\n
Object.preventExtensions(1);\n// TypeError: 1 is not an object (ES5 code)\n\nObject.preventExtensions(1);\n// 1                             (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.preventextensions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ES2015_behavior441235113194444353294.01.04.0.0
preventExtensions61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions\n

\n
\n", + "global_objects/object/seal": "

Object.seal()

The Object.seal() static method seals an object. Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. seal() returns the same object that was passed in.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.seal(obj)\n
\n

Parameters

\n
obj

The object which should be sealed.

Return value

\n

The object being sealed.

Description

\n
\n

Sealing an object is equivalent to preventing extensions and then changing all existing properties' descriptors to configurable: false. This has the effect of making the set of properties on the object fixed. Making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a TypeError (most commonly, although not exclusively, when in strict mode code).

The prototype chain remains untouched. However, due to the effect of preventing extensions, the [[Prototype]] cannot be reassigned.

Unlike Object.freeze(), objects sealed with Object.seal() may have their existing properties changed, as long as they are writable.

\n

Examples

\n

Using Object.seal

\n
\n

js

\n
const obj = {\n  prop() {},\n  foo: \"bar\",\n};\n\n// New properties may be added, existing properties\n// may be changed or removed.\nobj.foo = \"baz\";\nobj.lumpy = \"woof\";\ndelete obj.prop;\n\nconst o = Object.seal(obj);\n\no === obj; // true\nObject.isSealed(obj); // true\n\n// Changing property values on a sealed object\n// still works.\nobj.foo = \"quux\";\n\n// But you can't convert data properties to accessors,\n// or vice versa.\nObject.defineProperty(obj, \"foo\", {\n  get() {\n    return \"g\";\n  },\n}); // throws a TypeError\n\n// Now any changes, other than to property values,\n// will fail.\nobj.quaxxor = \"the friendly duck\";\n// silently doesn't add the property\ndelete obj.foo;\n// silently doesn't delete the property\n\n// ...and in strict mode such attempts\n// will throw TypeErrors.\nfunction fail() {\n  \"use strict\";\n  delete obj.foo; // throws a TypeError\n  obj.sparky = \"arf\"; // throws a TypeError\n}\nfail();\n\n// Attempted additions through\n// Object.defineProperty will also throw.\nObject.defineProperty(obj, \"ohai\", {\n  value: 17,\n}); // throws a TypeError\nObject.defineProperty(obj, \"foo\", {\n  value: \"eit\",\n}); // changes existing property value\n
\n

Non-object argument

\n
\n

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be returned as-is without any errors, since primitives are already, by definition, immutable.

\n

js

\n
Object.seal(1);\n// TypeError: 1 is not an object (ES5 code)\n\nObject.seal(1);\n// 1                             (ES2015 code)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.seal
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
seal61249125.14.41841251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal\n

\n
\n", + "global_objects/object/values": "

Object.values()

The Object.values() static method returns an array of a given object's own enumerable string-keyed property values.

\n

Try it

\n

Syntax

\n
\n

js

\n
Object.values(obj)\n
\n

Parameters

\n
obj

An object.

Return value

\n

An array containing the given object's own enumerable string-keyed property values.

Description

\n
\n

Object.values() returns an array whose elements are values of enumerable string-keyed properties found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.values() is the same as that provided by a for...in loop.

If you need the property keys, use Object.keys() instead. If you need both the property keys and values, use Object.entries() instead.

\n

Examples

\n

Using Object.values()

\n
\n

js

\n
const obj = { foo: \"bar\", baz: 42 };\nconsole.log(Object.values(obj)); // ['bar', 42]\n\n// Array-like object\nconst arrayLikeObj1 = { 0: \"a\", 1: \"b\", 2: \"c\" };\nconsole.log(Object.values(arrayLikeObj1)); // ['a', 'b', 'c']\n\n// Array-like object with random key ordering\n// When using numeric keys, the values are returned in the keys' numerical order\nconst arrayLikeObj2 = { 100: \"a\", 2: \"b\", 7: \"c\" };\nconsole.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']\n\n// getFoo is a non-enumerable property\nconst myObj = Object.create(\n  {},\n  {\n    getFoo: {\n      value() {\n        return this.foo;\n      },\n    },\n  },\n);\nmyObj.foo = \"bar\";\nconsole.log(Object.values(myObj)); // ['bar']\n
\n

Using Object.values() on primitives

\n
\n

Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.

\n

js

\n
// Strings have indices as enumerable own properties\nconsole.log(Object.values(\"foo\")); // ['f', 'o', 'o']\n\n// Other primitives have no own properties\nconsole.log(Object.values(100)); // []\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-object.values
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
values541447No4110.15454474110.36.01.07.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values\n

\n
\n", + "global_objects/function/function": "

Function() constructor

The Function() constructor creates Function objects. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval(). However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Function(functionBody)\nnew Function(arg1, functionBody)\nnew Function(arg1, arg2, functionBody)\nnew Function(arg1, arg2, /* …, */ argN, functionBody)\n\nFunction(functionBody)\nFunction(arg1, functionBody)\nFunction(arg1, arg2, functionBody)\nFunction(arg1, arg2, /* …, */ argN, functionBody)\n
\n

Note: Function() can be called with or without new. Both create a new Function instance.

\n

Parameters

\n
\narg1, …, argN Optional\n

Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain identifier, rest parameter, or destructured parameter, optionally with a default), or a list of such strings separated with commas.

As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: \"x\", \"theValue = 42\", \"[a, b] /* numbers */\" — or \"x, theValue = 42, [a, b] /* numbers */\". (\"x, theValue = 42\", \"[a, b]\" is also correct, though very confusing to read.)

functionBody

A string containing the JavaScript statements comprising the function definition.

Description

\n
\n

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than creating a function with a function expression or function declaration and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion:

\n

js

\n
`function anonymous(${args.join(\",\")}\n) {\n${functionBody}\n}`;\n
\n

This is observable by calling the function's toString() method.

However, unlike normal function expressions, the name anonymous is not added to the functionBody's scope, since functionBody only has access the global scope. If functionBody is not in strict mode (the body itself needs to have the \"use strict\" directive since it doesn't inherit the strictness from the context), you may use arguments.callee to refer to the function itself. Alternatively, you can define the recursive part as an inner function:

\n

js

\n
const recursiveFn = new Function(\n  \"count\",\n  `\n(function recursiveFn(count) {\n  if (count < 0) {\n    return;\n  }\n  console.log(count);\n  recursiveFn(count - 1);\n})(count);\n`,\n);\n
\n

Note that the two dynamic parts of the assembled source — the parameters list args.join(\",\") and functionBody — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts.

\n

js

\n
new Function(\"/*\", \"*/) {\");\n// SyntaxError: Unexpected end of arg string\n// Doesn't become \"function anonymous(/*) {*/) {}\"\n
\n
\n

Examples

\n

Specifying arguments with the Function constructor

\n
\n

The following code creates a Function object that takes two arguments.

\n

js

\n
// Example can be run directly in your JavaScript console\n\n// Create a function that takes two arguments, and returns the sum of those arguments\nconst adder = new Function(\"a\", \"b\", \"return a + b\");\n\n// Call the function\nadder(2, 6);\n// 8\n
\n

The arguments a and b are formal argument names that are used in the function body, return a + b.

\n

Creating a function object from a function declaration or function expression

\n
\n

js

\n
// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name\n\n// Observe that new Function is called. This is so we can call the function we created directly afterwards\nconst sumOfArray = new Function(\n  \"const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray\",\n)();\n\n// call the function\nsumOfArray([1, 2, 3, 4]);\n// 10\n\n// If you don't call new Function at the point of creation, you can use the Function.call() method to call it\nconst findLargestNumber = new Function(\n  \"function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber\",\n);\n\n// call the function\nfindLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]);\n// 8\n\n// Function declarations do not require a return statement\nconst sayHello = new Function(\n  \"return function (name) { return `Hello, ${name}` }\",\n)();\n\n// call the function\nsayHello(\"world\");\n// Hello, world\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Function11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function\n

\n
\n", + "global_objects/function/arguments": "

Function.prototype.arguments

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Note: The arguments property of Function objects is deprecated. The recommended way to access the arguments object is to refer to the variable arguments available within functions.

The arguments accessor property of Function instances returns the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError.

\n
\n

Description

\n
\n

The value of arguments is an array-like object corresponding to the arguments passed to a function.

In the case of recursion, i.e. if function f appears several times on the call stack, the value of f.arguments represents the arguments corresponding to the most recent invocation of the function.

The value of the arguments property is normally null if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned).

Note that the only behavior specified by the ECMAScript specification is that Function.prototype has an initial arguments accessor that unconditionally throws a TypeError for any get or set request (known as a \"poison pill accessor\"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions. The actual behavior of the arguments property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill Function.prototype.arguments accessor to specially handle this values that are non-strict functions.

\n

js

\n
(function f() {\n  if (Object.hasOwn(f, \"arguments\")) {\n    console.log(\n      \"arguments is an own property with descriptor\",\n      Object.getOwnPropertyDescriptor(f, \"arguments\"),\n    );\n  } else {\n    console.log(\n      \"f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments\",\n    );\n    console.log(\n      Object.getOwnPropertyDescriptor(\n        Object.getPrototypeOf(f),\n        \"arguments\",\n      ).get.call(f),\n    );\n  }\n})();\n\n// In Chrome:\n// arguments is an own property with descriptor {value: Arguments(0), writable: false, enumerable: false, configurable: false}\n\n// In Firefox:\n// f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments\n// Arguments { … }\n
\n
\n

Examples

\n

Using the arguments property

\n
\n

js

\n
function f(n) {\n  g(n - 1);\n}\n\nfunction g(n) {\n  console.log(`before: ${g.arguments[0]}`);\n  if (n > 0) {\n    f(n);\n  }\n  console.log(`after: ${g.arguments[0]}`);\n}\n\nf(2);\n\nconsole.log(`returned: ${g.arguments}`);\n\n// Logs:\n// before: 1\n// before: 0\n// after: 0\n// after: 1\n// returned: null\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
arguments11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments\n

\n
\n", + "global_objects/function/caller": "

Function.prototype.caller

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: In strict mode, accessing caller of a function throws an error — the API is removed with no replacement. This is to prevent code from being able to \"walk the stack\", which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read the rationale for the deprecation of arguments.callee.

The caller accessor property of Function instances returns the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError.

\n
\n

Description

\n
\n

If the function f was invoked by the top-level code, the value of f.caller is null; otherwise it's the function that called f. If the function that called f is a strict mode function, the value of f.caller is also null.

Note that the only behavior specified by the ECMAScript specification is that Function.prototype has an initial caller accessor that unconditionally throws a TypeError for any get or set request (known as a \"poison pill accessor\"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the caller property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill Function.prototype.caller accessor to specially handle this values that are non-strict functions.

\n

js

\n
(function f() {\n  if (Object.hasOwn(f, \"caller\")) {\n    console.log(\n      \"caller is an own property with descriptor\",\n      Object.getOwnPropertyDescriptor(f, \"caller\"),\n    );\n  } else {\n    console.log(\n      \"f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller\",\n    );\n    console.log(\n      Object.getOwnPropertyDescriptor(\n        Object.getPrototypeOf(f),\n        \"caller\",\n      ).get.call(f),\n    );\n  }\n})();\n\n// In Chrome:\n// caller is an own property with descriptor {value: null, writable: false, enumerable: false, configurable: false}\n\n// In Firefox:\n// f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller\n// null\n
\n

This property replaces the obsolete arguments.caller property of the arguments object.

The special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.

\n

Examples

\n

Checking the value of a function's caller property

\n
\n

The following code checks the value a function's caller property.

\n

js

\n
function myFunc() {\n  if (myFunc.caller === null) {\n    return \"The function was called from the top!\";\n  } else {\n    return `This function's caller was ${myFunc.caller}`;\n  }\n}\n
\n
\n

Reconstructing the stack and recursion

\n
\n

Note that in case of recursion, you can't reconstruct the call stack using this property. Consider:

\n

js

\n
function f(n) {\n  g(n - 1);\n}\nfunction g(n) {\n  if (n > 0) {\n    f(n);\n  } else {\n    stop();\n  }\n}\nf(2);\n
\n

At the moment stop() is called the call stack will be:

f(2) -> g(1) -> f(1) -> g(0) -> stop()\n

The following is true:

\n

js

\n
stop.caller === g && f.caller === g && g.caller === f;\n
\n

so if you tried to get the stack trace in the stop() function like this:

\n

js

\n
let f = stop;\nlet stack = \"Stack trace:\";\nwhile (f) {\n  stack += `\\n${f.name}`;\n  f = f.caller;\n}\n
\n

the loop would never stop.

\n

Strict mode caller

\n
\n

If the caller is a strict mode function, the value of caller is null.

\n

js

\n
function callerFunc() {\n  calleeFunc();\n}\n\nfunction strictCallerFunc() {\n  \"use strict\";\n  calleeFunc();\n}\n\nfunction calleeFunc() {\n  console.log(calleeFunc.caller);\n}\n\n(function () {\n  callerFunc();\n})();\n// Logs [Function: callerFunc]\n\n(function () {\n  strictCallerFunc();\n})();\n// Logs null\n
\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
caller112189.634.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\n

\n
\n", + "global_objects/function/displayname": "

Function: displayName

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The optional displayName property of a Function instance specifies the display name of the function.

\n
\n

Value

\n

The displayName property is not initially present on any function — it's added by the code authors. For the purpose of display, it should be a string.

Description

\n
\n

The displayName property, if present, may be preferred by consoles and profilers over the name property to be displayed as the name of a function.

Among browsers, only the Firefox console utilizes this property. React devtools also use the displayName property when displaying the component tree.

Firefox does some basic attempts to decode the displayName that's possibly generated by the anonymous JavaScript functions naming convention algorithm. The following patterns are detected:

If none of the above patterns match, the entire displayName is displayed.

\n

Examples

\n

Setting a displayName

\n
\n

By entering the following in a Firefox console, it should display as something like function MyFunction():

\n

js

\n
const a = function () {};\na.displayName = \"MyFunction\";\n\na; // function MyFunction()\n
\n
\n

Changing displayName dynamically

\n
\n

You can dynamically change the displayName of a function:

\n

js

\n
const object = {\n  // anonymous\n  someMethod: function someMethod(value) {\n    someMethod.displayName = `someMethod (${value})`;\n  },\n};\n\nconsole.log(object.someMethod.displayName); // undefined\n\nobject.someMethod(\"123\");\nconsole.log(object.someMethod.displayName); // \"someMethod (123)\"\n
\n
\n

Cleaning of displayName

\n
\n

Firefox devtools would clean up a few common patterns in the displayName property before displaying it.

\n

js

\n
function foo() {}\n\nfunction testName(name) {\n  foo.displayName = name;\n  console.log(foo);\n}\n\ntestName(\"$foo$\"); // function $foo$()\ntestName(\"foo bar\"); // function bar()\ntestName(\"Foo.prototype.add\"); // function add()\ntestName(\"foo .\"); // function foo .()\ntestName(\"foo <\"); // function foo <()\ntestName(\"foo?\"); // function foo?()\ntestName(\"foo()\"); // function foo()()\n\ntestName(\"[...]\"); // function ...()\ntestName(\"foo<\"); // function foo()\ntestName(\"foo...\"); // function foo()\ntestName(\"foo(^)\"); // function foo()\n
\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
displayNameNoNo13NoNoNoNoNo14NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/displayName\n

\n
\n", + "global_objects/function/length": "

Function: length

The length data property of a Function instance indicates the number of parameters expected by the function.

\n

Try it

\n

Value

\n
\n

A number.

\n
Property attributes of Function: length\n
Writable no
Enumerable no
Configurable yes
\n

Description

\n
\n

A Function object's length property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function.

The Function constructor is itself a Function object. Its length data property has a value of 1.

Due to historical reasons, Function.prototype is a callable itself. The length property of Function.prototype has a value of 0.

\n

Examples

\n

Using function length

\n
\n

js

\n
console.log(Function.length); // 1\n\nconsole.log((() => {}).length); // 0\nconsole.log(((a) => {}).length); // 1\nconsole.log(((a, b) => {}).length); // 2 etc.\n\nconsole.log(((...args) => {}).length);\n// 0, rest parameter is not counted\n\nconsole.log(((a, b = 1, c) => {}).length);\n// 1, only parameters before the first one with\n// a default value are counted\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-instances-length
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
length11214314.418410.111.01.00.10.0
configurable_true431237No301043433730104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length\n

\n
\n", + "global_objects/function/name": "

Function: name

The name data property of a Function instance indicates the function's name as specified when it was created, or it may be either anonymous or '' (an empty string) for functions created anonymously.

\n

Try it

\n

Value

\n
\n

A string.

\n
Property attributes of Function: name\n
Writable no
Enumerable no
Configurable yes

Note: In non-standard, pre-ES2015 implementations the configurable attribute was false as well.

\n

Description

\n
\n

The function's name property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.

The name property is read-only and cannot be changed by the assignment operator:

\n

js

\n
function someFunction() {}\n\nsomeFunction.name = \"otherFunction\";\nconsole.log(someFunction.name); // someFunction\n
\n

To change it, use Object.defineProperty().

The name property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.

\n

Function declaration

\n
\n

The name property returns the name of a function declaration.

\n

js

\n
function doSomething() {}\ndoSomething.name; // \"doSomething\"\n
\n
\n

Default-exported function declaration

\n
\n

An export default declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is \"default\".

\n

js

\n
// -- someModule.js --\nexport default function () {}\n\n// -- main.js --\nimport someModule from \"./someModule.js\";\n\nsomeModule.name; // \"default\"\n
\n
\n

Function constructor

\n
\n

Functions created with the Function() constructor have name \"anonymous\".

\n

js

\n
new Function().name; // \"anonymous\"\n
\n
\n

Function expression

\n
\n

If the function expression is named, that name is used as the name property.

\n

js

\n
const someFunction = function someFunctionName() {};\nsomeFunction.name; // \"someFunctionName\"\n
\n

Anonymous function expressions created using the keyword function or arrow functions would have \"\" (an empty string) as their name.

\n

js

\n
(function () {}).name; // \"\"\n(() => {}).name; // \"\"\n
\n

However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate.

One practical case where the name cannot be inferred is a function returned from another function:

\n

js

\n
function getFoo() {\n  return () => {};\n}\ngetFoo().name; // \"\"\n
\n
\n

Variable declaration and method

\n
\n

Variables and methods can infer the name of an anonymous function from its syntactic position.

\n

js

\n
const f = function () {};\nconst object = {\n  someMethod: function () {},\n};\n\nconsole.log(f.name); // \"f\"\nconsole.log(object.someMethod.name); // \"someMethod\"\n
\n

The same applies to assignment:

\n

js

\n
let f;\nf = () => {};\nf.name; // \"f\"\n
\n
\n

Initializer and default value

\n
\n

Functions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their name.

\n

js

\n
const [f = () => {}] = [];\nf.name; // \"f\"\n\nconst { someMethod: m = () => {} } = {};\nm.name; // \"m\"\n\nfunction foo(f = () => {}) {\n  console.log(f.name);\n}\nfoo(); // \"f\"\n\nclass Foo {\n  static someMethod = () => {};\n}\nFoo.someMethod.name; // someMethod\n
\n
\n

Shorthand method

\n
\n

js

\n
const o = {\n  foo() {},\n};\no.foo.name; // \"foo\";\n
\n

Bound function

\n
\n

Function.prototype.bind() produces a function whose name is \"bound \" plus the function name.

\n

js

\n
function foo() {}\nfoo.bind({}).name; // \"bound foo\"\n
\n
\n

Getter and setter

\n
\n

When using get and set accessor properties, \"get\" or \"set\" will appear in the function name.

\n

js

\n
const o = {\n  get foo() {},\n  set foo(x) {},\n};\n\nconst descriptor = Object.getOwnPropertyDescriptor(o, \"foo\");\ndescriptor.get.name; // \"get foo\"\ndescriptor.set.name; // \"set foo\";\n
\n
\n

Class

\n
\n

A class's name follows the same algorithm as function declarations and expressions.

\n

js

\n
class Foo {}\nFoo.name; // \"Foo\"\n
\n

Warning: JavaScript will set the function's name property only if a function does not have an own property called name. However, classes' static members will be set as own properties of the class constructor function, and thus prevent the built-in name from being applied. See an example below.

\n

Symbol as function name

\n
\n

If a Symbol is used a function name and the symbol has a description, the method's name is the description in square brackets.

\n

js

\n
const sym1 = Symbol(\"foo\");\nconst sym2 = Symbol();\n\nconst o = {\n  [sym1]() {},\n  [sym2]() {},\n};\n\no[sym1].name; // \"[foo]\"\no[sym2].name; // \"[]\"\n
\n
\n

Private property

\n
\n

Private fields and private methods have the hash (#) as part of their names.

\n

js

\n
class Foo {\n  #field = () => {};\n  #method() {}\n  getNames() {\n    console.log(this.#field.name);\n    console.log(this.#method.name);\n  }\n}\n\nnew Foo().getNames();\n// \"#field\"\n// \"#method\"\n
\n
\n

Examples

\n

Telling the constructor name of an object

\n
\n

You can use obj.constructor.name to check the \"class\" of an object.

\n

js

\n
function Foo() {} // Or: class Foo {}\n\nconst fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // \"Foo\"\n
\n

However, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a static method property name():

\n

js

\n
class Foo {\n  constructor() {}\n  static name() {}\n}\n
\n

With a static name() method Foo.name no longer holds the actual class name but a reference to the name() function object. Trying to obtain the class of fooInstance via fooInstance.constructor.name won't give us the class name at all, but instead a reference to the static class method. Example:

\n

js

\n
const fooInstance = new Foo();\nconsole.log(fooInstance.constructor.name); // ƒ name() {}\n
\n

Due to the existence of static fields, name may not be a function either.

\n

js

\n
class Foo {\n  static name = 123;\n}\nconsole.log(new Foo().constructor.name); // 123\n
\n

If a class has a static property called name, it will also become writable. The built-in definition in the absence of a custom static definition is read-only:

\n

js

\n
Foo.name = \"Hello\";\nconsole.log(Foo.name); // \"Hello\" if class Foo has a static \"name\" property, but \"Foo\" if not.\n
\n

Therefore you may not rely on the built-in name property to always hold a class's name.

\n

JavaScript compressors and minifiers

\n
\n

Warning: Be careful when using the name property with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time.

Source code such as:

\n

js

\n
function Foo() {}\nconst foo = new Foo();\n\nif (foo.constructor.name === \"Foo\") {\n  console.log(\"'foo' is an instance of 'Foo'\");\n} else {\n  console.log(\"Oops!\");\n}\n
\n

may be compressed to:

\n

js

\n
function a() {}\nconst b = new a();\nif (b.constructor.name === \"Foo\") {\n  console.log(\"'foo' is an instance of 'Foo'\");\n} else {\n  console.log(\"Oops!\");\n}\n
\n

In the uncompressed version, the program runs into the truthy branch and logs \"'foo' is an instance of 'Foo'\" — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the name property, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-instances-name
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
name15141No10.564.41841161.01.00.10.0
configurable_true431438No301043433830104.01.04.0.0
inferred_names5179
14–79Names for functions defined in a dictionary are properly assigned; however, anonymous functions defined on a var/let variable assignment have blank names.
\n
53No381051515341105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name\n

\n
\n", + "global_objects/function/prototype": "

Function: prototype

\n

The prototype data property of a Function instance is used when the function is used as a constructor with the new operator. It will become the new object's prototype.

Note: Not all Function objects have the prototype property — see description.

\n
\n

Value

\n
\n

An object.

\n
Property attributes of Function: prototype\n
Writable yes
Enumerable no
Configurable no

Note: The prototype property of classes is not writable.

\n

Description

\n
\n

When a function is called with new, the constructor's prototype property will become the resulting object's prototype.

\n

js

\n
function Ctor() {}\nconst inst = new Ctor();\nconsole.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true\n
\n

You can read Inheritance and the prototype chain for more information about the interactions between a constructor function's prototype property and the resulting object's prototype.

A function having a prototype property is not sufficient for it to be eligible as a constructor. Generator functions have a prototype property, but cannot be called with new:

\n

js

\n
async function* asyncGeneratorFunction() {}\nfunction* generatorFunction() {}\n
\n

Instead, generator functions' prototype property is used when they are called without new. The prototype property will become the returned Generator object's prototype.

In addition, some functions may have a prototype but throw unconditionally when called with new. For example, the Symbol() and BigInt() functions throw when called with new, because Symbol.prototype and BigInt.prototype are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed.

The following functions do not have prototype, and are therefore ineligible as constructors, even if a prototype property is later manually assigned:

\n

js

\n
const method = { foo() {} }.foo;\nconst arrowFunction = () => {};\nasync function asyncFunction() {}\n
\n

The following are valid constructors that have prototype:

\n

js

\n
class Class {}\nfunction fn() {}\n
\n

A bound function does not have a prototype property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance.

\n

js

\n
const boundFunction = function () {}.bind(null);\n
\n

A function's prototype property, by default, is a plain object with one property: constructor, which is a reference to the function itself. The constructor property is writable, non-enumerable, and configurable.

If the prototype of a function is reassigned with something other than an Object, when the function is called with new, the returned object's prototype would be Object.prototype instead. (In other words, new ignores the prototype property and constructs a plain object.)

\n

js

\n
function Ctor() {}\nCtor.prototype = 3;\nconsole.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true\n
\n
\n

Examples

\n

Changing the prototype of all instances by mutating the prototype property

\n
\n

js

\n
function Ctor() {}\nconst p1 = new Ctor();\nconst p2 = new Ctor();\nCtor.prototype.prop = 1;\nconsole.log(p1.prop); // 1\nconsole.log(p2.prop); // 1\n
\n

Adding a non-method property to a class's prototype property

\n
\n

Class fields add properties to each instance. Class methods declare function properties on the prototype. However, there's no way to add a non-function property to the prototype. In case you want to share static data between all instances (for example, Error.prototype.name is the same between all error instances), you can manually assign it on the prototype of a class.

\n

js

\n
class Dog {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\nDog.prototype.species = \"dog\";\n\nconsole.log(new Dog(\"Jack\").species); // \"dog\"\n
\n

This can be made more ergonomic using static initialization blocks, which are called when the class is initialized.

\n

js

\n
class Dog {\n  static {\n    Dog.prototype.species = \"dog\";\n  }\n  constructor(name) {\n    this.name = name;\n  }\n}\n\nconsole.log(new Dog(\"Jack\").species); // \"dog\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function-instances-prototype
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype\n

\n
\n", + "global_objects/function/apply": "

Function.prototype.apply()

The apply() method of Function instances calls this function with a given this value, and arguments provided as an array (or an array-like object).

\n

Try it

\n

Syntax

\n
\n

js

\n
apply(thisArg)\napply(thisArg, argsArray)\n
\n

Parameters

\n
thisArg

The value of this provided for the call to func. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

\nargsArray Optional\n

An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function.

Return value

\n

The result of calling the function with the specified this value and arguments.

Description

\n
\n

Note: This function is almost identical to call(), except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array — for example, func.call(this, \"eat\", \"bananas\") vs. func.apply(this, [\"eat\", \"bananas\"]).

Normally, when calling a function, the value of this inside the function is the object that the function was accessed on. With apply(), you can assign an arbitrary value as this when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

You can also use any kind of object which is array-like as the second parameter. In practice, this means that it needs to have a length property, and integer (\"index\") properties in the range (0..length - 1). For example, you could use a NodeList, or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }. You can also use arguments, for example:

\n

js

\n
function wrapper() {\n  return anotherFn.apply(null, arguments);\n}\n
\n

With the rest parameters and parameter spread syntax, this can be rewritten as:

\n

js

\n
function wrapper(...args) {\n  return anotherFn(...args);\n}\n
\n

In general, fn.apply(null, args) is equivalent to fn(...args) with the parameter spread syntax, except args is expected to be an array-like object in the former case with apply(), and an iterable object in the latter case with spread syntax.

Warning: Do not use apply() to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means new.target is undefined, and classes throw an error because they can't be called without new. Use Reflect.construct() or extends instead.

\n

Examples

\n

Using apply() to append an array to another

\n
\n

You can use Array.prototype.push() to append an element to an array. Because push() accepts a variable number of arguments, you can also push multiple elements at once. But if you pass an array to push(), it will actually add that array as a single element, instead of adding the elements individually, ending up with an array inside an array. On the other hand, Array.prototype.concat() does have the desired behavior in this case, but it does not append to the existing array — it creates and returns a new array.

In this case, you can use apply to implicitly \"spread\" an array as a series of arguments.

\n

js

\n
const array = [\"a\", \"b\"];\nconst elements = [0, 1, 2];\narray.push.apply(array, elements);\nconsole.info(array); // [\"a\", \"b\", 0, 1, 2]\n
\n

The same effect can be achieved with the spread syntax.

\n

js

\n
const array = [\"a\", \"b\"];\nconst elements = [0, 1, 2];\narray.push(...elements);\nconsole.info(array); // [\"a\", \"b\", 0, 1, 2]\n
\n
\n

Using apply() and built-in functions

\n
\n

Clever usage of apply() allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax).

For example, we can use Math.max() and Math.min() to find out the maximum and minimum value in an array.

\n

js

\n
// min/max number in an array\nconst numbers = [5, 6, 2, 3, 7];\n\n// using Math.min/Math.max apply\nlet max = Math.max.apply(null, numbers);\n// This about equal to Math.max(numbers[0], …)\n// or Math.max(5, 6, …)\n\nlet min = Math.min.apply(null, numbers);\n\n// vs. simple loop based algorithm\nmax = -Infinity;\nmin = +Infinity;\n\nfor (let i = 0; i < numbers.length; i++) {\n  if (numbers[i] > max) {\n    max = numbers[i];\n  }\n  if (numbers[i] < min) {\n    min = numbers[i];\n  }\n}\n
\n

But beware: by using apply() (or the spread syntax) with an arbitrarily long arguments list, you run the risk of exceeding the JavaScript engine's argument length limit.

The consequences of calling a function with too many arguments (that is, more than tens of thousands of arguments) is unspecified and varies across engines. (The JavaScriptCore engine has a hard-coded argument limit of 65536.) Most engines throw an exception; but there's no normative specification preventing other behaviors, such as arbitrarily limiting the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.

If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:

\n

js

\n
function minOfArray(arr) {\n  let min = Infinity;\n  const QUANTUM = 32768;\n\n  for (let i = 0; i < arr.length; i += QUANTUM) {\n    const submin = Math.min.apply(\n      null,\n      arr.slice(i, Math.min(i + QUANTUM, arr.length)),\n    );\n    min = Math.min(submin, min);\n  }\n\n  return min;\n}\n\nconst min = minOfArray([5, 6, 2, 3, 7]);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function.prototype.apply
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
apply11215.5414.418410.111.01.00.10.0
generic_arrays_as_arguments17124956≤3718410.161.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\n

\n
\n", + "global_objects/function/bind": "

Function.prototype.bind()

The bind() method of Function instances creates a new function that, when called, calls this function with its this keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

\n

Try it

\n

Syntax

\n
\n

js

\n
bind(thisArg)\nbind(thisArg, arg1)\nbind(thisArg, arg1, arg2)\nbind(thisArg, arg1, arg2, /* …, */ argN)\n
\n

Parameters

\n
thisArg

The value to be passed as the this parameter to the target function func when the bound function is called. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the new operator.

\narg1, …, argN Optional\n

Arguments to prepend to arguments provided to the bound function when invoking func.

Return value

\n

A copy of the given function with the specified this value, and initial arguments (if provided).

Description

\n
\n

The bind() function creates a new bound function. Calling the bound function generally results in the execution of the function it wraps, which is also called the target function. The bound function will store the parameters passed — which include the value of this and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see const boundFn = fn.bind(thisArg, arg1, arg2) as being equivalent to const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs) for the effect when it's called (but not when boundFn is constructed).

A bound function can be further bound by calling boundFn.bind(thisArg, /* more args */), which creates another bound function boundFn2. The newly bound thisArg value is ignored, because the target function of boundFn2, which is boundFn, already has a bound this. When boundFn2 is called, it would call boundFn, which in turn calls fn. The arguments that fn ultimately receives are, in order: the arguments bound by boundFn, arguments bound by boundFn2, and the arguments received by boundFn2.

\n

js

\n
\"use strict\"; // prevent `this` from being boxed into the wrapper object\n\nfunction log(...args) {\n  console.log(this, ...args);\n}\nconst boundLog = log.bind(\"this value\", 1, 2);\nconst boundLog2 = boundLog.bind(\"new this value\", 3, 4);\nboundLog2(5, 6); // \"this value\", 1, 2, 3, 4, 5, 6\n
\n

A bound function may also be constructed using the new operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided this value is ignored (because construction prepares its own this, as seen by the parameters of Reflect.construct). If the bound function is directly constructed, new.target will be the target function instead. (That is, the bound function is transparent to new.target.)

\n

js

\n
class Base {\n  constructor(...args) {\n    console.log(new.target === Base);\n    console.log(args);\n  }\n}\n\nconst BoundBase = Base.bind(null, 1, 2);\n\nnew BoundBase(3, 4); // true, [1, 2, 3, 4]\n
\n

However, because a bound function does not have the prototype property, it cannot be used as a base class for extends.

\n

js

\n
class Derived extends class {}.bind(null) {}\n// TypeError: Class extends value does not have valid prototype property undefined\n
\n

When using a bound function as the right-hand side of instanceof, instanceof would reach for the target function (which is stored internally in the bound function) and read its prototype instead.

\n

js

\n
class Base {}\nconst BoundBase = Base.bind(null, 1, 2);\nconsole.log(new Base() instanceof BoundBase); // true\n
\n

The bound function has the following properties:

length

The length of the target function minus the number of arguments being bound (not counting the thisArg parameter), with 0 being the minimum value.

name

The name of the target function plus a \"bound \" prefix.

The bound function also inherits the prototype chain of the target function. However, it doesn't have other own properties of the target function (such as static properties if the target function is a class).

\n

Examples

\n

Creating a bound function

\n
\n

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).

Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

\n

js

\n
// Top-level 'this' is bound to 'globalThis' in scripts.\nthis.x = 9;\nconst module = {\n  x: 81,\n  getX() {\n    return this.x;\n  },\n};\n\n// The 'this' parameter of 'getX' is bound to 'module'.\nconsole.log(module.getX()); // 81\n\nconst retrieveX = module.getX;\n// The 'this' parameter of 'retrieveX' is bound to 'globalThis' in non-strict mode.\nconsole.log(retrieveX()); // 9\n\n// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.\nconst boundGetX = retrieveX.bind(module);\nconsole.log(boundGetX()); // 81\n
\n

Note: If you run this example in strict mode, the this parameter of retrieveX will be bound to undefined instead of globalThis, causing the retrieveX() call to fail.

If you run this example in an ECMAScript module, top-level this will be bound to undefined instead of globalThis, causing the this.x = 9 assignment to fail.

If you run this example in a Node CommonJS module, top-level this will be bound to module.exports instead of globalThis. However, the this parameter of retrieveX will still be bound to globalThis in non-strict mode and to undefined in strict mode. Therefore, in non-strict mode (the default), the retrieveX() call will return undefined because this.x = 9 is writing to a different object (module.exports) from what getX is reading from (globalThis).

In fact, some built-in \"methods\" are also getters that return bound functions — one notable example being Intl.NumberFormat.prototype.format(), which, when accessed, returns a bound function that you can directly pass as a callback.

\n

Partially applied functions

\n
\n

The next simplest use of bind() is to make a function with pre-specified initial arguments.

These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed to the bound function at the time it is called.

\n

js

\n
function list(...args) {\n  return args;\n}\n\nfunction addArguments(arg1, arg2) {\n  return arg1 + arg2;\n}\n\nconsole.log(list(1, 2, 3)); // [1, 2, 3]\n\nconsole.log(addArguments(1, 2)); // 3\n\n// Create a function with a preset leading argument\nconst leadingThirtySevenList = list.bind(null, 37);\n\n// Create a function with a preset first argument.\nconst addThirtySeven = addArguments.bind(null, 37);\n\nconsole.log(leadingThirtySevenList()); // [37]\nconsole.log(leadingThirtySevenList(1, 2, 3)); // [37, 1, 2, 3]\nconsole.log(addThirtySeven(5)); // 42\nconsole.log(addThirtySeven(5, 10)); // 42\n// (the last argument 10 is ignored)\n
\n
\n

With setTimeout()

\n
\n

By default, within setTimeout(), the this keyword will be set to globalThis, which is window in browsers. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.

\n

js

\n
class LateBloomer {\n  constructor() {\n    this.petalCount = Math.floor(Math.random() * 12) + 1;\n  }\n  bloom() {\n    // Declare bloom after a delay of 1 second\n    setTimeout(this.declare.bind(this), 1000);\n  }\n  declare() {\n    console.log(`I am a beautiful flower with ${this.petalCount} petals!`);\n  }\n}\n\nconst flower = new LateBloomer();\nflower.bloom();\n// After 1 second, calls 'flower.declare()'\n
\n

You can also use arrow functions for this purpose.

\n

js

\n
class LateBloomer {\n  bloom() {\n    // Declare bloom after a delay of 1 second\n    setTimeout(() => this.declare(), 1000);\n  }\n}\n
\n
\n

Bound functions used as constructors

\n
\n

Bound functions are automatically suitable for use with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. However, provided arguments are still prepended to the constructor call.

\n

js

\n
function Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\n\nPoint.prototype.toString = function () {\n  return `${this.x},${this.y}`;\n};\n\nconst p = new Point(1, 2);\np.toString();\n// '1,2'\n\n// The thisArg's value doesn't matter because it's ignored\nconst YAxisPoint = Point.bind(null, 0 /*x*/);\n\nconst axisPoint = new YAxisPoint(5);\naxisPoint.toString(); // '0,5'\n\naxisPoint instanceof Point; // true\naxisPoint instanceof YAxisPoint; // true\nnew YAxisPoint(17, 42) instanceof Point; // true\n
\n

Note that you need not do anything special to create a bound function for use with new. new.target, instanceof, this etc. all work as expected, as if the constructor was never bound. The only difference is that it can no longer be used for extends.

The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using new. If you call it without new, the bound this is suddenly not ignored.

\n

js

\n
const emptyObj = {};\nconst YAxisPoint = Point.bind(emptyObj, 0 /*x*/);\n\n// Can still be called as a normal function\n// (although usually this is undesirable)\nYAxisPoint(13);\n\n// The modifications to `this` is now observable from the outside\nconsole.log(emptyObj); // { x: 0, y: 13 }\n
\n

If you wish to restrict a bound function to only be callable with new, or only be callable without new, the target function must enforce that restriction, such as by checking new.target !== undefined or using a class instead.

\n

Binding classes

\n
\n

Using bind() on classes preserves most of the class's semantics, except that all static own properties of the current class are lost. However, because the prototype chain is preserved, you can still access static properties inherited from the parent class.

\n

js

\n
class Base {\n  static baseProp = \"base\";\n}\n\nclass Derived extends Base {\n  static derivedProp = \"derived\";\n}\n\nconst BoundDerived = Derived.bind(null);\nconsole.log(BoundDerived.baseProp); // \"base\"\nconsole.log(BoundDerived.derivedProp); // undefined\nconsole.log(new BoundDerived() instanceof Derived); // true\n
\n
\n

Transforming methods to utility functions

\n
\n

bind() is also helpful in cases where you want to transform a method which requires a specific this value to a plain utility function that accepts the previous this parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of calling array.map(callback), you use map(array, callback), which avoids mutating Array.prototype, and allows you to use map with array-like objects that are not arrays (for example, arguments).

Take Array.prototype.slice(), for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

\n

js

\n
const slice = Array.prototype.slice;\n\n// ...\n\nslice.call(arguments);\n
\n

Note that you can't save slice.call and call it as a plain function, because the call() method also reads its this value, which is the function it should call. In this case, you can use bind() to bind the value of this for call(). In the following piece of code, slice() is a bound version of Function.prototype.call(), with the this value bound to Array.prototype.slice(). This means that additional call() calls can be eliminated:

\n

js

\n
// Same as \"slice\" in the previous example\nconst unboundSlice = Array.prototype.slice;\nconst slice = Function.prototype.call.bind(unboundSlice);\n\n// ...\n\nslice(arguments);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function.prototype.bind
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
bind7124911.65.141841261.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\n

\n
\n", + "global_objects/function/tostring": "

Function.prototype.toString()

The toString() method of Function instances returns a string representing the source code of this function.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the source code of the function.

Description

\n
\n

The Function object overrides the toString() method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function.

JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

The toString() method will throw a TypeError exception (\"Function.prototype.toString called on incompatible object\"), if its this value object is not a Function object.

\n

js

\n
Function.prototype.toString.call(\"foo\"); // throws TypeError\n
\n

If the toString() method is called on built-in function objects, a function created by Function.prototype.bind(), or other non-JavaScript functions, then toString() returns a native function string which looks like

function someName() { [native code] }\n

For intrinsic object methods and functions, someName is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like [1 + 1], someName, or 1.

Note: This means using eval() on native function strings is a guaranteed syntax error.

If the toString() method is called on a function created by the Function constructor, toString() returns the source code of a synthesized function declaration named \"anonymous\" using the provided parameters and function body. For example, Function(\"a\", \"b\", \"return a + b\").toString() will return:

function anonymous(a,b\n) {\nreturn a + b\n}\n

Since ES2018, the spec requires the return value of toString() to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the compatibility table.

\n

Examples

\n

Comparing actual source code and toString results

\n
\n
\n

js

\n
function test(fn) {\n  console.log(fn.toString());\n}\n\nfunction f() {}\nclass A {\n  a() {}\n}\nfunction* g() {}\n\ntest(f); // \"function f() {}\"\ntest(A); // \"class A { a() {} }\"\ntest(g); // \"function* g() {}\"\ntest((a) => a); // \"(a) => a\"\ntest({ a() {} }.a); // \"a() {}\"\ntest({ *a() {} }.a); // \"*a() {}\"\ntest({ [0]() {} }[0]); // \"[0]() {}\"\ntest(Object.getOwnPropertyDescriptor({ get a() {} }, \"a\").get); // \"get a() {}\"\ntest(Object.getOwnPropertyDescriptor({ set a(x) {} }, \"a\").set); // \"set a(x) {}\"\ntest(Function.prototype.toString); // \"function toString() { [native code] }\"\ntest(function f() {}.bind(0)); // \"function () { [native code] }\"\ntest(Function(\"a\", \"b\")); // function anonymous(a\\n) {\\nb\\n}\n
\n

Note that after the Function.prototype.toString() revision, when toString() is called, implementations are never allowed to synthesize a function's source that is not a native function string. The method always returns the exact source code used to create the function — including the getter and setter examples above. The Function constructor itself has the capability of synthesizing the source code for the function (and is therefore a form of implicit eval()).

\n

Getting source text of a function

\n
\n

It is possible to get the source text of a function by coercing it to a string — for example, by wrapping it in a template literal:

\n

js

\n
function foo() {\n  return \"bar\";\n}\nconsole.log(`${foo}`);\n// function foo() {\n//   return \"bar\";\n// }\n
\n

This source text is exact, including any interspersed comments (which won't be stored by the engine's internal representation otherwise).

\n

js

\n
function foo /* a comment */() {\n  return \"bar\";\n}\nconsole.log(foo.toString());\n// function foo /* a comment */() {\n//   return \"bar\";\n// }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11215314.418410.111.01.00.10.0
toString_revision667954No53No66665447No9.01.0No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString\n

\n
\n", + "global_objects/function/@@hasinstance": "

Function.prototype[@@hasInstance]()

The [@@hasInstance]() method of Function instances specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. It is called by the instanceof operator.

\n

Syntax

\n
\n

js

\n
func[Symbol.hasInstance](value)\n
\n

Parameters

\n
value

The object to test. Primitive values always return false.

Return value

\n

true if func.prototype is in the prototype chain of value; otherwise, false. Always returns false if value is not an object or this is not a function. If this is a bound function, returns the result of a instanceof test on value and the underlying target function.

Exceptions

\n
TypeError

Thrown if this is not a bound function and this.prototype is not an object.

Description

\n
\n

The instanceof operator calls the [@@hasInstance]() method of the right-hand side whenever such a method exists. Because all functions inherit from Function.prototype by default, they would all have the [@@hasInstance]() method, so most of the time, the Function.prototype[@@hasInstance] method specifies the behavior of instanceof when the right-hand side is a function. This method implements the default behavior of the instanceof operator (the same algorithm when constructor has no @@hasInstance method).

Unlike most methods, the Function.prototype[@@hasInstance]() property is non-configurable and non-writable. This is a security feature to prevent the underlying target function of a bound function from being obtainable. See this StackOverflow answer for an example.

\n

Examples

\n

Reverting to default instanceof behavior

\n
\n

You would rarely need to call this method directly. Instead, this method is called by the instanceof operator. You should expect the two results to usually be equivalent.

\n

js

\n
class Foo {}\nconst foo = new Foo();\nconsole.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true\n
\n

You may want to use this method if you want to invoke the default instanceof behavior, but you don't know if a constructor has a overridden [@@hasInstance]() method.

\n

js

\n
class Foo {\n  static [Symbol.hasInstance](value) {\n    // A custom implementation\n    return false;\n  }\n}\n\nconst foo = new Foo();\nconsole.log(foo instanceof Foo); // false\nconsole.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-function.prototype-@@hasinstance
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@hasInstance501550No371050505037105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance\n

\n
\n", + "global_objects/boolean/boolean": "

Boolean() constructor

The Boolean() constructor creates Boolean objects. When called as a function, it returns primitive values of type Boolean.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Boolean(value)\nBoolean(value)\n
\n

Note: Boolean() can be called with or without new, but with different effects. See Return value.

\n

Parameters

\n
value

The initial value of the Boolean object.

Return value

\n
\n

When Boolean() is called as a constructor (with new), it creates a Boolean object, which is not a primitive.

When Boolean() is called as a function (without new), it coerces the parameter to a boolean primitive.

Warning: You should rarely find yourself using Boolean as a constructor.

\n

Description

\n
\n

The value passed as the first parameter is converted to a boolean value. If the value is omitted or is 0, -0, 0n, null, false, NaN, undefined, or the empty string (\"\"), then the object has an initial value of false. All other values, including any object, an empty array ([]), or the string \"false\", create an object with an initial value of true.

Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with the value false. This property is legacy and non-standard and should not be used.

\n

Examples

\n

Creating Boolean objects with an initial value of false

\n
\n
\n

js

\n
const bZero = new Boolean(0);\nconst bNull = new Boolean(null);\nconst bEmptyString = new Boolean(\"\");\nconst bfalse = new Boolean(false);\n\ntypeof bfalse; // \"object\"\nBoolean(bfalse); // true\n
\n

Note how converting a Boolean object to a primitive with Boolean() always yields true, even if the object holds a value of false. You are therefore always advised to avoid constructing Boolean wrapper objects.

If you need to take the primitive value out from the wrapper object, instead of using the Boolean() function, use the object's valueOf() method instead.

\n

js

\n
const bfalse = new Boolean(false);\n\nbfalse.valueOf(); // false\n
\n
\n

Creating Boolean objects with an initial value of true\n

\n
\n

js

\n
const btrue = new Boolean(true);\nconst btrueString = new Boolean(\"true\");\nconst bfalseString = new Boolean(\"false\");\nconst bSuLin = new Boolean(\"Su Lin\");\nconst bArrayProto = new Boolean([]);\nconst bObjProto = new Boolean({});\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-boolean-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Boolean11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/Boolean\n

\n
\n", + "global_objects/array/tostring": "

Array.prototype.toString()

The toString() method of Array instances returns a string representing the specified array and its elements.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the elements of the array.

Description

\n
\n

The Array object overrides the toString method of Object. The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array].

\n

js

\n
const arr = [];\narr.join = 1; // re-assign `join` with a non-function\nconsole.log(arr.toString()); // [object Array]\n\nconsole.log(Array.prototype.toString.call({ join: () => 1 })); // 1\n
\n

JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

Array.prototype.toString recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString does not have delimiters, nested arrays look like they are flattened.

\n

js

\n
const matrix = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9],\n];\n\nconsole.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9\n
\n

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

\n

js

\n
const arr = [];\narr.push(1, [3, arr, 4], 2);\nconsole.log(arr.toString()); // 1,3,,4,2\n
\n
\n

Examples

\n

Using toString()

\n
\n

js

\n
const array1 = [1, 2, \"a\", \"1a\"];\n\nconsole.log(array1.toString()); // \"1,2,a,1a\"\n
\n

Using toString() on sparse arrays

\n
\n

Following the behavior of join(), toString() treats empty slots the same as undefined and produces an extra separator:

\n

js

\n
console.log([1, , 3].toString()); // '1,,3'\n
\n
\n

Calling toString() on non-array objects

\n
\n

toString() is generic. It expects this to have a join() method; or, failing that, uses Object.prototype.toString() instead.

\n

js

\n
console.log(Array.prototype.toString.call({ join: () => 1 }));\n// 1; a number\nconsole.log(Array.prototype.toString.call({ join: () => undefined }));\n// undefined\nconsole.log(Array.prototype.toString.call({ join: \"not function\" }));\n// \"[object Object]\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString1121441≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString\n

\n
\n", + "global_objects/boolean/tostring": "

Boolean.prototype.toString()

The toString() method of Boolean values returns a string representing the specified boolean value.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the specified boolean value.

Description

\n
\n

The Boolean object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For Boolean values, the toString method returns a string representation of the boolean value, which is either \"true\" or \"false\".

The toString() method requires its this value to be a Boolean primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to boolean values.

Because Boolean doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a Boolean object is used in a context expecting a string, such as in a template literal. However, boolean primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

\n

js

\n
Boolean.prototype.toString = () => \"Overridden\";\nconsole.log(`${true}`); // \"true\"\nconsole.log(`${new Boolean(true)}`); // \"Overridden\"\n
\n
\n

Examples

\n

Using toString()

\n
\n

js

\n
const flag = new Boolean(true);\nconsole.log(flag.toString()); // \"true\"\nconsole.log(false.toString()); // \"false\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-boolean.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11213414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/toString\n

\n
\n", + "global_objects/boolean/valueof": "

Boolean.prototype.valueOf()

The valueOf() method of Boolean values returns the primitive value of a Boolean object.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

The primitive value of the given Boolean object.

Description

\n
\n

The valueOf() method of Boolean returns the primitive value of a Boolean object or literal Boolean as a Boolean data type.

This method is usually called internally by JavaScript and not explicitly in code.

\n

Examples

\n

Using valueOf()\n

\n
\n

js

\n
x = new Boolean();\nmyVar = x.valueOf(); // assigns false to myVar\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-boolean.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/valueOf\n

\n
\n", + "global_objects/symbol/for": "

Symbol.for()

The Symbol.for() static method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.

\n

Try it

\n

Syntax

\n
\n

js

\n
Symbol.for(key)\n
\n

Parameters

\n
key

String, required. The key for the symbol (and also used for the description of the symbol).

Return value

\n

An existing symbol with the given key if found; otherwise, a new symbol is created and returned.

Description

\n

In contrast to Symbol(), the Symbol.for() function creates a symbol available in a global symbol registry list. Symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, Symbol.for() will create a new global symbol.

Examples

\n

Using Symbol.for()

\n
\n
\n

js

\n
Symbol.for(\"foo\"); // create a new global symbol\nSymbol.for(\"foo\"); // retrieve the already created symbol\n\n// Same global symbol, but not locally\nSymbol.for(\"bar\") === Symbol.for(\"bar\"); // true\nSymbol(\"bar\") === Symbol(\"bar\"); // false\n\n// The key is also used as the description\nconst sym = Symbol.for(\"mario\");\nsym.toString(); // \"Symbol(mario)\"\n
\n

To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols:

\n

js

\n
Symbol.for(\"mdn.foo\");\nSymbol.for(\"mdn.bar\");\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.for
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
for401236No2794040362794.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for\n

\n
\n", + "global_objects/symbol/keyfor": "

Symbol.keyFor()

The Symbol.keyFor() static method retrieves a shared symbol key from the global symbol registry for the given symbol.

\n

Try it

\n

Syntax

\n
\n

js

\n
Symbol.keyFor(sym)\n
\n

Parameters

\n
sym

Symbol, required. The symbol to find a key for.

Return value

\n

A string representing the key for the given symbol if one is found on the global registry; otherwise, undefined.

Examples

\n

Using keyFor()

\n
\n

js

\n
const globalSym = Symbol.for(\"foo\"); // create a new global symbol\nSymbol.keyFor(globalSym); // \"foo\"\n\nconst localSym = Symbol();\nSymbol.keyFor(localSym); // undefined\n\n// well-known symbols are not symbols registered\n// in the global symbol registry\nSymbol.keyFor(Symbol.iterator); // undefined\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.keyfor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keyFor401236No2794040362794.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/keyFor\n

\n
\n", + "global_objects/symbol/hasinstance": "

Symbol.hasInstance

The Symbol.hasInstance static data property represents the well-known symbol @@hasInstance. The instanceof operator looks up this symbol on its right-hand operand for the method used to determine if the constructor object recognizes an object as its instance.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@hasInstance.

\n
Property attributes of Symbol.hasInstance\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The instanceof operator uses the following algorithm to calculate the return value of object instanceof constructor:

  1. If constructor has a @@hasInstance method, then call it with object as the first argument and return the result, coerced to a boolean. Throw a TypeError if constructor is not an object, or if constructor[@@hasInstance] is not one of null, undefined, or a function.
  2. Otherwise, if constructor doesn't have a @@hasInstance method (constructor[@@hasInstance] is null or undefined), then determine the result using the same algorithm as Function.prototype[@@hasInstance]. Throw a TypeError if constructor is not a function.

Because all functions inherit from Function.prototype by default, most of the time, the Function.prototype[@@hasInstance] method specifies the behavior of instanceof when the right-hand side is a function.

\n

Examples

\n

Custom instanceof behavior

\n
\n

You could implement your custom instanceof behavior like this, for example:

\n

js

\n
class MyArray {\n  static [Symbol.hasInstance](instance) {\n    return Array.isArray(instance);\n  }\n}\nconsole.log([] instanceof MyArray); // true\n
\n
\n

js

\n
function MyArray() {}\nObject.defineProperty(MyArray, Symbol.hasInstance, {\n  value(instance) {\n    return Array.isArray(instance);\n  },\n});\nconsole.log([] instanceof MyArray); // true\n
\n
\n

Checking the instance of an object

\n
\n

Just in the same manner at which you can check if an object is an instance of a class using the instanceof keyword, we can also use Symbol.hasInstance for such checks.

\n

js

\n
class Animal {\n  constructor() {}\n}\n\nconst cat = new Animal();\n\nconsole.log(Animal[Symbol.hasInstance](cat)); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.hasinstance
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hasInstance501550No371050505037105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance\n

\n
\n", + "global_objects/json/stringify": "

JSON.stringify()

The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

\n

Try it

\n

Syntax

\n
\n

js

\n
JSON.stringify(value)\nJSON.stringify(value, replacer)\nJSON.stringify(value, replacer, space)\n
\n

Parameters

\n
value

The value to convert to a JSON string.

\nreplacer Optional\n

A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of value to be included in the output. If replacer is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including Symbol values, are completely ignored. If replacer is anything other than a function or an array (e.g. null or not provided), all string-keyed properties of the object are included in the resulting JSON string.

\nspace Optional\n

A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.

If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than 10 is treated as if it were 10). Values less than 1 indicate that no space should be used.

If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.

If space is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is null or not provided — no white space is used.

Return value

\n

A JSON string representing the given value, or undefined.

Exceptions

\n
TypeError

Thrown in one of the following cases:

  • \nvalue contains a circular reference.
  • A BigInt value is encountered.

Description

\n
\n

JSON.stringify() converts a value to the JSON notation that the value represents. Values are stringified in the following manner:

\n

The replacer parameter

\n
\n

The replacer parameter can be either a function or an array.

As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored.

As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer's this context.

The replacer function is called for the initial object being stringified as well, in which case the key is an empty string (\"\"). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as key. The current property value will be replaced with the replacer's return value for stringification. This means:

Note: When parsing JSON generated with replacer functions, you would likely want to use the reviver parameter to perform the reverse operation.

Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become null instead of omitted). Using the replacer function allows you to control the order of the array elements by returning a different array.

\n

The space parameter

\n
\n

The space parameter may be used to control spacing in the final string.

Each level of indentation will never be longer than 10. Number values of space are clamped to 10, and string values are truncated to 10 characters.

\n

Examples

\n

Using JSON.stringify

\n
\n

js

\n
JSON.stringify({}); // '{}'\nJSON.stringify(true); // 'true'\nJSON.stringify(\"foo\"); // '\"foo\"'\nJSON.stringify([1, \"false\", false]); // '[1,\"false\",false]'\nJSON.stringify([NaN, null, Infinity]); // '[null,null,null]'\nJSON.stringify({ x: 5 }); // '{\"x\":5}'\n\nJSON.stringify(new Date(1906, 0, 2, 15, 4, 5));\n// '\"1906-01-02T15:04:05.000Z\"'\n\nJSON.stringify({ x: 5, y: 6 });\n// '{\"x\":5,\"y\":6}'\nJSON.stringify([new Number(3), new String(\"false\"), new Boolean(false)]);\n// '[3,\"false\",false]'\n\n// String-keyed array elements are not enumerable and make no sense in JSON\nconst a = [\"foo\", \"bar\"];\na[\"baz\"] = \"quux\"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]\nJSON.stringify(a);\n// '[\"foo\",\"bar\"]'\n\nJSON.stringify({ x: [10, undefined, function () {}, Symbol(\"\")] });\n// '{\"x\":[10,null,null,null]}'\n\n// Standard data structures\nJSON.stringify([\n  new Set([1]),\n  new Map([[1, 2]]),\n  new WeakSet([{ a: 1 }]),\n  new WeakMap([[{ a: 1 }, 2]]),\n]);\n// '[{},{},{},{}]'\n\n// TypedArray\nJSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([\n  new Uint8Array([1]),\n  new Uint8ClampedArray([1]),\n  new Uint16Array([1]),\n  new Uint32Array([1]),\n]);\n// '[{\"0\":1},{\"0\":1},{\"0\":1},{\"0\":1}]'\nJSON.stringify([new Float32Array([1]), new Float64Array([1])]);\n// '[{\"0\":1},{\"0\":1}]'\n\n// toJSON()\nJSON.stringify({\n  x: 5,\n  y: 6,\n  toJSON() {\n    return this.x + this.y;\n  },\n});\n// '11'\n\n// Symbols:\nJSON.stringify({ x: undefined, y: Object, z: Symbol(\"\") });\n// '{}'\nJSON.stringify({ [Symbol(\"foo\")]: \"foo\" });\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, [Symbol.for(\"foo\")]);\n// '{}'\nJSON.stringify({ [Symbol.for(\"foo\")]: \"foo\" }, (k, v) => {\n  if (typeof k === \"symbol\") {\n    return \"a symbol\";\n  }\n});\n// undefined\n\n// Non-enumerable properties:\nJSON.stringify(\n  Object.create(null, {\n    x: { value: \"x\", enumerable: false },\n    y: { value: \"y\", enumerable: true },\n  }),\n);\n// '{\"y\":\"y\"}'\n\n// BigInt values throw\nJSON.stringify({ x: 2n });\n// TypeError: BigInt value can't be serialized in JSON\n
\n

Using a function as replacer

\n
\n
\n

js

\n
function replacer(key, value) {\n  // Filtering out properties\n  if (typeof value === \"string\") {\n    return undefined;\n  }\n  return value;\n}\n\nconst foo = {\n  foundation: \"Mozilla\",\n  model: \"box\",\n  week: 45,\n  transport: \"car\",\n  month: 7,\n};\nJSON.stringify(foo, replacer);\n// '{\"week\":45,\"month\":7}'\n
\n

If you wish the replacer to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).

\n

js

\n
function makeReplacer() {\n  let isInitial = true;\n\n  return (key, value) => {\n    if (isInitial) {\n      isInitial = false;\n      return value;\n    }\n    if (key === \"\") {\n      // Omit all properties with name \"\" (except the initial object)\n      return undefined;\n    }\n    return value;\n  };\n}\n\nconst replacer = makeReplacer();\nconsole.log(JSON.stringify({ \"\": 1, b: 2 }, replacer)); // \"{\"b\":2}\"\n
\n
\n

Using an array as replacer

\n
\n

js

\n
const foo = {\n  foundation: \"Mozilla\",\n  model: \"box\",\n  week: 45,\n  transport: \"car\",\n  month: 7,\n};\n\nJSON.stringify(foo, [\"week\", \"month\"]);\n// '{\"week\":45,\"month\":7}', only keep \"week\" and \"month\" properties\n
\n

Using the space parameter

\n
\n

Indent the output with one space:

\n

js

\n
console.log(JSON.stringify({ a: 2 }, null, \" \"));\n/*\n{\n \"a\": 2\n}\n*/\n
\n

Using a tab character mimics standard pretty-print appearance:

\n

js

\n
console.log(JSON.stringify({ uno: 1, dos: 2 }, null, \"\\t\"));\n/*\n{\n\t\"uno\": 1,\n\t\"dos\": 2\n}\n*/\n
\n
\n

toJSON() behavior

\n
\n

Defining toJSON() for an object allows overriding its serialization behavior.

\n

js

\n
const obj = {\n  data: \"data\",\n\n  toJSON(key) {\n    return key ? `Now I am a nested object under key '${key}'` : this;\n  },\n};\n\nJSON.stringify(obj);\n// '{\"data\":\"data\"}'\n\nJSON.stringify({ obj });\n// '{\"obj\":\"Now I am a nested object under key 'obj'\"}'\n\nJSON.stringify([obj]);\n// '[\"Now I am a nested object under key '0'\"]'\n
\n
\n

Issue with serializing circular references

\n
\n

Since the JSON format doesn't support object references (although an IETF draft exists), a TypeError will be thrown if one attempts to encode an object with circular references.

\n

js

\n
const circularReference = {};\ncircularReference.myself = circularReference;\n\n// Serializing circular references throws \"TypeError: cyclic object value\"\nJSON.stringify(circularReference);\n
\n

To serialize circular references, you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

If you are using JSON.stringify() to deep-copy an object, you may instead want to use structuredClone(), which supports circular references. JavaScript engine APIs for binary serialization, such as v8.serialize(), also support circular references.

\n

Using JSON.stringify() with localStorage

\n
\n

In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify():

\n

js

\n
// Creating an example of JSON\nconst session = {\n  screens: [],\n  state: true,\n};\nsession.screens.push({ name: \"screenA\", width: 450, height: 250 });\nsession.screens.push({ name: \"screenB\", width: 650, height: 350 });\nsession.screens.push({ name: \"screenC\", width: 750, height: 120 });\nsession.screens.push({ name: \"screenD\", width: 250, height: 60 });\nsession.screens.push({ name: \"screenE\", width: 390, height: 120 });\nsession.screens.push({ name: \"screenF\", width: 1240, height: 650 });\n\n// Converting the JSON string with JSON.stringify()\n// then saving with localStorage in the name of session\nlocalStorage.setItem(\"session\", JSON.stringify(session));\n\n// Example of how to transform the String generated through\n// JSON.stringify() and saved in localStorage in JSON object again\nconst restoredSession = JSON.parse(localStorage.getItem(\"session\"));\n\n// Now restoredSession variable contains the object that was saved\n// in localStorage\nconsole.log(restoredSession);\n
\n
\n

Well-formed JSON.stringify()

\n
\n

Engines implementing the well-formed JSON.stringify specification will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16:

\n

js

\n
JSON.stringify(\"\\uD800\"); // '\"�\"'\n
\n

But with this change JSON.stringify() represents lone surrogates using JSON escape sequences that can be encoded in valid UTF-8 or UTF-16:

\n

js

\n
JSON.stringify(\"\\uD800\"); // '\"\\\\ud800\"'\n
\n

This change should be backwards-compatible as long as you pass the result of JSON.stringify() to APIs such as JSON.parse() that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. Only if you are directly interpreting the result of JSON.stringify() do you need to carefully handle JSON.stringify()'s two possible encodings of these code points.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-json.stringify
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
stringify3123.5810.54≤371841141.01.00.10.0
well_formed_stringify727964No6012.17272645012.211.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify\n

\n
\n", + "global_objects/string/string": "

String() constructor

The String() constructor creates String objects. When called as a function, it returns primitive values of type String.

\n

Syntax

\n
\n
\n

js

\n
new String(thing)\nString(thing)\n
\n

Note: String() can be called with or without new, but with different effects. See Return value.

\n

Parameters

\n
thing

Anything to be converted to a string.

Return value

\n
\n

When String is called as a constructor (with new), it creates a String object, which is not a primitive.

When String is called as a function, it coerces the parameter to a string primitive. Symbol values would be converted to \"Symbol(description)\", where description is the description of the Symbol, instead of throwing.

Warning: You should rarely find yourself using String as a constructor.

\n

Examples

\n

String constructor and String function

\n
\n

String function and String constructor produce different results:

\n

js

\n
const a = new String(\"Hello world\"); // a === \"Hello world\" is false\nconst b = String(\"Hello world\"); // b === \"Hello world\" is true\na instanceof String; // is true\nb instanceof String; // is false\ntypeof a; // \"object\"\ntypeof b; // \"string\"\n
\n

Here, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.

\n

Using String() to stringify a symbol

\n
\n

String() is the only case where a symbol can be converted to a string without throwing, because it's very explicit.

\n

js

\n
const sym = Symbol(\"example\");\n`${sym}`; // TypeError: Cannot convert a Symbol value to a string\n\"\" + sym; // TypeError: Cannot convert a Symbol value to a string\n\"\".concat(sym); // TypeError: Cannot convert a Symbol value to a string\n
\n
\n

js

\n
const sym = Symbol(\"example\");\nString(sym); // \"Symbol(example)\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
String11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String\n

\n
\n", + "global_objects/symbol/symbol": "

Symbol() constructor

The Symbol() function returns primitive values of type Symbol.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
Symbol()\nSymbol(description)\n
\n

Note: Symbol() can only be called without new. Attempting to construct it with new throws a TypeError.

\n

Parameters

\n
\ndescription Optional\n

A string. A description of the symbol which can be used for debugging but not to access the symbol itself.

Examples

\n

Creating symbols

\n
\n

To create a new primitive symbol, you write Symbol() with an optional string as its description:

\n

js

\n
const sym1 = Symbol();\nconst sym2 = Symbol(\"foo\");\nconst sym3 = Symbol(\"foo\");\n
\n

The above code creates three new symbols. Note that Symbol(\"foo\") does not coerce the string \"foo\" into a symbol. It creates a new symbol each time:

\n

js

\n
Symbol(\"foo\") === Symbol(\"foo\"); // false\n
\n
\n

new Symbol()

\n
\n

The following syntax with the new operator will throw a TypeError:

\n

js

\n
const sym = new Symbol(); // TypeError\n
\n

This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number).

If you really want to create a Symbol wrapper object, you can use the Object() function:

\n

js

\n
const sym = Symbol(\"foo\");\nconst symObj = Object(sym);\ntypeof sym; // \"symbol\"\ntypeof symObj; // \"object\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Symbol381236No2593838362593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/Symbol\n

\n
\n", + "global_objects/symbol/asynciterator": "

Symbol.asyncIterator

The Symbol.asyncIterator static data property represents the well-known symbol @@asyncIterator. The async iterable protocol looks up this symbol for the method that returns the async iterator for an object. In order for an object to be async iterable, it must have an @@asyncIterator key.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@asyncIterator.

\n
Property attributes of Symbol.asyncIterator\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

User-defined async iterables

\n
\n

You can define your own async iterable by setting the [Symbol.asyncIterator] property on an object.

\n

js

\n
const myAsyncIterable = {\n  async *[Symbol.asyncIterator]() {\n    yield \"hello\";\n    yield \"async\";\n    yield \"iteration!\";\n  },\n};\n\n(async () => {\n  for await (const x of myAsyncIterable) {\n    console.log(x);\n  }\n})();\n// Logs:\n// \"hello\"\n// \"async\"\n// \"iteration!\"\n
\n

When creating an API, remember that async iterables are designed to represent something iterable — like a stream of data or a list —, not to completely replace callbacks and events in most situations.

\n

Built-in async iterables

\n

ReadableStream is the only built-in JavaScript object that has the Symbol.asyncIterator method set by default at the time of writing.

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.asynciterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
asyncIterator637957No5011.16363574611.38.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator\n

\n
\n", + "global_objects/symbol/isconcatspreadable": "

Symbol.isConcatSpreadable

The Symbol.isConcatSpreadable static data property represents the well-known symbol @@isConcatSpreadable. The Array.prototype.concat() method looks up this symbol on each object being concatenated to determine if it should be treated as an array-like object and flattened to its array elements.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@isConcatSpreadable.

\n
Property attributes of Symbol.isConcatSpreadable\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The @@isConcatSpreadable symbol (Symbol.isConcatSpreadable) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects:

\n

Examples

\n

Arrays

\n
\n

By default, Array.prototype.concat() spreads (flattens) arrays into its result:

\n

js

\n
const alpha = [\"a\", \"b\", \"c\"];\nconst numeric = [1, 2, 3];\n\nconst alphaNumeric = alpha.concat(numeric);\n\nconsole.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]\n
\n

When setting Symbol.isConcatSpreadable to false, you can disable the default behavior:

\n

js

\n
const alpha = [\"a\", \"b\", \"c\"];\nconst numeric = [1, 2, 3];\n\nnumeric[Symbol.isConcatSpreadable] = false;\nconst alphaNumeric = alpha.concat(numeric);\n\nconsole.log(alphaNumeric); // Result: ['a', 'b', 'c', [1, 2, 3] ]\n
\n
\n

Array-like objects

\n
\n

For array-like objects, the default is to not spread. Symbol.isConcatSpreadable needs to be set to true in order to get a flattened array:

\n

js

\n
const x = [1, 2, 3];\n\nconst fakeArray = {\n  [Symbol.isConcatSpreadable]: true,\n  length: 2,\n  0: \"hello\",\n  1: \"world\",\n};\n\nx.concat(fakeArray); // [1, 2, 3, \"hello\", \"world\"]\n
\n

Note: The length property is used to control the number of object properties to be added. In the above example, length:2 indicates two properties has to be added.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.isconcatspreadable
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isConcatSpreadable481548No351048484835105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable\n

\n
\n", + "global_objects/array/concat": "

Array.prototype.concat()

The concat() method of Array instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

\n

Try it

\n

Syntax

\n
\n

js

\n
concat()\nconcat(value1)\nconcat(value1, value2)\nconcat(value1, value2, /* …, */ valueN)\n
\n

Parameters

\n
\nvalue1, …, valueN Optional\n

Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called. See the description below for more details.

Return value

\n

A new Array instance.

Description

\n
\n

The concat method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property Symbol.isConcatSpreadable set to a truthy value, each element of the argument will be independently added to the final array. The concat method does not recurse into nested array arguments.

The concat() method is a copying method. It does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains the same elements as the ones from the original arrays.

The concat() method preserves empty slots if any of the source arrays is sparse.

The concat() method is generic. The this value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy @@isConcatSpreadable will be spread into the resulting array.

\n

Examples

\n

Concatenating two arrays

\n
\n

The following code concatenates two arrays:

\n

js

\n
const letters = [\"a\", \"b\", \"c\"];\nconst numbers = [1, 2, 3];\n\nconst alphaNumeric = letters.concat(numbers);\nconsole.log(alphaNumeric);\n// results in ['a', 'b', 'c', 1, 2, 3]\n
\n
\n

Concatenating three arrays

\n
\n

The following code concatenates three arrays:

\n

js

\n
const num1 = [1, 2, 3];\nconst num2 = [4, 5, 6];\nconst num3 = [7, 8, 9];\n\nconst numbers = num1.concat(num2, num3);\n\nconsole.log(numbers);\n// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]\n
\n
\n

Concatenating values to an array

\n
\n

The following code concatenates three values to an array:

\n

js

\n
const letters = [\"a\", \"b\", \"c\"];\n\nconst alphaNumeric = letters.concat(1, [2, 3]);\n\nconsole.log(alphaNumeric);\n// results in ['a', 'b', 'c', 1, 2, 3]\n
\n
\n

Concatenating nested arrays

\n
\n

The following code concatenates nested arrays and demonstrates retention of references:

\n

js

\n
const num1 = [[1]];\nconst num2 = [2, [3]];\n\nconst numbers = num1.concat(num2);\n\nconsole.log(numbers);\n// results in [[1], 2, [3]]\n\n// modify the first element of num1\nnum1[0].push(4);\n\nconsole.log(numbers);\n// results in [[1, 4], 2, [3]]\n
\n
\n

Concatenating array-like objects with Symbol.isConcatSpreadable

\n
\n

concat does not treat all array-like objects as arrays by default — only if Symbol.isConcatSpreadable is set to a truthy value (e.g. true).

\n

js

\n
const obj1 = { 0: 1, 1: 2, 2: 3, length: 3 };\nconst obj2 = { 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true };\nconsole.log([0].concat(obj1, obj2));\n// [ 0, { '0': 1, '1': 2, '2': 3, length: 3 }, 1, 2, 3 ]\n
\n
\n

Using concat() on sparse arrays

\n
\n

If any of the source arrays is sparse, the resulting array will also be sparse:

\n

js

\n
console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5]\nconsole.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]\n
\n
\n

Calling concat() on non-array objects

\n
\n

If the this value is not an array, it is converted to an object and then treated in the same way as the arguments for concat(). In this case the return value is always a plain new array.

\n

js

\n
console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3]\nconsole.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ]\nconst arrayLike = {\n  [Symbol.isConcatSpreadable]: true,\n  length: 2,\n  0: 1,\n  1: 2,\n  2: 99, // ignored by concat() since length is 2\n};\nconsole.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.concat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
concat11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat\n

\n
\n", + "global_objects/symbol/iterator": "

Symbol.iterator

The Symbol.iterator static data property represents the well-known symbol @@iterator. The iterable protocol looks up this symbol for the method that returns the iterator for an object. In order for an object to be iterable, it must have an @@iterator key.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@iterator.

\n
Property attributes of Symbol.iterator\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Some built-in types have a default iteration behavior, while other types (such as Object) do not. Some built-in types with a @@iterator method are:

See also Iteration protocols for more information.

\n

Examples

\n

User-defined iterables

\n
\n

We can make our own iterables like this:

\n

js

\n
const myIterable = {};\nmyIterable[Symbol.iterator] = function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n};\n[...myIterable]; // [1, 2, 3]\n
\n

Or iterables can be defined directly inside a class or object using a computed property:

\n

js

\n
class Foo {\n  *[Symbol.iterator]() {\n    yield 1;\n    yield 2;\n    yield 3;\n  }\n}\n\nconst someObj = {\n  *[Symbol.iterator]() {\n    yield \"a\";\n    yield \"b\";\n  },\n};\n\nconsole.log(...new Foo()); // 1, 2, 3\nconsole.log(...someObj); // 'a', 'b'\n
\n
\n

Non-well-formed iterables

\n
\n

If an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:

\n

js

\n
const nonWellFormedIterable = {};\nnonWellFormedIterable[Symbol.iterator] = () => 1;\n[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
iterator431236No301043433630104.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator\n

\n
\n", + "global_objects/symbol/match": "

Symbol.match

\n

The Symbol.match static data property represents the well-known symbol @@match. The String.prototype.match() method looks up this symbol on its first argument for the method used to match an input string against the current object. This symbol is also used to determine if an object should be treated as a regex.

For more information, see RegExp.prototype[@@match]() and String.prototype.match().

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@match.

\n
Property attributes of Symbol.match\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

This function is also used to identify if objects have the behavior of regular expressions. For example, the methods String.prototype.startsWith(), String.prototype.endsWith() and String.prototype.includes(), check if their first argument is a regular expression and will throw a TypeError if they are. Now, if the match symbol is set to false (or a Falsy value except undefined), it indicates that the object is not intended to be used as a regular expression object.

Examples

\n

Marking a RegExp as not a regex

\n
\n

The following code will throw a TypeError:

\n

js

\n
\"/bar/\".startsWith(/bar/);\n\n// Throws TypeError, as /bar/ is a regular expression\n// and Symbol.match is not modified.\n
\n

However, if you set Symbol.match to false, the object will be considered as not a regular expression object. The methods startsWith and endsWith won't throw a TypeError as a consequence.

\n

js

\n
const re = /foo/;\nre[Symbol.match] = false;\n\"/foo/\".startsWith(re); // true\n\"/baz/\".endsWith(re); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.match
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
match507940No371050504037105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match\n

\n
\n", + "global_objects/string/match": "

String.prototype.match()

The match() method of String values retrieves the result of matching this string against a regular expression.

\n

Try it

\n

Syntax

\n
\n

js

\n
match(regexp)\n
\n

Parameters

\n
regexp

A regular expression object, or any object that has a Symbol.match method.

If regexp is not a RegExp object and does not have a Symbol.match method, it is implicitly converted to a RegExp by using new RegExp(regexp).

If you don't give any parameter and use the match() method directly, you will get an Array with an empty string: [\"\"], because this is equivalent to match(/(?:)/).

Return value

\n
\n

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

\n

Description

\n
\n

The implementation of String.prototype.match itself is very simple — it simply calls the Symbol.match method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[@@match]().

For more information about the semantics of match() when a regex is passed, see RegExp.prototype[@@match]().

\n

Examples

\n

Using match()

\n
\n

In the following example, match() is used to find \"Chapter\" followed by one or more numeric characters followed by a decimal point and numeric character zero or more times.

The regular expression includes the i flag so that upper/lower case differences will be ignored.

\n

js

\n
const str = \"For more information, see Chapter 3.4.5.1\";\nconst re = /see (chapter \\d+(\\.\\d)*)/i;\nconst found = str.match(re);\n\nconsole.log(found);\n// [\n//   'see Chapter 3.4.5.1',\n//   'Chapter 3.4.5.1',\n//   '.1',\n//   index: 22,\n//   input: 'For more information, see Chapter 3.4.5.1',\n//   groups: undefined\n// ]\n
\n

In the match result above, 'see Chapter 3.4.5.1' is the whole match. 'Chapter 3.4.5.1' was captured by (chapter \\d+(\\.\\d)*). '.1' was the last value captured by (\\.\\d). The index property (22) is the zero-based index of the whole match. The input property is the original string that was parsed.

\n

Using global and ignoreCase flags with match()

\n
\n

The following example demonstrates the use of the global flag and ignore-case flag with match(). All letters A through E and a through e are returned, each its own element in the array.

\n

js

\n
const str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nconst regexp = /[A-E]/gi;\nconst matches = str.match(regexp);\n\nconsole.log(matches);\n// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']\n
\n
\n

Using named capturing groups

\n
\n

In browsers which support named capturing groups, the following code captures \"fox\" or \"cat\" into a group named animal:

\n

js

\n
const paragraph = \"The quick brown fox jumps over the lazy dog. It barked.\";\n\nconst capturingRegex = /(?<animal>fox|cat) jumps over/;\nconst found = paragraph.match(capturingRegex);\nconsole.log(found.groups); // {animal: \"fox\"}\n
\n
\n

Using match() with no parameter

\n
\n

js

\n
const str = \"Nothing will come of nothing.\";\n\nstr.match(); // returns [\"\"]\n
\n

Using match() with a non-RegExp implementing @@match

\n
\n

If an object has a Symbol.match method, it can be used as a custom matcher. The return value of Symbol.match becomes the return value of match().

\n

js

\n
const str = \"Hmm, this is interesting.\";\n\nstr.match({\n  [Symbol.match](str) {\n    return [\"Yes, it's interesting.\"];\n  },\n}); // returns [\"Yes, it's interesting.\"]\n
\n
\n

A non-RegExp as the parameter

\n
\n

When the regexp parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp(regexp).

\n

js

\n
const str1 =\n  \"NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.\";\nconst str2 =\n  \"My grandfather is 65 years old and My grandmother is 63 years old.\";\nconst str3 = \"The contract was declared null and void.\";\nstr1.match(\"number\"); // \"number\" is a string. returns [\"number\"]\nstr1.match(NaN); // the type of NaN is the number. returns [\"NaN\"]\nstr1.match(Infinity); // the type of Infinity is the number. returns [\"Infinity\"]\nstr1.match(+Infinity); // returns [\"Infinity\"]\nstr1.match(-Infinity); // returns [\"-Infinity\"]\nstr2.match(65); // returns [\"65\"]\nstr2.match(+65); // A number with a positive sign. returns [\"65\"]\nstr3.match(null); // returns [\"null\"]\n
\n

This may have unexpected results if special characters are not properly escaped.

\n

js

\n
console.log(\"123\".match(\"1.3\")); // [ \"123\" ]\n
\n

This is a match because . in a regex matches any character. In order to make it only match specifically a dot character, you need to escape the input.

\n

js

\n
console.log(\"123\".match(\"1\\\\.3\")); // null\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.match
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
match11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match\n

\n
\n", + "global_objects/symbol/matchall": "

Symbol.matchAll

\n

The Symbol.matchAll static data property represents the well-known symbol @@matchAll. The String.prototype.matchAll() method looks up this symbol on its first argument for the method that returns an iterator, that yields matches of the current object against a string.

For more information, see RegExp.prototype[@@matchAll]() and String.prototype.matchAll().

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@matchAll.

\n
Property attributes of Symbol.matchAll\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

Using Symbol.matchAll

\n
\n

js

\n
const str = \"2016-01-02|2019-03-07\";\n\nconst numbers = {\n  *[Symbol.matchAll](str) {\n    for (const n of str.matchAll(/[0-9]+/g)) yield n[0];\n  },\n};\n\nconsole.log(Array.from(str.matchAll(numbers)));\n// [\"2016\", \"01\", \"02\", \"2019\", \"03\", \"07\"]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.matchall
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
matchAll737967No6013737367521311.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/matchAll\n

\n
\n", + "global_objects/string/matchall": "

String.prototype.matchAll()

The matchAll() method of String values returns an iterator of all results matching this string against a regular expression, including capturing groups.

\n

Try it

\n

Syntax

\n
\n

js

\n
matchAll(regexp)\n
\n

Parameters

\n
regexp

A regular expression object, or any object that has a Symbol.matchAll method.

If regexp is not a RegExp object and does not have a Symbol.matchAll method, it is implicitly converted to a RegExp by using new RegExp(regexp, 'g').

If regexp is a regex, then it must have the global (g) flag set, or a TypeError is thrown.

Return value

\n

An iterable iterator object (which is not restartable) of matches. Each match is an array with the same shape as the return value of RegExp.prototype.exec().

Exceptions

\n
TypeError

Thrown if the regexp is a regex that does not have the global (g) flag set (its flags property does not contain \"g\").

Description

\n

The implementation of String.prototype.matchAll itself is very simple — it simply calls the Symbol.matchAll method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from RegExp.prototype[@@matchAll]().

Examples

\n

Regexp.prototype.exec() and matchAll()

\n
\n

Without matchAll(), it's possible to use calls to regexp.exec() (and regexes with the g flag) in a loop to obtain all the matches:

\n

js

\n
const regexp = /foo[a-z]*/g;\nconst str = \"table football, foosball\";\nlet match;\n\nwhile ((match = regexp.exec(str)) !== null) {\n  console.log(\n    `Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,\n  );\n}\n// Found football start=6 end=14.\n// Found foosball start=16 end=24.\n
\n

With matchAll() available, you can avoid the while loop and exec with g. Instead, you get an iterator to use with the more convenient for...of, array spreading, or Array.from() constructs:

\n

js

\n
const regexp = /foo[a-z]*/g;\nconst str = \"table football, foosball\";\nconst matches = str.matchAll(regexp);\n\nfor (const match of matches) {\n  console.log(\n    `Found ${match[0]} start=${match.index} end=${\n      match.index + match[0].length\n    }.`,\n  );\n}\n// Found football start=6 end=14.\n// Found foosball start=16 end=24.\n\n// matches iterator is exhausted after the for...of iteration\n// Call matchAll again to create a new iterator\nArray.from(str.matchAll(regexp), (m) => m[0]);\n// [ \"football\", \"foosball\" ]\n
\n

matchAll will throw an exception if the g flag is missing.

\n

js

\n
const regexp = /[a-c]/;\nconst str = \"abc\";\nstr.matchAll(regexp);\n// TypeError\n
\n

matchAll internally makes a clone of the regexp — so, unlike regexp.exec(), lastIndex does not change as the string is scanned.

\n

js

\n
const regexp = /[a-c]/g;\nregexp.lastIndex = 1;\nconst str = \"abc\";\nArray.from(str.matchAll(regexp), (m) => `${regexp.lastIndex}${m[0]}`);\n// [ \"1 b\", \"1 c\" ]\n
\n

However, this means that unlike using regexp.exec() in a loop, you can't mutate lastIndex to make the regex advance or rewind.

\n

Better access to capturing groups (than String.prototype.match())

\n
\n

Another compelling reason for matchAll is the improved access to capture groups.

Capture groups are ignored when using match() with the global g flag:

\n

js

\n
const regexp = /t(e)(st(\\d?))/g;\nconst str = \"test1test2\";\n\nstr.match(regexp); // ['test1', 'test2']\n
\n

Using matchAll, you can access capture groups easily:

\n

js

\n
const array = [...str.matchAll(regexp)];\n\narray[0];\n// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]\narray[1];\n// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]\n
\n
\n

Using matchAll() with a non-RegExp implementing @@matchAll

\n
\n

If an object has a Symbol.matchAll method, it can be used as a custom matcher. The return value of Symbol.matchAll becomes the return value of matchAll().

\n

js

\n
const str = \"Hmm, this is interesting.\";\n\nstr.matchAll({\n  [Symbol.matchAll](str) {\n    return [[\"Yes, it's interesting.\"]];\n  },\n}); // returns [[\"Yes, it's interesting.\"]]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.matchall
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
matchAll737967No6013737367521311.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll\n

\n
\n", + "global_objects/symbol/replace": "

Symbol.replace

\n

The Symbol.replace static data property represents the well-known symbol @@replace. The String.prototype.replace() method looks up this symbol on its first argument for the method that replaces substrings matched by the current object.

For more information, see RegExp.prototype[@@replace]() and String.prototype.replace().

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@replace.

\n
Property attributes of Symbol.replace\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

Using Symbol.replace

\n
\n

js

\n
class CustomReplacer {\n  constructor(value) {\n    this.value = value;\n  }\n  [Symbol.replace](string) {\n    return string.replace(this.value, \"#!@?\");\n  }\n}\n\nconsole.log(\"football\".replace(new CustomReplacer(\"foo\"))); // \"#!@?tball\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.replace
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
replace507949No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace\n

\n
\n", + "global_objects/string/replace": "

String.prototype.replace()

The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

\n

Try it

\n

Syntax

\n
\n

js

\n
replace(pattern, replacement)\n
\n

Parameters

\n
pattern

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.

replacement

Can be a string or a function.

  • If it's a string, it will replace the substring matched by pattern. A number of special replacement patterns are supported; see the Specifying a string as the replacement section below.
  • If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the Specifying a function as the replacement section below.

Return value

\n

A new string, with one, some, or all matches of the pattern replaced by the specified replacement.

Description

\n
\n

This method does not mutate the string value it's called on. It returns a new string.

A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead.

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replace(). In this case the behavior of replace() is entirely encoded by the @@replace method — for example, any mention of \"capturing groups\" in the description below is actually functionality provided by RegExp.prototype[@@replace].

If the pattern is an empty string, the replacement is prepended to the start of the string.

\n

js

\n
\"xxx\".replace(\"\", \"_\"); // \"_xxx\"\n
\n

A regexp with the g flag is the only case where replace() replaces more than once. For more information about how regex properties (especially the sticky flag) interact with replace(), see RegExp.prototype[@@replace]().

\n

Specifying a string as the replacement

\n
\n

The replacement string can include the following special replacement patterns:

Pattern Inserts
$$ Inserts a \"$\".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Inserts the nth (1-indexed) capturing group where n is a positive integer less than 100.
$<Name> Inserts the named capturing group where Name is the group name.

$n and $<Name> are only available if the pattern argument is a RegExp object. If the pattern is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string.

\n

js

\n
\"foo\".replace(/(f)/, \"$2\");\n// \"$2oo\"; the regex doesn't have the second group\n\n\"foo\".replace(\"f\", \"$1\");\n// \"$1oo\"; the pattern is a string, so it doesn't have any groups\n\n\"foo\".replace(/(f)|(g)/, \"$2\");\n// \"oo\"; the second group exists but isn't matched\n
\n
\n

Specifying a function as the replacement

\n
\n

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

Note: The above-mentioned special replacement patterns do not apply for strings returned from the replacer function.

The function has the following signature:

\n

js

\n
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {\n  return replacement;\n}\n
\n

The arguments to the function are as follows:

match

The matched substring. (Corresponds to $& above.)

p1, p2, …, pN

The nth string found by a capture group (including named capturing groups), provided the first argument to replace() is a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if the pattern is /(\\a+)(\\b+)/, then p1 is the match for \\a+, and p2 is the match for \\b+. If the group is part of a disjunction (e.g. \"abc\".replace(/(a)|(b)/, replacer)), the unmatched alternative will be undefined.

offset

The offset of the matched substring within the whole string being examined. For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.

string

The whole string being examined.

groups

An object whose keys are the used group names, and whose values are the matched portions (undefined if not matched). Only present if the pattern contains at least one named capturing group.

The exact number of arguments depends on whether the first argument is a RegExp object — and, if so, how many capture groups it has.

The following example will set newString to 'abc - 12345 - #$*%':

\n

js

\n
function replacer(match, p1, p2, p3, offset, string) {\n  // p1 is non-digits, p2 digits, and p3 non-alphanumerics\n  return [p1, p2, p3].join(\" - \");\n}\nconst newString = \"abc12345#$*%\".replace(/([^\\d]*)(\\d*)([^\\w]*)/, replacer);\nconsole.log(newString); // abc - 12345 - #$*%\n
\n

The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

\n

Examples

\n

Defining the regular expression in replace()

\n
\n

In the following example, the regular expression is defined in replace() and includes the ignore case flag.

\n

js

\n
const str = \"Twas the night before Xmas...\";\nconst newstr = str.replace(/xmas/i, \"Christmas\");\nconsole.log(newstr); // Twas the night before Christmas...\n
\n

This logs 'Twas the night before Christmas...'.

Note: See the regular expression guide for more explanations about regular expressions.

\n

Using the global and ignoreCase flags with replace()

\n
\n

Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits replace() to replace each occurrence of 'apples' in the string with 'oranges'.

\n

js

\n
const re = /apples/gi;\nconst str = \"Apples are round, and apples are juicy.\";\nconst newstr = str.replace(re, \"oranges\");\nconsole.log(newstr); // oranges are round, and oranges are juicy.\n
\n

This logs 'oranges are round, and oranges are juicy'.

\n

Switching words in a string

\n
\n

The following script switches the words in the string. For the replacement text, the script uses capturing groups and the $1 and $2 replacement patterns.

\n

js

\n
const re = /(\\w+)\\s(\\w+)/;\nconst str = \"Maria Cruz\";\nconst newstr = str.replace(re, \"$2, $1\");\nconsole.log(newstr); // Cruz, Maria\n
\n

This logs 'Cruz, Maria'.

\n

Using an inline function that modifies the matched characters

\n
\n

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.

The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.

\n

js

\n
function styleHyphenFormat(propertyName) {\n  function upperToHyphenLower(match, offset, string) {\n    return (offset > 0 ? \"-\" : \"\") + match.toLowerCase();\n  }\n  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);\n}\n
\n

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the toLowerCase() method. If we had tried to do this using the match without a function, the toLowerCase() would have no effect.

\n

js

\n
// Won't work\nconst newString = propertyName.replace(/[A-Z]/g, \"-\" + \"$&\".toLowerCase());\n
\n

This is because '$&'.toLowerCase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern.

\n

Replacing a Fahrenheit degree with its Celsius equivalent

\n
\n

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with \"F\". The function returns the Celsius number ending with \"C\". For example, if the input number is \"212F\", the function returns \"100C\". If the number is \"0F\", the function returns \"-17.77777777777778C\".

The regular expression test checks for any number that ends with F. The number of Fahrenheit degrees is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the number of Fahrenheit degrees passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

\n

js

\n
function f2c(x) {\n  function convert(str, p1, offset, s) {\n    return `${((p1 - 32) * 5) / 9}C`;\n  }\n  const s = String(x);\n  const test = /(-?\\d+(?:\\.\\d*)?)F\\b/g;\n  return s.replace(test, convert);\n}\n
\n
\n

Making a generic replacer

\n
\n

Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives the offset parameter, it will be trivial if the regex is statically known.

\n

js

\n
\"abcd\".replace(/(bc)/, (match, p1, offset) => `${match} (${offset}) `);\n// \"abc (1) d\"\n
\n

However, this replacer would be hard to generalize if we want it to work with any regex pattern. The replacer is variadic — the number of arguments it receives depends on the number of capturing groups present. We can use rest parameters, but it would also collect offset, string, etc. into the array. The fact that groups may or may not be passed depending on the identity of the regex would also make it hard to generically know which argument corresponds to the offset.

\n

js

\n
function addOffset(match, ...args) {\n  const offset = args.at(-2);\n  return `${match} (${offset}) `;\n}\n\nconsole.log(\"abcd\".replace(/(bc)/, addOffset)); // \"abc (1) d\"\nconsole.log(\"abcd\".replace(/(?<group>bc)/, addOffset)); // \"abc (abcd) d\"\n
\n

The addOffset example above doesn't work when the regex contains a named group, because in this case args.at(-2) would be the string instead of the offset.

Instead, you need to extract the last few arguments based on type, because groups is an object while string is a string.

\n

js

\n
function addOffset(match, ...args) {\n  const hasNamedGroups = typeof args.at(-1) === \"object\";\n  const offset = hasNamedGroups ? args.at(-3) : args.at(-2);\n  return `${match} (${offset}) `;\n}\n\nconsole.log(\"abcd\".replace(/(bc)/, addOffset)); // \"abc (1) d\"\nconsole.log(\"abcd\".replace(/(?<group>bc)/, addOffset)); // \"abc (1) d\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.replace
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
replace11215.5
4–5.5A replacement function as second argument is not supported.
\n
414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace\n

\n
\n", + "global_objects/symbol/search": "

Symbol.search

\n

The Symbol.search static data property represents the well-known symbol @@search. The String.prototype.search() method looks up this symbol on its first argument for the method that returns the index within a string that matches the current object.

For more information, see RegExp.prototype[@@search]() and String.prototype.search().

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@search.

\n
Property attributes of Symbol.search\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

Custom string search

\n
\n

js

\n
class caseInsensitiveSearch {\n  constructor(value) {\n    this.value = value.toLowerCase();\n  }\n  [Symbol.search](string) {\n    return string.toLowerCase().indexOf(this.value);\n  }\n}\n\nconsole.log(\"foobar\".search(new caseInsensitiveSearch(\"BaR\"))); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.search
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
search507949No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/search\n

\n
\n", + "global_objects/string/search": "

String.prototype.search()

The search() method of String values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.

\n

Try it

\n

Syntax

\n
\n

js

\n
search(regexp)\n
\n

Parameters

\n
regexp

A regular expression object, or any object that has a Symbol.search method.

If regexp is not a RegExp object and does not have a Symbol.search method, it is implicitly converted to a RegExp by using new RegExp(regexp).

Return value

\n

The index of the first match between the regular expression and the given string, or -1 if no match was found.

Description

\n
\n

The implementation of String.prototype.search() itself is very simple — it simply calls the Symbol.search method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[@@search]().

The g flag of regexp has no effect on the search() result, and the search always happens as if the regex's lastIndex is 0. For more information on the behavior of search(), see RegExp.prototype[@@search]().

When you want to know whether a pattern is found, and also know its index within a string, use search().

\n

Examples

\n

Using search()

\n
\n

The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1).

\n

js

\n
const str = \"hey JudE\";\nconst re = /[A-Z]/;\nconst reDot = /[.]/;\nconsole.log(str.search(re)); // returns 4, which is the index of the first capital letter \"J\"\nconsole.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.search
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
search11214414.418410.111.01.00.10.0
flagsNoNo1–49NoNoNoNoNo4–49NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search\n

\n
\n", + "global_objects/symbol/species": "

Symbol.species

\n

The Symbol.species static data property represents the well-known symbol @@species. Methods that create copies of an object may look up this symbol on the object for the constructor function to use when creating the copy.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@species.

\n
Property attributes of Symbol.species\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The @@species accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as map(). the map() method uses instance.constructor[Symbol.species] to get the constructor for constructing the new array. For more information, see subclassing built-ins.

All built-in implementations of @@species return the this value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, map() will return an array of the same type as the original array.

\n

Examples

\n

Using species

\n
\n

You might want to return Array objects in your derived array class MyArray. For example, when using methods such as map() that return the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The species symbol lets you do this:

\n

js

\n
class MyArray extends Array {\n  // Overwrite species to the parent Array constructor\n  static get [Symbol.species]() {\n    return Array;\n  }\n}\nconst a = new MyArray(1, 2, 3);\nconst mapped = a.map((x) => x * x);\n\nconsole.log(mapped instanceof MyArray); // false\nconsole.log(mapped instanceof Array); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
species511341No381051514141105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species\n

\n
\n", + "global_objects/symbol/split": "

Symbol.split

\n

The Symbol.split static data property represents the well-known symbol @@split. The String.prototype.split() method looks up this symbol on its first argument for the method that splits a string at the indices that match the current object.

For more information, seeRegExp.prototype[@@split]() and String.prototype.split().

\n
\n

Try it

\n

Value

\n
\n

The well-known symbol @@split.

\n
Property attributes of Symbol.split\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

Custom reverse split

\n
\n

js

\n
class ReverseSplit {\n  [Symbol.split](string) {\n    const array = string.split(\" \");\n    return array.reverse();\n  }\n}\n\nconsole.log(\"Another one bites the dust\".split(new ReverseSplit()));\n// [ \"dust\", \"the\", \"bites\", \"one\", \"Another\" ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.split
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
split507949No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split\n

\n
\n", + "global_objects/string/split": "

String.prototype.split()

The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
split(separator)\nsplit(separator, limit)\n
\n

Parameters

\n
separator

The pattern describing where each split should occur. Can be undefined, a string, or an object with a Symbol.split method — the typical example being a regular expression. Omitting separator or passing undefined causes split() to return an array with the calling string as a single element. All values that are not undefined or objects with a @@split method are coerced to strings.

\nlimit Optional\n

A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

  • The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
  • If limit is 0, [] is returned.

Return value

\n

An Array of strings, split at each point where the separator occurs in the given string.

Description

\n
\n

If separator is a non-empty string, the target string is split by all matches of the separator without including separator in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like myString.split(\"\\t\"). If separator contains multiple characters, that entire character sequence must be found in order to split. If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If separator does not occur in str, the returned array contains one element consisting of the entire string.

If separator is an empty string (\"\"), str is converted to an array of each of its UTF-16 \"characters\", without empty strings on either ends of the resulting string.

Note: \"\".split(\"\") is therefore the only way to produce an empty array when a string is passed as separator.

Warning: When the empty string (\"\") is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (code points), but by UTF-16 code units. This destroys surrogate pairs. See \"How do you get a string to a character array in JavaScript?\" on StackOverflow.

If separator is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is Unicode-aware.

\n

js

\n
\"😄😄\".split(/(?:)/); // [ \"\\ud83d\", \"\\ude04\", \"\\ud83d\", \"\\ude04\" ]\n\"😄😄\".split(/(?:)/u); // [ \"😄\", \"😄\" ]\n
\n

If separator is a regular expression with capturing groups, then each time separator matches, the captured groups (including any undefined results) are spliced into the output array. This behavior is specified by the regexp's Symbol.split method.

If separator is an object with a Symbol.split method, that method is called with the target string and limit as arguments, and this set to the object. Its return value becomes the return value of split.

Any other value will be coerced to a string before being used as separator.

\n

Examples

\n

Using split()

\n
\n

When the string is empty and a non-empty separator is specified, split() returns [\"\"]. If the string and separator are both empty strings, an empty array is returned.

\n

js

\n
const emptyString = \"\";\n\n// string is empty and separator is non-empty\nconsole.log(emptyString.split(\"a\"));\n// [\"\"]\n\n// string and separator are both empty strings\nconsole.log(emptyString.split(emptyString));\n// []\n
\n

The following example defines a function that splits a string into an array of strings using separator. After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

\n

js

\n
function splitString(stringToSplit, separator) {\n  const arrayOfStrings = stringToSplit.split(separator);\n\n  console.log(\"The original string is:\", stringToSplit);\n  console.log(\"The separator is:\", separator);\n  console.log(\n    \"The array has\",\n    arrayOfStrings.length,\n    \"elements:\",\n    arrayOfStrings.join(\" / \"),\n  );\n}\n\nconst tempestString = \"Oh brave new world that has such people in it.\";\nconst monthString = \"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\";\n\nconst space = \" \";\nconst comma = \",\";\n\nsplitString(tempestString, space);\nsplitString(tempestString);\nsplitString(monthString, comma);\n
\n

This example produces the following output:

The original string is: \"Oh brave new world that has such people in it.\"\nThe separator is: \" \"\nThe array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.\n\nThe original string is: \"Oh brave new world that has such people in it.\"\nThe separator is: \"undefined\"\nThe array has 1 elements: Oh brave new world that has such people in it.\n\nThe original string is: \"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\"\nThe separator is: \",\"\nThe array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec\n
\n

Removing spaces from a string

\n
\n

In the following example, split() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and the semicolon from the string. nameList is the array returned as a result of split().

\n

js

\n
const names = \"Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand \";\n\nconsole.log(names);\n\nconst re = /\\s*(?:;|$)\\s*/;\nconst nameList = names.split(re);\n\nconsole.log(nameList);\n
\n

This logs two lines; the first line logs the original string, and the second line logs the resulting array.

Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand\n[ \"Harry Trump\", \"Fred Barney\", \"Helen Rigby\", \"Bill Abel\", \"Chris Hand\", \"\" ]\n
\n

Returning a limited number of splits

\n
\n

In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.

\n

js

\n
const myString = \"Hello World. How are you doing?\";\nconst splits = myString.split(\" \", 3);\n\nconsole.log(splits); // [ \"Hello\", \"World.\", \"How\" ]\n
\n
\n

Splitting with a RegExp to include parts of the separator in the result

\n
\n

If separator is a regular expression that contains capturing parentheses ( ), matched results are included in the array.

\n

js

\n
const myString = \"Hello 1 word. Sentence number 2.\";\nconst splits = myString.split(/(\\d)/);\n\nconsole.log(splits);\n// [ \"Hello \", \"1\", \" word. Sentence number \", \"2\", \".\" ]\n
\n

Note: \\d matches the character class for digits between 0 and 9.

\n

Using a custom splitter

\n
\n

An object with a Symbol.split method can be used as a splitter with custom behavior.

The following example splits a string using an internal state consisting of an incrementing number:

\n

js

\n
const splitByNumber = {\n  [Symbol.split](str) {\n    let num = 1;\n    let pos = 0;\n    const result = [];\n    while (pos < str.length) {\n      const matchPos = str.indexOf(num, pos);\n      if (matchPos === -1) {\n        result.push(str.substring(pos));\n        break;\n      }\n      result.push(str.substring(pos, matchPos));\n      pos = matchPos + String(num).length;\n      num++;\n    }\n    return result;\n  },\n};\n\nconst myString = \"a1bc2c5d3e4f\";\nconsole.log(myString.split(splitByNumber)); // [ \"a\", \"bc\", \"c5d\", \"e\", \"f\" ]\n
\n

The following example uses an internal state to enforce certain behavior, and to ensure a \"valid\" result is produced.

\n

js

\n
const DELIMITER = \";\";\n\n// Split the commands, but remove any invalid or unnecessary values.\nconst splitCommands = {\n  [Symbol.split](str, lim) {\n    const results = [];\n    const state = {\n      on: false,\n      brightness: {\n        current: 2,\n        min: 1,\n        max: 3,\n      },\n    };\n    let pos = 0;\n    let matchPos = str.indexOf(DELIMITER, pos);\n\n    while (matchPos !== -1) {\n      const subString = str.slice(pos, matchPos).trim();\n\n      switch (subString) {\n        case \"light on\":\n          // If the `on` state is already true, do nothing.\n          if (!state.on) {\n            state.on = true;\n            results.push(subString);\n          }\n          break;\n\n        case \"light off\":\n          // If the `on` state is already false, do nothing.\n          if (state.on) {\n            state.on = false;\n            results.push(subString);\n          }\n          break;\n\n        case \"brightness up\":\n          // Enforce a brightness maximum.\n          if (state.brightness.current < state.brightness.max) {\n            state.brightness.current += 1;\n            results.push(subString);\n          }\n          break;\n\n        case \"brightness down\":\n          // Enforce a brightness minimum.\n          if (state.brightness.current > state.brightness.min) {\n            state.brightness.current -= 1;\n            results.push(subString);\n          }\n          break;\n      }\n\n      if (results.length === lim) {\n        break;\n      }\n\n      pos = matchPos + DELIMITER.length;\n      matchPos = str.indexOf(DELIMITER, pos);\n    }\n\n    // If we broke early due to reaching the split `lim`, don't add the remaining commands.\n    if (results.length < lim) {\n      results.push(str.slice(pos).trim());\n    }\n\n    return results;\n  },\n};\n\nconst commands =\n  \"light on; brightness up; brightness up; brightness up; light on; brightness down; brightness down; light off\";\nconsole.log(commands.split(splitCommands, 3)); // [\"light on\", \"brightness up\", \"brightness down\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.split
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
split11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\n

\n
\n", + "global_objects/symbol/toprimitive": "

Symbol.toPrimitive

The Symbol.toPrimitive static data property represents the well-known symbol @@toPrimitive. All type coercion algorithms look up this symbol on objects for the method that accepts a preferred type and returns a primitive representation of the object, before falling back to using the object's valueOf() and toString() methods.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@toPrimitive.

\n
Property attributes of Symbol.toPrimitive\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

With the help of the Symbol.toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint, which specifies the preferred type of the result primitive value. The hint argument can be one of \"number\", \"string\", and \"default\".

The \"number\" hint is used by numeric coercion algorithms. The \"string\" hint is used by the string coercion algorithm. The \"default\" hint is used by the primitive coercion algorithm. The hint only acts as a weak signal of preference, and the implementation is free to ignore it (as Symbol.prototype[@@toPrimitive]() does). The language does not enforce alignment between the hint and the result type, although [@@toPrimitive]() must return a primitive, or a TypeError is thrown.

Objects without the @@toPrimitive property are converted to primitives by calling the valueOf() and toString() methods in different orders, which is explained in more detail in the type coercion section. @@toPrimitive allows full control over the primitive conversion process. For example, Date.prototype[@@toPrimitive] treats \"default\" as if it's \"string\" and calls toString() instead of valueOf(). Symbol.prototype[@@toPrimitive] ignores the hint and always returns a symbol, which means even in string contexts, Symbol.prototype.toString() won't be called, and Symbol objects must always be explicitly converted to strings through String().

\n

Examples

\n

Modifying primitive values converted from an object

\n
\n

Following example describes how Symbol.toPrimitive property can modify the primitive value converted from an object.

\n

js

\n
// An object without Symbol.toPrimitive property.\nconst obj1 = {};\nconsole.log(+obj1); // NaN\nconsole.log(`${obj1}`); // \"[object Object]\"\nconsole.log(obj1 + \"\"); // \"[object Object]\"\n\n// An object with Symbol.toPrimitive property.\nconst obj2 = {\n  [Symbol.toPrimitive](hint) {\n    if (hint === \"number\") {\n      return 10;\n    }\n    if (hint === \"string\") {\n      return \"hello\";\n    }\n    return true;\n  },\n};\nconsole.log(+obj2); // 10        — hint is \"number\"\nconsole.log(`${obj2}`); // \"hello\"   — hint is \"string\"\nconsole.log(obj2 + \"\"); // \"true\"    — hint is \"default\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.toprimitive
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toPrimitive471544No341047474434105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive\n

\n
\n", + "global_objects/symbol/tostringtag": "

Symbol.toStringTag

The Symbol.toStringTag static data property represents the well-known symbol @@toStringTag. Object.prototype.toString() looks up this symbol on the this value for the property containing a string that represents the type of the object.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@toStringTag.

\n
Property attributes of Symbol.toStringTag\n
Writable no
Enumerable no
Configurable no
\n

Examples

\n

Default tags

\n
\n

Some values do not have Symbol.toStringTag, but have special toString() representations. For a complete list, see Object.prototype.toString().

\n

js

\n
Object.prototype.toString.call(\"foo\"); // \"[object String]\"\nObject.prototype.toString.call([1, 2]); // \"[object Array]\"\nObject.prototype.toString.call(3); // \"[object Number]\"\nObject.prototype.toString.call(true); // \"[object Boolean]\"\nObject.prototype.toString.call(undefined); // \"[object Undefined]\"\nObject.prototype.toString.call(null); // \"[object Null]\"\n// ... and more\n
\n
\n

Built-in toStringTag symbols

\n
\n

Most built-in objects provide their own @@toStringTag property. Almost all built-in objects' @@toStringTag property is not writable, not enumerable, and configurable; the exception is Iterator, which is writable for compatibility reasons.

For constructor objects like Promise, the property is installed on Constructor.prototype, so that all instances of the constructor inherit @@toStringTag and can be stringified. For non-constructor objects like Math and JSON, the property is installed as a static property, so that the namespace object itself can be stringified. Sometimes, the constructor also provides its own toString method (for example, Intl.Locale), in which case the @@toStringTag property is only used when you explicitly call Object.prototype.toString on it.

\n

js

\n
Object.prototype.toString.call(new Map()); // \"[object Map]\"\nObject.prototype.toString.call(function* () {}); // \"[object GeneratorFunction]\"\nObject.prototype.toString.call(Promise.resolve()); // \"[object Promise]\"\n// ... and more\n
\n
\n

Custom tag with toStringTag

\n
\n

When creating your own class, JavaScript defaults to the \"Object\" tag:

\n

js

\n
class ValidatorClass {}\n\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Object]\"\n
\n

Now, with the help of toStringTag, you are able to set your own custom tag:

\n

js

\n
class ValidatorClass {\n  get [Symbol.toStringTag]() {\n    return \"Validator\";\n  }\n}\n\nObject.prototype.toString.call(new ValidatorClass()); // \"[object Validator]\"\n
\n
\n

toStringTag available on all DOM prototype objects

\n
\n

Due to a WebIDL spec change in mid-2020, browsers are adding a Symbol.toStringTag property to all DOM prototype objects. For example, to access the Symbol.toStringTag property on HTMLButtonElement:

\n

js

\n
const test = document.createElement(\"button\");\ntest.toString(); // \"[object HTMLButtonElement]\"\ntest[Symbol.toStringTag]; // \"HTMLButtonElement\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.tostringtag
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toStringTag491551No361049495136105.01.06.0.0
dom_objects507978No371450507937145.01.0No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag\n

\n
\n", + "global_objects/symbol/unscopables": "

Symbol.unscopables

The Symbol.unscopables static data property represents the well-known symbol @@unscopables. The with statement looks up this symbol on the scope object for a property containing a collection of properties that should not become bindings within the with environment.

\n

Try it

\n

Value

\n
\n

The well-known symbol @@unscopables.

\n
Property attributes of Symbol.unscopables\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

The @@unscopables symbol (accessed via Symbol.unscopables) can be defined on any object to exclude property names from being exposed as lexical variables in with environment bindings. Note that when using strict mode, with statements are not available, and this symbol is likely not needed.

Setting a property of the @@unscopables object to true (or any truthy value) will make the corresponding property of the with scope object unscopable and therefore won't be introduced to the with body scope. Setting a property to false (or any falsy value) will make it scopable and thus appear as lexical scope variables.

When deciding whether x is unscopable, the entire prototype chain of the @@unscopables property is looked up for a property called x. This means if you declared @@unscopables as a plain object, Object.prototype properties like toString would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see an example below). You are advised to make your custom @@unscopables property have null as its prototype, like Array.prototype[@@unscopables] does.

This protocol is also utilized by DOM APIs, such as Element.prototype.append().

\n

Examples

\n

Scoping in with statements

\n
\n

The following code works fine in ES5 and below. However, in ECMAScript 2015 and later, the Array.prototype.keys() method was introduced. That means that inside a with environment, \"keys\" would now be the method and not the variable. That's why the @@unscopables symbol was introduced. A built-in @@unscopables setting is implemented as Array.prototype[@@unscopables] to prevent some of the Array methods being scoped into the with statement.

\n

js

\n
var keys = [];\n\nwith (Array.prototype) {\n  keys.push(\"something\");\n}\n
\n
\n

Unscopables in objects

\n
\n

You can also set @@unscopables for your own objects.

\n

js

\n
const obj = {\n  foo: 1,\n  bar: 2,\n  baz: 3,\n};\n\nobj[Symbol.unscopables] = {\n  // Make the object have `null` prototype to prevent\n  // `Object.prototype` methods from being unscopable\n  __proto__: null,\n  // `foo` will be scopable\n  foo: false,\n  // `bar` will be unscopable\n  bar: true,\n  // `baz` is omitted; because `undefined` is falsy, it is also scopable (default)\n};\n\nwith (obj) {\n  console.log(foo); // 1\n  console.log(bar); // ReferenceError: bar is not defined\n  console.log(baz); // 3\n}\n
\n
\n

Avoid using a non-null-prototype object as @@unscopables

\n
\n

Declaring @@unscopables as a plain object without eliminating its prototype may cause subtle bugs. Consider the following code working before @@unscopables:

\n

js

\n
const character = {\n  name: \"Yoda\",\n  toString: function () {\n    return \"Use with statements, you must not\";\n  },\n};\n\nwith (character) {\n  console.log(name + ' says: \"' + toString() + '\"'); // Yoda says: \"Use with statements, you must not\"\n}\n
\n

To preserve backward compatibility, you decided to add an @@unscopables property when adding more properties to character. You may naïvely do it like:

\n

js

\n
const character = {\n  name: \"Yoda\",\n  toString: function () {\n    return \"Use with statements, you must not\";\n  },\n  student: \"Luke\",\n  [Symbol.unscopables]: {\n    // Make `student` unscopable\n    student: true,\n  },\n};\n
\n

However, the code above now breaks:

\n

js

\n
with (character) {\n  console.log(name + ' says: \"' + toString() + '\"'); // Yoda says: \"[object Undefined]\"\n}\n
\n

This is because when looking up character[Symbol.unscopables].toString, it returns Object.prototype.toString(), which is a truthy value, thus making the toString() call in the with() statement reference globalThis.toString() instead — and because it's called without a this, this is undefined, making it return [object Undefined].

Even when the method is not overridden by character, making it unscopable will change the value of this.

\n

js

\n
const proto = {};\nconst obj = { __proto__: proto };\n\nwith (proto) {\n  console.log(isPrototypeOf(obj)); // true; `isPrototypeOf` is scoped and `this` is `proto`\n}\n\nproto[Symbol.unscopables] = {};\n\nwith (proto) {\n  console.log(isPrototypeOf(obj)); // TypeError: Cannot convert undefined or null to object\n  // `isPrototypeOf` is unscoped and `this` is undefined\n}\n
\n

To fix this, always make sure @@unscopables only contains properties you wish to be unscopable, without Object.prototype properties.

\n

js

\n
const character = {\n  name: \"Yoda\",\n  toString: function () {\n    return \"Use with statements, you must not\";\n  },\n  student: \"Luke\",\n  [Symbol.unscopables]: {\n    // Make the object have `null` prototype to prevent\n    // `Object.prototype` methods from being unscopable\n    __proto__: null,\n    // Make `student` unscopable\n    student: true,\n  },\n};\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.unscopables
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unscopables381248No2593838482593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables\n

\n
\n", + "global_objects/symbol/description": "

Symbol.prototype.description

The description accessor property of Symbol values returns a string containing the description of this symbol, or undefined if the symbol has no description.

\n

Try it

\n

Description

\n

Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. It is different to Symbol.prototype.toString() as it does not contain the enclosing \"Symbol()\" string. See the examples.

Examples

\n

Using description

\n
\n

js

\n
Symbol(\"desc\").toString(); // \"Symbol(desc)\"\nSymbol(\"desc\").description; // \"desc\"\nSymbol(\"\").description; // \"\"\nSymbol().description; // undefined\n\n// well-known symbols\nSymbol.iterator.toString(); // \"Symbol(Symbol.iterator)\"\nSymbol.iterator.description; // \"Symbol.iterator\"\n\n// global symbols\nSymbol.for(\"foo\").toString(); // \"Symbol(foo)\"\nSymbol.for(\"foo\").description; // \"foo\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.prototype.description
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
description707963No5712.1
12No support for an undefined description.
\n
7070634912.2
12No support for an undefined description.
\n
10.01.011.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description\n

\n
\n", + "global_objects/symbol/tostring": "

Symbol.prototype.toString()

The toString() method of Symbol values returns a string representing this symbol value.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the specified symbol value.

Description

\n
\n

The Symbol object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For Symbol values, the toString method returns a descriptive string in the form \"Symbol(description)\", where description is the symbol's description.

The toString() method requires its this value to be a Symbol primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to symbol values.

Because Symbol has a [@@toPrimitive]() method, that method always takes priority over toString() when a Symbol object is coerced to a string. However, because Symbol.prototype[@@toPrimitive]() returns a symbol primitive, and symbol primitives throw a TypeError when implicitly converted to a string, the toString() method is never implicitly called by the language. To stringify a symbol, you must explicitly call its toString() method or use the String() function.

\n

Examples

\n

Using toString()

\n
\n

js

\n
Symbol(\"desc\").toString(); // \"Symbol(desc)\"\n\n// well-known symbols\nSymbol.iterator.toString(); // \"Symbol(Symbol.iterator)\"\n\n// global symbols\nSymbol.for(\"foo\").toString(); // \"Symbol(foo)\"\n
\n

Implicitly calling toString()

\n
\n

The only way to make JavaScript implicitly call toString() instead of [@@toPrimitive]() on a symbol wrapper object is by deleting the @@toPrimitive method first.

Warning: You should not do this in practice. Never mutate built-in objects unless you know exactly what you're doing.

\n

js

\n
delete Symbol.prototype[Symbol.toPrimitive];\nconsole.log(`${Object(Symbol(\"foo\"))}`); // \"Symbol(foo)\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString381236No2593838362593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toString\n

\n
\n", + "global_objects/symbol/valueof": "

Symbol.prototype.valueOf()

The valueOf() method of Symbol values returns this symbol value.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

The primitive value of the specified Symbol object.

Description

\n
\n

The valueOf() method of Symbol returns the primitive value of a Symbol object as a Symbol data type.

JavaScript calls the valueOf() method to convert an object to a primitive value. You rarely need to invoke the valueOf() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

\n

Examples

\n

Using valueOf()

\n
\n

js

\n
const sym = Symbol(\"example\");\nsym === sym.valueOf(); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf381236No2593838362593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/valueOf\n

\n
\n", + "global_objects/symbol/@@toprimitive": "

Symbol.prototype[@@toPrimitive]()

The [@@toPrimitive]() method of Symbol values returns this symbol value.

\n

Syntax

\n
\n

js

\n
symbolValue[Symbol.toPrimitive](hint)\n
\n

Parameters

\n
hint

A string value indicating the primitive value to return. The value is ignored.

Return value

\n

The primitive value of the specified Symbol object.

Description

\n
\n

The [@@toPrimitive]() method of Symbol returns the primitive value of a Symbol object as a Symbol data type. The hint argument is not used.

JavaScript calls the [@@toPrimitive]() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

\n

Examples

\n

Using @@toPrimitive

\n
\n

js

\n
const sym = Symbol(\"example\");\nsym === sym[Symbol.toPrimitive](); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-symbol.prototype-@@toprimitive
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@toPrimitive471544No341047474434105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive\n

\n
\n", + "global_objects/error/error": "

Error() constructor

The Error() constructor creates Error objects.

\n

Syntax

\n
\n
\n

js

\n
new Error()\nnew Error(message)\nnew Error(message, options)\nnew Error(message, fileName)\nnew Error(message, fileName, lineNumber)\n\nError()\nError(message)\nError(message, options)\nError(message, fileName)\nError(message, fileName, lineNumber)\n
\n

Note: Error() can be called with or without new. Both create a new Error instance.

\n

Parameters

\n
\nmessage Optional\n

A human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A value indicating the specific cause of the error, reflected in the cause property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The path to the file that raised this error, reflected in the fileName property. Defaults to the name of the file containing the code that called the Error() constructor.

\nlineNumber Optional Non-standard \n

The line number within the file on which the error was raised, reflected in the lineNumber property. Defaults to the line number containing the Error() constructor invocation.

Examples

\n

Function call or new construction

\n
\n

When Error is used like a function, that is without new, it will return an Error object. Therefore, a mere call to Error will produce the same output that constructing an Error object via the new keyword would.

\n

js

\n
const x = Error(\"I was created using a function call!\");\n\n// above has the same functionality as following\nconst y = new Error('I was constructed via the \"new\" keyword!');\n
\n
\n

Rethrowing an error with a cause

\n
\n

It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new Error, as shown.

\n

js

\n
try {\n  frameworkThatCanThrow();\n} catch (err) {\n  throw new Error(\"New error message\", { cause: err });\n}\n
\n

For a more detailed example see Error > Differentiate between similar errors.

\n

Omitting options argument

\n
\n

JavaScript only tries to read options.cause if options is an object — this avoids ambiguity with the other non-standard Error(message, fileName, lineNumber) signature, which requires the second parameter to be a string. If you omit options, pass a primitive value as options, or pass an object without the cause property, then the created Error object will have no cause property.

\n

js

\n
// Omitting options\nconst error1 = new Error(\"Error message\");\nconsole.log(\"cause\" in error1); // false\n\n// Passing a primitive value\nconst error2 = new Error(\"Error message\", \"\");\nconsole.log(\"cause\" in error2); // false\n\n// Passing an object without a cause property\nconst error3 = new Error(\"Error message\", { details: \"http error\" });\nconsole.log(\"cause\" in error3); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-error-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Error11216414.418410.111.01.00.10.0
fileName_parameterNoNo1NoNoNoNoNo4NoNoNoNoNo
lineNumber_parameterNoNo1NoNoNoNoNo4NoNoNoNoNo
options_cause_parameter939391No7915939391661517.01.1316.9.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error\n

\n
\n", + "global_objects/error/stack": "

Error.prototype.stack

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The non-standard stack property of an Error instance offers a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call.

\n
\n

Value

\n
\n

A string.

Because the stack property is non-standard, implementations differ about where it's installed.

\n
Property attributes of Error.prototype.stack\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n
\n

Each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number. (Note that the Error object also possesses the fileName, lineNumber and columnNumber properties for retrieving these from the error thrown (but only the error, and not its trace).)

Note that this is the format used by Firefox. There is no standard formatting. However, Safari 6+ and Opera 12- use a very similar format. Browsers using the V8 JavaScript engine (such as Chrome, Opera 15+, Android Browser) and IE10+, on the other hand, uses a different format.

Argument values in the stack: Prior to Firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign. While an object (or array, etc.) would appear in the converted form \"[object Object]\", and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be — it is still possible in Firefox 14 — easier to use arguments.callee.caller.arguments, as could the function name be retrieved by arguments.callee.caller.name). \"undefined\" is listed as \"(void 0)\". Note that if string arguments were passed in with values such as \"@\", \"(\", \")\" (or if in file names), you could not easily rely on these for breaking the line into its component parts. Thus, in Firefox 14 and later this is less of an issue.

Different browsers set this value at different times. For example, Firefox sets it when creating an Error object, while PhantomJS sets it only when throwing the Error, and archived MSDN docs also seem to match the PhantomJS implementation.

\n

Examples

\n

Using the stack property

\n
\n

The following HTML markup demonstrates the use of stack property.

\n

html

\n
<!doctype html>\n<meta charset=\"UTF-8\" />\n<title>Stack Trace Example</title>\n<body>\n  <script>\n    function trace() {\n      try {\n        throw new Error(\"myError\");\n      } catch (e) {\n        alert(e.stack);\n      }\n    }\n    function b() {\n      trace();\n    }\n    function a() {\n      b(3, 4, \"\\n\\n\", undefined, {});\n    }\n    a(\"first call, firstarg\");\n  </script>\n</body>\n
\n

Assuming the above markup is saved as C:\\example.html on a Windows file system it produces an alert message box with the following text:

Starting with Firefox 30 and later containing the column number:

trace@file:///C:/example.html:9:17\nb@file:///C:/example.html:16:13\na@file:///C:/example.html:19:13\n@file:///C:/example.html:21:9\n

Firefox 14 to Firefox 29:

trace@file:///C:/example.html:9\nb@file:///C:/example.html:16\na@file:///C:/example.html:19\n@file:///C:/example.html:21\n

Firefox 13 and earlier would instead produce the following text:

Error(\"myError\")@:0\ntrace()@file:///C:/example.html:9\nb(3,4,\"\\n\\n\",(void 0),[object Object])@file:///C:/example.html:16\na(\"first call, firstarg\")@file:///C:/example.html:19\n@file:///C:/example.html:21\n
\n

Stack of eval'ed code

\n
\n

Starting with Firefox 30, the error stack of code in Function() and eval() calls, now produces stacks with more detailed information about the line and column numbers inside these calls. Function calls are indicated with \"> Function\" and eval calls with \"> eval\".

\n

js

\n
try {\n  new Function(\"throw new Error()\")();\n} catch (e) {\n  console.log(e.stack);\n}\n\n// anonymous@file:///C:/example.html line 7 > Function:1:1\n// @file:///C:/example.html:7:6\n\ntry {\n  eval(\"eval('FAIL')\");\n} catch (x) {\n  console.log(x.stack);\n}\n\n// @file:///C:/example.html line 7 > eval line 1 > eval:1:1\n// @file:///C:/example.html line 7 > eval:1:1\n// @file:///C:/example.html:7:6\n
\n

You can also use the //# sourceURL directive to name an eval source. See also Debug eval sources in the Debugger docs and this blog post.

\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
stack31211010.56≤371841161.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack\n

\n
\n", + "global_objects/error/cause": "

Error: cause

\n

The cause data property of an Error instance indicates the specific original cause of the error.

It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error.

\n
\n

Value

\n
\n

The value that was passed to the Error() constructor in the options.cause argument. It may not be present.

\n
Property attributes of Error: cause\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n

The value of cause can be of any type. You should not make assumptions that the error you caught has an Error as its cause, in the same way that you cannot be sure the variable bound in the catch statement is an Error either. The \"Providing structured data as the error cause\" example below shows a case where a non-error is deliberately provided as the cause.

Examples

\n

Rethrowing an error with a cause

\n
\n

It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new Error, as shown.

\n

js

\n
try {\n  connectToDatabase();\n} catch (err) {\n  throw new Error(\"Connecting to database failed.\", { cause: err });\n}\n
\n

For a more detailed example see Error > Differentiate between similar errors.

\n

Providing structured data as the error cause

\n
\n

Error messages written for human consumption may be inappropriate for machine parsing — since they're subject to rewording or punctuation changes that may break any existing parsing written to consume them. So when throwing an error from a function, as an alternative to a human-readable error message, you can instead provide the cause as structured data, for machine parsing.

\n

js

\n
function makeRSA(p, q) {\n  if (!Number.isInteger(p) || !Number.isInteger(q)) {\n    throw new Error(\"RSA key generation requires integer inputs.\", {\n      cause: { code: \"NonInteger\", values: [p, q] },\n    });\n  }\n  if (!areCoprime(p, q)) {\n    throw new Error(\"RSA key generation requires two co-prime integers.\", {\n      cause: { code: \"NonCoprime\", values: [p, q] },\n    });\n  }\n  // rsa algorithm…\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-installerrorcause
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
cause939391No7915939391661517.01.1316.9.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n

\n
\n", + "global_objects/error/columnnumber": "

Error: columnNumber

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The columnNumber data property of an Error instance contains the column number in the line of the file that raised this error.

\n
\n

Value

\n
\n

A positive integer.

\n
Property attributes of Error: columnNumber\n
Writable yes
Enumerable no
Configurable yes
\n

Examples

\n

Using columnNumber

\n
\n

js

\n
try {\n  throw new Error(\"Could not parse input\");\n} catch (err) {\n  console.log(err.columnNumber); // 9\n}\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
columnNumberNoNo1NoNoNoNoNo4NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/columnNumber\n

\n
\n", + "global_objects/error/filename": "

Error: fileName

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The fileName data property of an Error instance contains the path to the file that raised this error.

\n
\n

Value

\n
\n

A string.

\n
Property attributes of Error: fileName\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n

This non-standard property contains the path to the file that raised this error. If called from a debugger context, the Firefox Developer Tools for example, \"debugger eval code\" is returned.

Examples

\n

Using fileName

\n
\n

js

\n
const e = new Error(\"Could not parse input\");\nthrow e;\n// e.fileName could look like \"file:///C:/example.html\"\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fileNameNoNo1NoNoNoNoNo4NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/fileName\n

\n
\n", + "global_objects/error/linenumber": "

Error: lineNumber

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The lineNumber data property of an Error instance contains the line number in the file that raised this error.

\n
\n

Value

\n
\n

A positive integer.

\n
Property attributes of Error: lineNumber\n
Writable yes
Enumerable no
Configurable yes
\n

Examples

\n

Using lineNumber

\n
\n

js

\n
try {\n  throw new Error(\"Could not parse input\");\n} catch (err) {\n  console.log(err.lineNumber); // 2\n}\n
\n

Alternative example using error event

\n
\n
\n

js

\n
window.addEventListener(\"error\", (e) => {\n  console.log(e.lineNumber); // 5\n});\nconst e = new Error(\"Could not parse input\");\nthrow e;\n
\n

This is not a standard feature and lacks widespread support. See the browser compatibility table below.

\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lineNumberNoNo1NoNoNoNoNo4NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/lineNumber\n

\n
\n", + "global_objects/error/message": "

Error: message

The message data property of an Error instance is a human-readable description of the error.

\n

Value

\n
\n

A string corresponding to the value passed to the Error() constructor as the first argument.

\n
Property attributes of Error: message\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n
\n

This property contains a brief description of the error if one is available or has been set. The message property combined with the name property is used by the Error.prototype.toString() method to create a string representation of the Error.

By default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the Error constructor.

\n

Examples

\n

Throwing a custom error

\n
\n

js

\n
const e = new Error(\"Could not parse input\");\n// e.message is 'Could not parse input'\nthrow e;\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-error.prototype.message
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
message11216514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/message\n

\n
\n", + "global_objects/error/tostring": "

Error.prototype.toString()

The toString() method of Error instances returns a string representing this error.

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the specified Error object.

Description

\n
\n

The Error object overrides the Object.prototype.toString() method inherited by all objects. Its semantics are as follows:

\n

js

\n
Error.prototype.toString = function () {\n  if (\n    this === null ||\n    (typeof this !== \"object\" && typeof this !== \"function\")\n  ) {\n    throw new TypeError();\n  }\n  let name = this.name;\n  name = name === undefined ? \"Error\" : `${name}`;\n  let msg = this.message;\n  msg = msg === undefined ? \"\" : `${msg}`;\n  if (name === \"\") {\n    return msg;\n  }\n  if (msg === \"\") {\n    return name;\n  }\n  return `${name}: ${msg}`;\n};\n
\n
\n

Examples

\n

Using toString()

\n
\n

js

\n
const e1 = new Error(\"fatal error\");\nconsole.log(e1.toString()); // \"Error: fatal error\"\n\nconst e2 = new Error(\"fatal error\");\ne2.name = undefined;\nconsole.log(e2.toString()); // \"Error: fatal error\"\n\nconst e3 = new Error(\"fatal error\");\ne3.name = \"\";\nconsole.log(e3.toString()); // \"fatal error\"\n\nconst e4 = new Error(\"fatal error\");\ne4.name = \"\";\ne4.message = undefined;\nconsole.log(e4.toString()); // \"\"\n\nconst e5 = new Error(\"fatal error\");\ne5.name = \"hello\";\ne5.message = undefined;\nconsole.log(e5.toString()); // \"hello\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-error.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11216414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString\n

\n
\n", + "global_objects/reflect/construct": "

Reflect.construct()

The Reflect.construct() static method is like the new operator, but as a function. It is equivalent to calling new target(...args). It gives also the added option to specify a different new.target value.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.construct(target, argumentsList)\nReflect.construct(target, argumentsList, newTarget)\n
\n

Parameters

\n
target

The target function to call.

argumentsList

An array-like object specifying the arguments with which target should be called.

\nnewTarget Optional\n

The value of new.target operator, which usually specifies the prototype of the returned object. If newTarget is not present, its value defaults to target.

Return value

\n

A new instance of target (or newTarget, if present), initialized by target as a constructor with the given argumentsList.

Exceptions

\n
TypeError

Thrown if target or newTarget is not a constructor, or if argumentsList is not an object.

Description

\n
\n

Reflect.apply() provides the reflective semantic of a constructor call. That is, Reflect.construct(target, argumentsList, newTarget) is semantically equivalent to:

\n

js

\n
new target(...argumentsList);\n
\n

Note that when using the new operator, target and newTarget are always the same constructor — but Reflect.construct() allows you to pass a different new.target value. Conceptually, newTarget is the function on which new was called, and newTarget.prototype will become the constructed object's prototype, while target is the constructor that is actually executed to initialize the object. For example, new.target may also be different from the currently executed constructor in class inheritance.

\n

js

\n
class A {\n  constructor() {\n    console.log(new.target.name);\n  }\n}\nclass B extends A {}\n\nnew B(); // \"B\"\n
\n

Reflect.construct() allows you to invoke a constructor with a variable number of arguments. (This is also possible with the spread syntax in a normal constructor call.)

\n

js

\n
const obj = new Foo(...args);\nconst obj = Reflect.construct(Foo, args);\n
\n

Reflect.construct() invokes the [[Construct]] object internal method of target.

\n

Examples

\n

Using Reflect.construct()

\n
\n

js

\n
const d = Reflect.construct(Date, [1776, 6, 4]);\nd instanceof Date; // true\nd.getFullYear(); // 1776\n
\n

Reflect.construct() vs. Object.create()

\n
\n

Prior to the introduction of Reflect, objects could be constructed using an arbitrary combination of constructors and prototypes using Object.create().

\n

js

\n
function OneClass() {\n  this.name = \"one\";\n}\n\nfunction OtherClass() {\n  this.name = \"other\";\n}\n\nconst obj2 = Object.create(OtherClass.prototype);\nOneClass.apply(obj2, args);\n\nconsole.log(obj1.name); // 'one'\nconsole.log(obj2.name); // 'one'\n\nconsole.log(obj1 instanceof OneClass); // false\nconsole.log(obj2 instanceof OneClass); // false\n\nconsole.log(obj1 instanceof OtherClass); // true\nconsole.log(obj2 instanceof OtherClass); // true\n\n// Another example to demonstrate below:\n\nfunction func1(a, b, c, d) {\n  console.log(arguments[3]);\n}\n\nfunction func2(d, e, f, g) {\n  console.log(arguments[3]);\n}\n\nconst obj1 = Reflect.construct(func1, [\"I\", \"Love\", \"my\", \"country\"]);\n
\n

However, while the end result is the same, there is one important difference in the process. When using Object.create() and Function.prototype.apply(), the new.target operator will point to undefined within the function used as the constructor, since the new keyword is not being used to create the object. (In fact, it uses the apply semantic, not construct, although normal functions happen to operate nearly the same.)

When invoking Reflect.construct(), on the other hand, the new.target operator will point to the newTarget parameter if supplied, or target if not.

\n

js

\n
function OneClass() {\n  console.log(\"OneClass\");\n  console.log(new.target);\n}\nfunction OtherClass() {\n  console.log(\"OtherClass\");\n  console.log(new.target);\n}\n\nconst obj1 = Reflect.construct(OneClass, args);\n// Logs:\n// OneClass\n// function OneClass { ... }\n\nconst obj2 = Reflect.construct(OneClass, args, OtherClass);\n// Logs:\n// OneClass\n// function OtherClass { ... }\n\nconst obj3 = Object.create(OtherClass.prototype);\nOneClass.apply(obj3, args);\n// Output:\n//     OneClass\n//     undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.construct
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
construct491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct\n

\n
\n", + "global_objects/evalerror/evalerror": "

EvalError() constructor

The EvalError() constructor creates EvalError objects.

\n

Syntax

\n
\n
\n

js

\n
new EvalError()\nnew EvalError(message)\nnew EvalError(message, options)\nnew EvalError(message, fileName)\nnew EvalError(message, fileName, lineNumber)\n\nEvalError()\nEvalError(message)\nEvalError(message, options)\nEvalError(message, fileName)\nEvalError(message, fileName, lineNumber)\n
\n

Note: EvalError() can be called with or without new. Both create a new EvalError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

EvalError is not used in the current ECMAScript specification and will thus not be thrown by the runtime. However, the object itself remains for backwards compatibility with earlier versions of the specification.

Creating an EvalError

\n
\n

js

\n
try {\n  throw new EvalError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof EvalError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"EvalError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
EvalError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError/EvalError\n

\n
\n", + "global_objects/string/normalize": "

String.prototype.normalize()

The normalize() method of String values returns the Unicode Normalization Form of this string.

\n

Try it

\n

Syntax

\n
\n

js

\n
normalize()\nnormalize(form)\n
\n

Parameters

\n
\nform Optional\n

One of \"NFC\", \"NFD\", \"NFKC\", or \"NFKD\", specifying the Unicode Normalization Form. If omitted or undefined, \"NFC\" is used.

These values have the following meanings:

\"NFC\"

Canonical Decomposition, followed by Canonical Composition.

\"NFD\"

Canonical Decomposition.

\"NFKC\"

Compatibility Decomposition, followed by Canonical Composition.

\"NFKD\"

Compatibility Decomposition.

Return value

\n

A string containing the Unicode Normalization Form of the given string.

Exceptions

\n
RangeError

Thrown if form isn't one of the values specified above.

Description

\n
\n

Unicode assigns a unique numerical value, called a code point, to each character. For example, the code point for \"A\" is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character \"ñ\" for example can be represented by either of:

\n

js

\n
const string1 = \"\\u00F1\";\nconst string2 = \"\\u006E\\u0303\";\n\nconsole.log(string1); // ñ\nconsole.log(string2); // ñ\n
\n

However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.

\n

js

\n
const string1 = \"\\u00F1\"; // ñ\nconst string2 = \"\\u006E\\u0303\"; // ñ\n\nconsole.log(string1 === string2); // false\nconsole.log(string1.length); // 1\nconsole.log(string2.length); // 2\n
\n

The normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on canonical equivalence and the other based on compatibility.

\n

Canonical equivalence normalization

\n
\n

In Unicode, two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior (for example, they should always be sorted in the same way).

You can use normalize() using the \"NFD\" or \"NFC\" arguments to produce a form of the string that will be the same for all canonically equivalent strings. In the example below we normalize two representations of the character \"ñ\":

\n

js

\n
let string1 = \"\\u00F1\"; // ñ\nlet string2 = \"\\u006E\\u0303\"; // ñ\n\nstring1 = string1.normalize(\"NFD\");\nstring2 = string2.normalize(\"NFD\");\n\nconsole.log(string1 === string2); // true\nconsole.log(string1.length); // 2\nconsole.log(string2.length); // 2\n
\n

Composed and decomposed forms

Note that the length of the normalized form under \"NFD\" is 2. That's because \"NFD\" gives you the decomposed version of the canonical form, in which single code points are split into multiple combining ones. The decomposed canonical form for \"ñ\" is \"\\u006E\\u0303\".

You can specify \"NFC\" to get the composed canonical form, in which multiple code points are replaced with single code points where possible. The composed canonical form for \"ñ\" is \"\\u00F1\":

\n

js

\n
let string1 = \"\\u00F1\"; // ñ\nlet string2 = \"\\u006E\\u0303\"; // ñ\n\nstring1 = string1.normalize(\"NFC\");\nstring2 = string2.normalize(\"NFC\");\n\nconsole.log(string1 === string2); // true\nconsole.log(string1.length); // 1\nconsole.log(string2.length); // 1\nconsole.log(string2.codePointAt(0).toString(16)); // f1\n
\n
\n

Compatibility normalization

\n
\n

In Unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some — but not necessarily all — applications.

All canonically equivalent sequences are also compatible, but not vice versa.

For example:

In some respects (such as sorting) they should be treated as equivalent—and in some (such as visual appearance) they should not, so they are not canonically equivalent.

You can use normalize() using the \"NFKD\" or \"NFKC\" arguments to produce a form of the string that will be the same for all compatible strings:

\n

js

\n
let string1 = \"\\uFB00\";\nlet string2 = \"\\u0066\\u0066\";\n\nconsole.log(string1); // ff\nconsole.log(string2); // ff\nconsole.log(string1 === string2); // false\nconsole.log(string1.length); // 1\nconsole.log(string2.length); // 2\n\nstring1 = string1.normalize(\"NFKD\");\nstring2 = string2.normalize(\"NFKD\");\n\nconsole.log(string1); // ff <- visual appearance changed\nconsole.log(string2); // ff\nconsole.log(string1 === string2); // true\nconsole.log(string1.length); // 2\nconsole.log(string2.length); // 2\n
\n

When applying compatibility normalization it's important to consider what you intend to do with the strings, since the normalized form may not be appropriate for all applications. In the example above the normalization is appropriate for search, because it enables a user to find the string by searching for \"f\". But it may not be appropriate for display, because the visual representation is different.

As with canonical normalization, you can ask for decomposed or composed compatible forms by passing \"NFKD\" or \"NFKC\", respectively.

\n

Examples

\n

Using normalize()

\n
\n

js

\n
// Initial string\n\n// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE\n// U+0323: COMBINING DOT BELOW\nconst str = \"\\u1E9B\\u0323\";\n\n// Canonically-composed form (NFC)\n\n// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE\n// U+0323: COMBINING DOT BELOW\nstr.normalize(\"NFC\"); // '\\u1E9B\\u0323'\nstr.normalize(); // same as above\n\n// Canonically-decomposed form (NFD)\n\n// U+017F: LATIN SMALL LETTER LONG S\n// U+0323: COMBINING DOT BELOW\n// U+0307: COMBINING DOT ABOVE\nstr.normalize(\"NFD\"); // '\\u017F\\u0323\\u0307'\n\n// Compatibly-composed (NFKC)\n\n// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE\nstr.normalize(\"NFKC\"); // '\\u1E69'\n\n// Compatibly-decomposed (NFKD)\n\n// U+0073: LATIN SMALL LETTER S\n// U+0323: COMBINING DOT BELOW\n// U+0307: COMBINING DOT ABOVE\nstr.normalize(\"NFKD\"); // '\\u0073\\u0323\\u0307'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.normalize
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
normalize341231No211037343121102.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize\n

\n
\n", + "global_objects/number/toexponential": "

Number.prototype.toExponential()

The toExponential() method of Number values returns a string representing this number in exponential notation.

\n

Try it

\n

Syntax

\n
\n

js

\n
toExponential()\ntoExponential(fractionDigits)\n
\n

Parameters

\n
\nfractionDigits Optional\n

Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number.

Return value

\n

A string representing the given Number object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point.

Exceptions

\n
RangeError

Thrown if fractionDigits is not between 0 and 100 (inclusive).

TypeError

Thrown if this method is invoked on an object that is not a Number.

Description

\n
\n

If the fractionDigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely.

If you use the toExponential() method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point.

If a number has more digits than requested by the fractionDigits parameter, the number is rounded to the nearest number represented by fractionDigits digits. See the discussion of rounding in the description of the toFixed() method, which also applies to toExponential().

\n

Examples

\n

Using toExponential

\n
\n

js

\n
const numObj = 77.1234;\n\nconsole.log(numObj.toExponential()); // 7.71234e+1\nconsole.log(numObj.toExponential(4)); // 7.7123e+1\nconsole.log(numObj.toExponential(2)); // 7.71e+1\nconsole.log((77.1234).toExponential()); // 7.71234e+1\nconsole.log((77).toExponential()); // 7.7e+1\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.toexponential
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toExponential11215.5724.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential\n

\n
\n", + "global_objects/number/toprecision": "

Number.prototype.toPrecision()

The toPrecision() method of Number values returns a string representing this number to the specified precision.

\n

Try it

\n

Syntax

\n
\n

js

\n
toPrecision()\ntoPrecision(precision)\n
\n

Parameters

\n
\nprecision Optional\n

An integer specifying the number of significant digits.

Return value

\n
\n

A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the Number.prototype.toFixed() method, which also applies to toPrecision().

If the precision argument is omitted, behaves as Number.prototype.toString(). If the precision argument is a non-integer value, it is rounded to the nearest integer.

\n

Exceptions

\n
RangeError

Thrown if precision is not between 1 and 100 (inclusive).

Examples

\n

Using toPrecision\n

\n
\n

js

\n
let num = 5.123456;\n\nconsole.log(num.toPrecision()); // '5.123456'\nconsole.log(num.toPrecision(5)); // '5.1235'\nconsole.log(num.toPrecision(2)); // '5.1'\nconsole.log(num.toPrecision(1)); // '5'\n\nnum = 0.000123;\n\nconsole.log(num.toPrecision()); // '0.000123'\nconsole.log(num.toPrecision(5)); // '0.00012300'\nconsole.log(num.toPrecision(2)); // '0.00012'\nconsole.log(num.toPrecision(1)); // '0.0001'\n\n// note that exponential notation might be returned in some circumstances\nconsole.log((1234.5).toPrecision(2)); // '1.2e+3'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.toprecision
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toPrecision11215.5724.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision\n

\n
\n", + "global_objects/rangeerror/rangeerror": "

RangeError() constructor

The RangeError() constructor creates RangeError objects.

\n

Syntax

\n
\n
\n

js

\n
new RangeError()\nnew RangeError(message)\nnew RangeError(message, options)\nnew RangeError(message, fileName)\nnew RangeError(message, fileName, lineNumber)\n\nRangeError()\nRangeError(message)\nRangeError(message, options)\nRangeError(message, fileName)\nRangeError(message, fileName, lineNumber)\n
\n

Note: RangeError() can be called with or without new. Both create a new RangeError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

Using RangeError (for numeric values)

\n
\n

js

\n
function check(n) {\n  if (!(n >= -500 && n <= 500)) {\n    throw new RangeError(\"The argument must be between -500 and 500.\");\n  }\n}\n\ntry {\n  check(2000);\n} catch (error) {\n  if (error instanceof RangeError) {\n    // Handle the error\n  }\n}\n
\n

Using RangeError (for non-numeric values)

\n
\n

js

\n
function check(value) {\n  if (![\"apple\", \"banana\", \"carrot\"].includes(value)) {\n    throw new RangeError(\n      'The argument must be an \"apple\", \"banana\", or \"carrot\".',\n    );\n  }\n}\n\ntry {\n  check(\"cabbage\");\n} catch (error) {\n  if (error instanceof RangeError) {\n    // Handle the error\n  }\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
RangeError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/RangeError\n

\n
\n", + "global_objects/referenceerror/referenceerror": "

ReferenceError() constructor

The ReferenceError() constructor creates ReferenceError objects.

\n

Syntax

\n
\n
\n

js

\n
new ReferenceError()\nnew ReferenceError(message)\nnew ReferenceError(message, options)\nnew ReferenceError(message, fileName)\nnew ReferenceError(message, fileName, lineNumber)\n\nReferenceError()\nReferenceError(message)\nReferenceError(message, options)\nReferenceError(message, fileName)\nReferenceError(message, fileName, lineNumber)\n
\n

Note: ReferenceError() can be called with or without new. Both create a new ReferenceError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception.

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

Catching a ReferenceError

\n
\n

js

\n
try {\n  let a = undefinedVariable;\n} catch (e) {\n  console.log(e instanceof ReferenceError); // true\n  console.log(e.message); // \"undefinedVariable is not defined\"\n  console.log(e.name); // \"ReferenceError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a ReferenceError

\n
\n

js

\n
try {\n  throw new ReferenceError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof ReferenceError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"ReferenceError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ReferenceError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/ReferenceError\n

\n
\n", + "global_objects/syntaxerror/syntaxerror": "

SyntaxError() constructor

The SyntaxError() constructor creates SyntaxError objects.

\n

Syntax

\n
\n
\n

js

\n
new SyntaxError()\nnew SyntaxError(message)\nnew SyntaxError(message, options)\nnew SyntaxError(message, fileName)\nnew SyntaxError(message, fileName, lineNumber)\n\nSyntaxError()\nSyntaxError(message)\nSyntaxError(message, options)\nSyntaxError(message, fileName)\nSyntaxError(message, fileName, lineNumber)\n
\n

Note: SyntaxError() can be called with or without new. Both create a new SyntaxError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

Catching a SyntaxError

\n
\n

js

\n
try {\n  eval(\"hoo bar\");\n} catch (e) {\n  console.log(e instanceof SyntaxError); // true\n  console.log(e.message);\n  console.log(e.name); // \"SyntaxError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a SyntaxError

\n
\n

js

\n
try {\n  throw new SyntaxError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof SyntaxError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"SyntaxError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
SyntaxError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/SyntaxError\n

\n
\n", + "global_objects/typeerror/typeerror": "

TypeError() constructor

The TypeError() constructor creates TypeError objects.

\n

Syntax

\n
\n
\n

js

\n
new TypeError()\nnew TypeError(message)\nnew TypeError(message, options)\nnew TypeError(message, fileName)\nnew TypeError(message, fileName, lineNumber)\n\nTypeError()\nTypeError(message)\nTypeError(message, options)\nTypeError(message, fileName)\nTypeError(message, fileName, lineNumber)\n
\n

Note: TypeError() can be called with or without new. Both create a new TypeError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

Catching a TypeError

\n
\n

js

\n
try {\n  null.f();\n} catch (e) {\n  console.log(e instanceof TypeError); // true\n  console.log(e.message); // \"null has no properties\"\n  console.log(e.name); // \"TypeError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating a TypeError

\n
\n

js

\n
try {\n  throw new TypeError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof TypeError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"TypeError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
TypeError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError/TypeError\n

\n
\n", + "global_objects/urierror/urierror": "

URIError() constructor

The URIError() constructor creates URIError objects.

\n

Syntax

\n
\n
\n

js

\n
new URIError()\nnew URIError(message)\nnew URIError(message, options)\nnew URIError(message, fileName)\nnew URIError(message, fileName, lineNumber)\n\nURIError()\nURIError(message)\nURIError(message, options)\nURIError(message, fileName)\nURIError(message, fileName, lineNumber)\n
\n

Note: URIError() can be called with or without new. Both create a new URIError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception.

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception.

Examples

\n

Catching an URIError

\n
\n

js

\n
try {\n  decodeURIComponent(\"%\");\n} catch (e) {\n  console.log(e instanceof URIError); // true\n  console.log(e.message); // \"malformed URI sequence\"\n  console.log(e.name); // \"URIError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Creating an URIError

\n
\n

js

\n
try {\n  throw new URIError(\"Hello\");\n} catch (e) {\n  console.log(e instanceof URIError); // true\n  console.log(e.message); // \"Hello\"\n  console.log(e.name); // \"URIError\"\n  console.log(e.stack); // Stack of the error\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-nativeerror-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
URIError11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError/URIError\n

\n
\n", + "global_objects/internalerror/internalerror": "

InternalError() constructor

\n

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The InternalError() constructor creates InternalError objects.

\n
\n

Syntax

\n
\n
\n

js

\n
new InternalError()\nnew InternalError(message)\nnew InternalError(message, options)\nnew InternalError(message, fileName)\nnew InternalError(message, fileName, lineNumber)\n\nInternalError()\nInternalError(message)\nInternalError(message, options)\nInternalError(message, fileName)\nInternalError(message, fileName, lineNumber)\n
\n

Note: InternalError() can be called with or without new. Both create a new InternalError instance.

\n

Parameters

\n
\nmessage Optional\n

Human-readable description of the error.

\noptions Optional\n

An object that has the following properties:

\ncause Optional\n

A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

\nfileName Optional Non-standard \n

The name of the file containing the code that caused the exception

\nlineNumber Optional Non-standard \n

The line number of the code that caused the exception

Examples

\n

Creating a new InternalError

\n
\n

js

\n
new InternalError(\"Engine failure\");\n
\n

Specifications

\n

Not part of any standard.

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
InternalErrorNoNo1NoNoNoNoNo4NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError/InternalError\n

\n
\n", + "errors/too_much_recursion": "

InternalError: too much recursion

The JavaScript exception \"too much recursion\" or \"Maximum call stack size exceeded\" occurs when there are too many function calls, or a function is missing a base case.

\n

Message

\n
RangeError: Maximum call stack size exceeded (Chrome)\nInternalError: too much recursion (Firefox)\nRangeError: Maximum call stack size exceeded. (Safari)\n

Error type

\n

InternalError in Firefox; RangeError in Chrome and Safari.

What went wrong?

\n
\n

A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case.

In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.

\n

Examples

\n
\n

This recursive function runs 10 times, as per the exit condition.

\n

js

\n
function loop(x) {\n  if (x >= 10)\n    // \"x >= 10\" is the exit condition\n    return;\n  // do stuff\n  loop(x + 1); // the recursive call\n}\nloop(0);\n
\n

Setting this condition to an extremely high value, won't work:

\n

js

\n
function loop(x) {\n  if (x >= 1000000000000) return;\n  // do stuff\n  loop(x + 1);\n}\nloop(0);\n\n// InternalError: too much recursion\n
\n

This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.

\n

js

\n
function loop(x) {\n  // The base case is missing\n  loop(x + 1); // Recursive call\n}\n\nloop(0);\n\n// InternalError: too much recursion\n
\n
\n

Class error: too much recursion

\n
\n
\n

js

\n
class Person {\n  constructor() {}\n  set name(name) {\n    this.name = name; // Recursive call\n  }\n}\n\nconst tony = new Person();\ntony.name = \"Tonisha\"; // InternalError: too much recursion\n
\n

When a value is assigned to the property name (this.name = name;) JavaScript needs to set that property. When this happens, the setter function is triggered.

In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive.

This issue also appears if the same variable is used in the getter.

\n

js

\n
class Person {\n  get name() {\n    return this.name; // Recursive call\n  }\n}\n
\n

To avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter. The same goes for the getter.

\n

js

\n
class Person {\n  constructor() {}\n  set name(name) {\n    this._name = name;\n  }\n  get name() {\n    return this._name;\n  }\n}\nconst tony = new Person();\ntony.name = \"Tonisha\";\nconsole.log(tony);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion\n

\n
\n", + "global_objects/number/epsilon": "

Number.EPSILON

The Number.EPSILON static data property represents the difference between 1 and the smallest floating point number greater than 1.

\n

Try it

\n

Value

\n
\n

2-52, or approximately 2.2204460492503130808472633361816E-16.

\n
Property attributes of Number.EPSILON\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Number.EPSILON is the difference between 1 and the next greater number representable in the Number format, because double precision floating point format only has 52 bits to represent the mantissa, and the lowest bit has a significance of 2-52.

Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. Number.MIN_VALUE is the smallest representable positive number, which is much smaller than Number.EPSILON.

Because EPSILON is a static property of Number, you always use it as Number.EPSILON, rather than as a property of a number value.

\n

Examples

\n

Testing equality

\n
\n

Any number encoding system occupying a finite number of bits, of whatever base you choose (e.g. decimal or binary), will necessarily be unable to represent all numbers exactly, because you are trying to represent an infinite number of points on the number line using a finite amount of memory. For example, a base-10 (decimal) system cannot represent 1/3 exactly, and a base-2 (binary) system cannot represent 0.1 exactly. Thus, for example, 0.1 + 0.2 is not exactly equal to 0.3:

\n

js

\n
console.log(0.1 + 0.2); // 0.30000000000000004\nconsole.log(0.1 + 0.2 === 0.3); // false\n
\n

For this reason, it is often advised that ===. Instead, we can deem two numbers as equal if they are close enough to each other. The Number.EPSILON constant is usually a reasonable threshold for errors if the arithmetic is around the magnitude of 1, because EPSILON, in essence, specifies how accurate the number \"1\" is.

\n

js

\n
function equal(x, y) {\n  return Math.abs(x - y) < Number.EPSILON;\n}\n\nconst x = 0.2;\nconst y = 0.3;\nconst z = 0.1;\nconsole.log(equal(x + z, y)); // true\n
\n

However, Number.EPSILON is inappropriate for any arithmetic operating on a larger magnitude. If your data is on the 103 order of magnitude, the decimal part will have a much smaller accuracy than Number.EPSILON:

\n

js

\n
function equal(x, y) {\n  return Math.abs(x - y) < Number.EPSILON;\n}\n\nconst x = 1000.1;\nconst y = 1000.2;\nconst z = 2000.3;\nconsole.log(x + y); // 2000.3000000000002; error of 10^-13 instead of 10^-16\nconsole.log(equal(x + y, z)); // false\n
\n

In this case, a larger tolerance is required. As the numbers compared have a magnitude of approximately 2000, a multiplier such as 2000 * Number.EPSILON creates enough tolerance for this instance.

\n

js

\n
function equal(x, y, tolerance = Number.EPSILON) {\n  return Math.abs(x - y) < tolerance;\n}\n\nconst x = 1000.1;\nconst y = 1000.2;\nconst z = 2000.3;\nconsole.log(equal(x + y, z, 2000 * Number.EPSILON)); // true\n
\n

In addition to magnitude, it is important to consider the accuracy of your input. For example, if the numbers are collected from a form input and the input value can only be adjusted by steps of 0.1 (i.e. <input type=\"number\" step=\"0.1\">), it usually makes sense to allow a much larger tolerance, such as 0.01, since the data only has a precision of 0.1.

Note: Important takeaway: do not simply use Number.EPSILON as a threshold for equality testing. Use a threshold that is appropriate for the magnitude and accuracy of the numbers you are comparing.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.epsilon
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
EPSILON341225No2193734252192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON\n

\n
\n", + "global_objects/number/min_safe_integer": "

Number.MIN_SAFE_INTEGER

\n

The Number.MIN_SAFE_INTEGER static data property represents the minimum safe integer in JavaScript, or -(253 - 1).

To represent integers smaller than this, consider using BigInt.

\n
\n

Try it

\n

Value

\n
\n

-9007199254740991 (-9,007,199,254,740,991, or about -9 quadrillion).

\n
Property attributes of Number.MIN_SAFE_INTEGER\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

Because MIN_SAFE_INTEGER is a static property of Number, you always use it as Number.MIN_SAFE_INTEGER, rather than as a property of a number value.

\n

Examples

\n

Using MIN_SAFE_INTEGER

\n
\n

js

\n
Number.MIN_SAFE_INTEGER; // -9007199254740991\n-(2 ** 53 - 1); // -9007199254740991\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.min_safe_integer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
MIN_SAFE_INTEGER341231No2193734312192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER\n

\n
\n", + "global_objects/number/max_safe_integer": "

Number.MAX_SAFE_INTEGER

\n

The Number.MAX_SAFE_INTEGER static data property represents the maximum safe integer in JavaScript (253 – 1).

For larger integers, consider using BigInt.

\n
\n

Try it

\n

Value

\n
\n

9007199254740991 (9,007,199,254,740,991, or ~9 quadrillion).

\n
Property attributes of Number.MAX_SAFE_INTEGER\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1. \"Safe\" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

Because MAX_SAFE_INTEGER is a static property of Number, you always use it as Number.MAX_SAFE_INTEGER, rather than as a property of a number value.

\n

Examples

\n

Return value of MAX_SAFE_INTEGER

\n
\n

js

\n
Number.MAX_SAFE_INTEGER; // 9007199254740991\n
\n

Relationship between MAX_SAFE_INTEGER and EPSILON

\n
\n

Number.EPSILON is 2-52, while MAX_SAFE_INTEGER is 253 – 1 — both of them are derived from the width of the mantissa, which is 53 bits (with the highest bit always being 1). Multiplying them will give a value very close — but not equal — to 2.

\n

js

\n
Number.MAX_SAFE_INTEGER * Number.EPSILON; // 1.9999999999999998\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.max_safe_integer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
MAX_SAFE_INTEGER341231No2193734312192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER\n

\n
\n", + "global_objects/typedarray": "

TypedArray

A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray, nor is there a directly visible TypedArray constructor. Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.

\n

Try it

\n

Description

\n
\n

The TypedArray constructor (often referred to as %TypedArray% to indicate its \"intrinsicness\", since it does not correspond to any global exposed to a JavaScript program) serves as the common superclass of all TypedArray subclasses. Think about %TypedArray% as an \"abstract class\" providing a common interface of utility methods for all typed array subclasses. This constructor is not directly exposed: there is no global TypedArray property. It is only accessible through Object.getPrototypeOf(Int8Array) and similar.

When creating an instance of a TypedArray subclass (e.g. Int8Array), an array buffer is created internally in memory or, if an ArrayBuffer object is given as constructor argument, that ArrayBuffer is used instead. The buffer address is saved as an internal property of the instance and all the methods of %TypedArray%.prototype will set and get values based on that array buffer address.

\n

TypedArray objects

\n
Type Value Range Size in bytes Web IDL type
Int8Array -128 to 127 1 byte
Uint8Array 0 to 255 1 octet
Uint8ClampedArray 0 to 255 1 octet
Int16Array -32768 to 32767 2 short
Uint16Array 0 to 65535 2 unsigned short
Int32Array -2147483648 to 2147483647 4 long
Uint32Array 0 to 4294967295 4 unsigned long
Float32Array \n-3.4e38 to 3.4e38\n 4 unrestricted float
Float64Array \n-1.8e308 to 1.8e308\n 8 unrestricted double
BigInt64Array -263 to 263 - 1 8 bigint
BigUint64Array 0 to 264 - 1 8 bigint

Value encoding and normalization

\n
\n

All typed arrays operate on ArrayBuffers, where you can observe the exact byte representation of each element, so how the numbers are encoded in binary format is significant.

All typed arrays except Int8Array, Uint8Array, and Uint8ClampedArray store each element using multiple bytes. These bytes can either be ordered from most significant to least significant (big-endian) or from least significant to most significant (little-endian). See Endianness for more explanation. Typed arrays always use the platform's native byte order. If you want to specify the endianness when writing and reading from buffers, you should use a DataView instead.

When writing to these typed arrays, values that are outside the representable range are normalized.

\n

Behavior when viewing a resizable buffer

\n
\n

When a TypedArray is created as a view of a resizable buffer, resizing the underlying buffer will have different effects on the size of the TypedArray depending on whether the TypedArray is constructed as length-tracking.

If a typed array is created without a specific size by omitting the third parameter or passing undefined, the typed array will become length-tracking, and will automatically resize to fit the underlying buffer as the latter is resized:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst float32 = new Float32Array(buffer);\n\nconsole.log(float32.byteLength); // 8\nconsole.log(float32.length); // 2\n\nbuffer.resize(12);\n\nconsole.log(float32.byteLength); // 12\nconsole.log(float32.length); // 3\n
\n

If a typed array is created with a specific size using the third length parameter, it won't resize to contain the buffer as the latter is grown:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst float32 = new Float32Array(buffer, 0, 2);\n\nconsole.log(float32.byteLength); // 8\nconsole.log(float32.length); // 2\nconsole.log(float32[0]); // 0, the initial value\n\nbuffer.resize(12);\n\nconsole.log(float32.byteLength); // 8\nconsole.log(float32.length); // 2\nconsole.log(float32[0]); // 0, the initial value\n
\n

When a buffer is shrunk, the viewing typed array may become out of bounds, in which case the typed array's observed size will decrease to 0. This is the only case where a non-length-tracking typed array's length may change.

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst float32 = new Float32Array(buffer, 0, 2);\n\nbuffer.resize(7);\n\nconsole.log(float32.byteLength); // 0\nconsole.log(float32.length); // 0\nconsole.log(float32[0]); // undefined\n
\n

If you then grow the buffer again to bring the typed array back in bounds, the typed array's size will be restored to its original value.

\n

js

\n
buffer.resize(8);\n\nconsole.log(float32.byteLength); // 8\nconsole.log(float32.length); // 2\nconsole.log(float32[0]); // 0 - back in bounds again!\n
\n

The same can happen for length-tracking typed arrays as well, if the buffer is shrunk beyond the byteOffset.

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst float32 = new Float32Array(buffer, 4);\n// float32 is length-tracking, but it only extends from the 4th byte\n// to the end of the buffer, so if the buffer is resized to be shorter\n// than 4 bytes, the typed array will become out of bounds\nbuffer.resize(3);\nconsole.log(float32.byteLength); // 0\n
\n
\n

Constructor

\n
\n

This object cannot be instantiated directly — attempting to construct it with new throws a TypeError.

\n

js

\n
new (Object.getPrototypeOf(Int8Array))();\n// TypeError: Abstract class TypedArray not directly constructable\n
\n

Instead, you create an instance of a typed array of a particular type, such as an Int8Array or a BigInt64Array. These objects all have a common syntax for their constructors:

\n

js

\n
new TypedArray()\nnew TypedArray(length)\nnew TypedArray(typedArray)\nnew TypedArray(object)\n\nnew TypedArray(buffer)\nnew TypedArray(buffer, byteOffset)\nnew TypedArray(buffer, byteOffset, length)\n
\n

Where TypedArray is a constructor for one of the concrete types.

Note: All TypedArray subclasses' constructors can only be constructed with new. Attempting to call one without new throws a TypeError.

\n

Parameters

\n
typedArray

When called with an instance of a TypedArray subclass, the typedArray gets copied into a new typed array. For a non-bigint TypedArray constructor, the typedArray parameter can only be of one of the non-bigint types (such as Int32Array). Similarly, for a bigint TypedArray constructor (BigInt64Array or BigUint64Array), the typedArray parameter can only be of one of the bigint types. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument.

object

When called with an object that's not a TypedArray instance, a new typed array is created in the same way as the TypedArray.from() method.

\nlength Optional\n

When called with a non-object, the parameter will be treated as a number specifying the length of the typed array. An internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, filled with zeros. Omitting all parameters is equivalent to using 0 as length.

\nbuffer, byteOffset Optional, length Optional\n

When called with an ArrayBuffer or SharedArrayBuffer instance, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified buffer. The byteOffset (in bytes) and length (in number of elements, each occupying BYTES_PER_ELEMENT bytes) parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer starting from byteOffset is viewed. If length is omitted, the typed array becomes length-tracking.

Exceptions

\n
\n

All TypeArray subclass constructors operate in the same way. They would all throw the following exceptions:

TypeError

Thrown in one of the following cases:

  • A typedArray is passed but it is a bigint type while the current constructor is not, or vice versa.
  • A typedArray is passed but the buffer it's viewing is detached, or a detached buffer is directly passed.
RangeError

Thrown in one of the following cases:

  • The new typed array's length is too large.
  • The length of buffer (if the length parameter is not specified) or byteOffset is not an integral multiple of the new typed array's element size.
  • \nbyteOffset is not a valid array index (an integer between 0 and 253 - 1).
  • When creating a view from a buffer, the bounds are outside the buffer. In other words, byteOffset + length * TypedArray.BYTES_PER_ELEMENT > buffer.byteLength.
\n

Static properties

\n
\n

These properties are defined on the TypedArray constructor object and are thus shared by all TypedArray subclass constructors.

TypedArray[@@species]

The constructor function used to create derived objects.

All TypedArray subclasses also have the following static properties:

TypedArray.BYTES_PER_ELEMENT

Returns a number value of the element size for the different TypedArray objects.

\n

Static methods

\n
\n

These methods are defined on the TypedArray constructor object and are thus shared by all TypedArray subclass constructors.

TypedArray.from()

Creates a new TypedArray from an array-like or iterable object. See also Array.from().

TypedArray.of()

Creates a new TypedArray with a variable number of arguments. See also Array.of().

\n

Instance properties

\n
\n

These properties are defined on TypedArray.prototype and shared by all TypedArray subclass instances.

TypedArray.prototype.buffer

Returns the ArrayBuffer referenced by the typed array.

TypedArray.prototype.byteLength

Returns the length (in bytes) of the typed array.

TypedArray.prototype.byteOffset

Returns the offset (in bytes) of the typed array from the start of its ArrayBuffer.

TypedArray.prototype.constructor

The constructor function that created the instance object. TypedArray.prototype.constructor is the hidden TypedArray constructor function, but each typed array subclass also defines its own constructor property.

TypedArray.prototype.length

Returns the number of elements held in the typed array.

TypedArray.prototype[@@toStringTag]

The initial value of the TypedArray.prototype[@@toStringTag] property is a getter that returns the same string as the typed array constructor's name. It returns undefined if the this value is not one of the typed array subclasses. This property is used in Object.prototype.toString(). However, because TypedArray also has its own toString() method, this property is not used unless you call Object.prototype.toString.call() with a typed array as thisArg.

All TypedArray subclasses also have the following instance properties:

TypedArray.prototype.BYTES_PER_ELEMENT

Returns a number value of the element size for the different TypedArray objects.

\n

Instance methods

\n
\n

These methods are defined on the TypedArray prototype object and are thus shared by all TypedArray subclass instances.

TypedArray.prototype.at()

Takes an integer value and returns the item at that index. This method allows for negative integers, which count back from the last item.

TypedArray.prototype.copyWithin()

Copies a sequence of array elements within the array. See also Array.prototype.copyWithin().

TypedArray.prototype.entries()

Returns a new array iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries().

TypedArray.prototype.every()

Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.every().

TypedArray.prototype.fill()

Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill().

TypedArray.prototype.filter()

Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter().

TypedArray.prototype.find()

Returns the first element in the array that satisfies a provided testing function, or undefined if no appropriate element is found. See also Array.prototype.find().

TypedArray.prototype.findIndex()

Returns the first index value in the array that has an element that satisfies a provided testing function, or -1 if no appropriate element was found. See also Array.prototype.findIndex().

TypedArray.prototype.findLast()

Returns the value of the last element in the array that satisfies a provided testing function, or undefined if no appropriate element is found. See also Array.prototype.findLast().

TypedArray.prototype.findLastIndex()

Returns the index of the last element in the array that satisfies a provided testing function, or -1 if no appropriate element was found. See also Array.prototype.findLastIndex().

TypedArray.prototype.forEach()

Calls a function for each element in the array. See also Array.prototype.forEach().

TypedArray.prototype.includes()

Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes().

TypedArray.prototype.indexOf()

Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf().

TypedArray.prototype.join()

Joins all elements of an array into a string. See also Array.prototype.join().

TypedArray.prototype.keys()

Returns a new array iterator that contains the keys for each index in the array. See also Array.prototype.keys().

TypedArray.prototype.lastIndexOf()

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.lastIndexOf().

TypedArray.prototype.map()

Creates a new array with the results of calling a provided function on every element in this array. See also Array.prototype.map().

TypedArray.prototype.reduce()

Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also Array.prototype.reduce().

TypedArray.prototype.reduceRight()

Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also Array.prototype.reduceRight().

TypedArray.prototype.reverse()

Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also Array.prototype.reverse().

TypedArray.prototype.set()

Stores multiple values in the typed array, reading input values from a specified array.

TypedArray.prototype.slice()

Extracts a section of an array and returns a new array. See also Array.prototype.slice().

TypedArray.prototype.some()

Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some().

TypedArray.prototype.sort()

Sorts the elements of an array in place and returns the array. See also Array.prototype.sort().

TypedArray.prototype.subarray()

Returns a new TypedArray from the given start and end element index.

TypedArray.prototype.toLocaleString()

Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString().

TypedArray.prototype.toReversed()

Returns a new array with the elements in reversed order, without modifying the original array.

TypedArray.prototype.toSorted()

Returns a new array with the elements sorted in ascending order, without modifying the original array.

TypedArray.prototype.toString()

Returns a string representing the array and its elements. See also Array.prototype.toString().

TypedArray.prototype.values()

Returns a new array iterator object that contains the values for each index in the array. See also Array.prototype.values().

TypedArray.prototype.with()

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

TypedArray.prototype[@@iterator]()

Returns a new array iterator object that contains the values for each index in the array.

\n

Examples

\n

Property access

\n
\n

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the ArrayBuffer and will never look at object properties. You can still use named properties, just like with all objects.

\n

js

\n
// Setting and getting using standard array syntax\nconst int16 = new Int16Array(2);\nint16[0] = 42;\nconsole.log(int16[0]); // 42\n\n// Indexed properties on prototypes are not consulted (Fx 25)\nInt8Array.prototype[20] = \"foo\";\nnew Int8Array(32)[20]; // 0\n// even when out of bound\nInt8Array.prototype[20] = \"foo\";\nnew Int8Array(8)[20]; // undefined\n// or with negative integers\nInt8Array.prototype[-1] = \"foo\";\nnew Int8Array(8)[-1]; // undefined\n\n// Named properties are allowed, though (Fx 30)\nInt8Array.prototype.foo = \"bar\";\nnew Int8Array(32).foo; // \"bar\"\n
\n
\n

Cannot be frozen

\n
\n

TypedArrays that aren't empty cannot be frozen, as their underlying ArrayBuffer could be mutated through another TypedArray view of the buffer. This would mean that the object would never genuinely be frozen.

\n

js

\n
const i8 = Int8Array.of(1, 2, 3);\nObject.freeze(i8);\n// TypeError: Cannot freeze array buffer views with elements\n
\n
\n

ByteOffset must be aligned

\n
\n

When constructing a TypedArray as a view onto an ArrayBuffer, the byteOffset argument must be aligned to its element size; in other words, the offset must be a multiple of BYTES_PER_ELEMENT.

\n

js

\n
const i32 = new Int32Array(new ArrayBuffer(4), 1);\n// RangeError: start offset of Int32Array should be a multiple of 4\n
\n
\n

js

\n
const i32 = new Int32Array(new ArrayBuffer(4), 0);\n
\n
\n

ByteLength must be aligned

\n
\n

Like the byteOffset parameter, the byteLength property of an ArrayBuffer passed to a TypedArray's constructor must be a multiple of the constructor's BYTES_PER_ELEMENT.

\n

js

\n
const i32 = new Int32Array(new ArrayBuffer(3));\n// RangeError: byte length of Int32Array should be a multiple of 4\n
\n
\n

js

\n
const i32 = new Int32Array(new ArrayBuffer(4));\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
@@species511348No381051514841105.01.06.5.0
BYTES_PER_ELEMENT71241011.65.14184124.21.01.00.10.0
TypedArray71241011.65.14184124.21.01.00.10.0
at929290No7815.49292906515.416.0No16.6.0
buffer71241011.65.14184124.21.01.00.10.0
byteLength71241011.65.14184124.21.01.00.10.0
byteOffset71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
copyWithin451234No329.1454534329.35.01.04.0.0
entries451237No329.1454537329.35.01.00.12.0
every451237No329.1454537329.35.01.04.0.0
fill451237No329.1454537329.35.01.04.0.0
filter451238No329.1454538329.35.01.04.0.0
find451237No329.1454537329.35.01.04.0.0
findIndex451237No329.1454537329.35.01.04.0.0
findLast9797104No8315.497971046815.418.01.16No
findLastIndex9797104No8315.497971046815.418.01.16No
forEach451238No321045453832105.01.04.0.0
from451238No321045453832105.01.04.0.0
includes471443No341047474334105.01.06.0.0
indexOf4512
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).indexOf(0, -0) will now always return +0.
No329.14545
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).indexOf(0, -0) will now always return +0.
329.35.01.04.0.0
index_properties_not_consulting_prototype
7Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
12Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
25
10Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
11.6Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
5.1Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
≤37Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
18Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
25
12Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
5Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
1.0Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
1.0Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
0.10.0Negative integers are not considered as indexed properties and therefore return the value of the prototype property.
iterable_in_constructor391452No261039395226104.01.04.0.0
join451237No329.1454537329.35.01.04.0.0
keys381237No251038383725103.01.00.12.0
lastIndexOf4512
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).lastIndexOf(0, -0) will now always return +0.
No32104545
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).lastIndexOf(0, -0) will now always return +0.
32105.01.04.0.0
length71241011.65.14184124.21.01.00.10.0
map451238No329.1454538329.35.01.04.0.0
name71241011.65.14184124.21.01.00.10.0
named_properties712301011.65.1≤3718301251.01.00.10.0
new_required71444No155.1≤3718441451.01.00.12.0
of451238No329.1454538329.35.01.04.0.0
reduce451237No321045453732105.01.04.0.0
reduceRight451237No321045453732105.01.04.0.0
reverse451237No321045453732105.01.04.0.0
set71241011.65.14184124.21.01.00.10.0
slice451238No321045453832105.01.04.0.0
some451237No321045453732105.01.04.0.0
sort451246No321045454632105.01.04.0.0
subarray71241011.65.14184124.21.01.00.12.0
toLocaleString712511011.65.1≤3718511251.01.00.10.0
toReversed110110115No9616110110115741621.01.3120.0.0
toSorted110110115No9616110110115741621.01.3120.0.0
toString712511011.65.1≤3718511251.01.00.10.0
values381237No251038383725103.01.00.12.0
with110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\n

\n
\n", + "global_objects/number/min_value": "

Number.MIN_VALUE

The Number.MIN_VALUE static data property represents the smallest positive numeric value representable in JavaScript.

\n

Try it

\n

Value

\n
\n

2-1074, or 5E-324.

\n
Property attributes of Number.MIN_VALUE\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Number.MIN_VALUE is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, \"must be the smallest non-zero positive value that can actually be represented by the implementation\". This is because small IEEE-754 floating point numbers are denormalized, but implementations are not required to support this representation, in which case Number.MIN_VALUE may be larger.

In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or 5E-324.

Because MIN_VALUE is a static property of Number, you always use it as Number.MIN_VALUE, rather than as a property of a number value.

\n

Examples

\n

Using MIN_VALUE

\n
\n

The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE, the func1 function is called; otherwise, the func2 function is called.

\n

js

\n
if (num1 / num2 >= Number.MIN_VALUE) {\n  func1();\n} else {\n  func2();\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.min_value
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
MIN_VALUE11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE\n

\n
\n", + "global_objects/number/isinteger": "

Number.isInteger()

The Number.isInteger() static method determines whether the passed value is an integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
Number.isInteger(value)\n
\n

Parameters

\n
value

The value to be tested for being an integer.

Return value

\n

The boolean value true if the given value is an integer. Otherwise false.

Description

\n
\n

If the target value is an integer, return true, otherwise return false. If the value is NaN or Infinity, return false. The method will also return true for floating point numbers that can be represented as integer. It will always return false if the value is not a number.

Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, 5.0000000000000001 only differs from 5 by 1e-16, which is too small to be represented. (For reference, Number.EPSILON stores the distance between 1 and the next representable floating-point number greater than 1, and that is about 2.22e-16.) Therefore, 5.0000000000000001 will be represented with the same encoding as 5, thus making Number.isInteger(5.0000000000000001) return true.

In a similar sense, numbers around the magnitude of Number.MAX_SAFE_INTEGER will suffer from loss of precision and make Number.isInteger return true even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, Number.isInteger(4500000000000000.1) is true, but Number.isInteger(4500000000000000.5) is false.)

\n

Examples

\n

Using isInteger

\n
\n

js

\n
Number.isInteger(0); // true\nNumber.isInteger(1); // true\nNumber.isInteger(-100000); // true\nNumber.isInteger(99999999999999999999999); // true\n\nNumber.isInteger(0.1); // false\nNumber.isInteger(Math.PI); // false\n\nNumber.isInteger(NaN); // false\nNumber.isInteger(Infinity); // false\nNumber.isInteger(-Infinity); // false\nNumber.isInteger(\"10\"); // false\nNumber.isInteger(true); // false\nNumber.isInteger(false); // false\nNumber.isInteger([1]); // false\n\nNumber.isInteger(5.0); // true\nNumber.isInteger(5.000000000000001); // false\nNumber.isInteger(5.0000000000000001); // true, because of loss of precision\nNumber.isInteger(4500000000000000.1); // true, because of loss of precision\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.isinteger
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isInteger341216No2193734162192.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger\n

\n
\n", + "global_objects/number/tolocalestring": "

Number.prototype.toLocaleString()

\n

The toLocaleString() method of Number values returns a string with a language-sensitive representation of this number. In implementations with Intl.NumberFormat API support, this method simply calls Intl.NumberFormat.

When formatting large numbers of numbers, it is better to create a Intl.NumberFormat object and use the function provided by its format() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n
\n

Parameters

\n
\n

The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.NumberFormat API, these parameters correspond exactly to the Intl.NumberFormat() constructor's parameters. Implementations without Intl.NumberFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.NumberFormat() constructor.

In implementations without Intl.NumberFormat support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.NumberFormat() constructor.

In implementations without Intl.NumberFormat support, this parameter is ignored.

See the Intl.NumberFormat() constructor for details on these parameters and how to use them.

\n

Return value

\n
\n

A string with a language-sensitive representation of the given number.

In implementations with Intl.NumberFormat, this is equivalent to new Intl.NumberFormat(locales, options).format(number).

\n

Examples

\n

Using toLocaleString()

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const number = 3500;\n\nconsole.log(number.toLocaleString()); // \"3,500\" if in U.S. English locale\n
\n
\n

Checking for support for locales and options parameters

\n
\n

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString() always uses the system's locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

\n

js

\n
function toLocaleStringSupportsLocales() {\n  return (\n    typeof Intl === \"object\" &&\n    !!Intl &&\n    typeof Intl.NumberFormat === \"function\"\n  );\n}\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const number = 123456.789;\n\n// German uses comma as decimal separator and period for thousands\nconsole.log(number.toLocaleString(\"de-DE\"));\n// → 123.456,789\n\n// Arabic in most Arabic speaking countries uses Eastern Arabic digits\nconsole.log(number.toLocaleString(\"ar-EG\"));\n// → ١٢٣٤٥٦٫٧٨٩\n\n// India uses thousands/lakh/crore separators\nconsole.log(number.toLocaleString(\"en-IN\"));\n// → 1,23,456.789\n\n// the nu extension key requests a numbering system, e.g. Chinese decimal\nconsole.log(number.toLocaleString(\"zh-Hans-CN-u-nu-hanidec\"));\n// → 一二三,四五六.七八九\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(number.toLocaleString([\"ban\", \"id\"]));\n// → 123.456,789\n
\n
\n

Using options

\n
\n

The results provided by toLocaleString can be customized using the options parameter:

\n

js

\n
const number = 123456.789;\n\n// request a currency format\nconsole.log(\n  number.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// → 123.456,79 €\n\n// the Japanese yen doesn't use a minor unit\nconsole.log(\n  number.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }),\n);\n// → ¥123,457\n\n// limit to three significant digits\nconsole.log(number.toLocaleString(\"en-IN\", { maximumSignificantDigits: 3 }));\n// → 1,23,000\n\n// Use the host default language with options for number formatting\nconst num = 30000.65;\nconsole.log(\n  num.toLocaleString(undefined, {\n    minimumFractionDigits: 2,\n    maximumFractionDigits: 2,\n  }),\n);\n// → \"30,000.65\" where English is the default language, or\n// → \"30.000,65\" where German is the default language, or\n// → \"30 000,65\" where French is the default language\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.tolocalestring
ECMAScript Internationalization API Specification
# sup-number.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString1
12Before Edge 18, numbers are rounded to 15 decimal digits. For example, (1000000000000005).toLocaleString('en-US') returns \"1,000,000,000,000,010\".
1
5In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, (1000000000000005).toLocaleString('en-US') returns \"1,000,000,000,000,010\".
414.418410.111.01.00.10.0
locales2412291115104.4265614101.51.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options2412291115104.4265614101.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString\n

\n
\n", + "global_objects/number/valueof": "

Number.prototype.valueOf()

The valueOf() method of Number values returns the value of this number.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

A number representing the primitive value of the specified Number object.

Description

\n

This method is usually called internally by JavaScript and not explicitly in web code.

Examples

\n

Using valueOf

\n
\n

js

\n
const numObj = new Number(10);\nconsole.log(typeof numObj); // object\n\nconst num = numObj.valueOf();\nconsole.log(num); // 10\nconsole.log(typeof num); // number\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-number.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf\n

\n
\n", + "global_objects/json/parse": "

JSON.parse()

The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

\n

Try it

\n

Syntax

\n
\n

js

\n
JSON.parse(text)\nJSON.parse(text, reviver)\n
\n

Parameters

\n
text

The string to parse as JSON. See the JSON object for a description of JSON syntax.

\nreviver Optional\n

If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:

key

The key associated with the value.

value

The value produced by parsing.

Return value

\n

The Object, Array, string, number, boolean, or null value corresponding to the given JSON text.

Exceptions

\n
SyntaxError

Thrown if the string to parse is not valid JSON.

Description

\n

JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the \"__proto__\" key — see Object literal syntax vs. JSON.

The reviver parameter

\n
\n

If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver.

The reviver is called with the object containing the property being processed as this (unless you define the reviver as an arrow function, in which case there's no separate this binding) and two arguments: key and value, representing the property name as a string (even for arrays) and the property value. If the reviver function returns undefined (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.

Similar to the replacer parameter of JSON.stringify(), for arrays and objects, reviver will be last called on the root value with an empty string as the key and the root object as the value. For other valid JSON values, reviver works similarly and is called once with an empty string as the key and the value itself as the value.

If you return another value from reviver, that value will completely replace the originally parsed value. This even applies to the root value. For example:

\n

js

\n
const transformedObj1 = JSON.parse('[1,5,{\"s\":1}]', (key, value) => {\n  return typeof value === \"object\" ? undefined : value;\n});\n\nconsole.log(transformedObj1); // undefined\n
\n

There is no way to work around this generically. You cannot specially handle the case where key is an empty string, because JSON objects can also contain keys that are empty strings. You need to know very precisely what kind of transformation is needed for each key when implementing the reviver.

Note that reviver is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.

\n

Examples

\n

Using JSON.parse()

\n
\n

js

\n
JSON.parse(\"{}\"); // {}\nJSON.parse(\"true\"); // true\nJSON.parse('\"foo\"'); // \"foo\"\nJSON.parse('[1, 5, \"false\"]'); // [1, 5, \"false\"]\nJSON.parse(\"null\"); // null\n
\n

Using the reviver parameter

\n
\n

js

\n
JSON.parse(\n  '{\"p\": 5}',\n  (key, value) =>\n    typeof value === \"number\"\n      ? value * 2 // return value * 2 for numbers\n      : value, // return everything else unchanged\n);\n// { p: 10 }\n\nJSON.parse('{\"1\": 1, \"2\": 2, \"3\": {\"4\": 4, \"5\": {\"6\": 6}}}', (key, value) => {\n  console.log(key);\n  return value;\n});\n// 1\n// 2\n// 4\n// 6\n// 5\n// 3\n// \"\"\n
\n

Using reviver when paired with the replacer of JSON.stringify()

\n
\n

In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:

\n

js

\n
// Maps are normally serialized as objects with no properties.\n// We can use the replacer to specify the entries to be serialized.\nconst map = new Map([\n  [1, \"one\"],\n  [2, \"two\"],\n  [3, \"three\"],\n]);\n\nconst jsonText = JSON.stringify(map, (key, value) =>\n  value instanceof Map ? Array.from(value.entries()) : value,\n);\n\nconsole.log(jsonText);\n// [[1,\"one\"],[2,\"two\"],[3,\"three\"]]\n\nconst map2 = JSON.parse(jsonText, (key, value) =>\n  Array.isArray(value) ? new Map(value) : value,\n);\n\nconsole.log(map2);\n// Map { 1 => \"one\", 2 => \"two\", 3 => \"three\" }\n
\n

Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:

\n

JSON.parse() does not allow trailing commas

\n
\n

js

\n
// both will throw a SyntaxError\nJSON.parse(\"[1, 2, 3, 4, ]\");\nJSON.parse('{\"foo\" : 1, }');\n
\n

JSON.parse() does not allow single quotes

\n
\n

js

\n
// will throw a SyntaxError\nJSON.parse(\"{'foo': 1}\");\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-json.parse
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parse3123.5810.54≤371841141.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\n

\n
\n", + "global_objects/bigint/asintn": "

BigInt.asIntN()

The BigInt.asIntN() static method truncates a BigInt value to the given number of least significant bits and returns that value as a signed integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
BigInt.asIntN(bits, bigint)\n
\n

Parameters

\n
bits

The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive.

bigint

The BigInt value to truncate to fit into the supplied bits.

Return value

\n

The value of bigint modulo 2^bits, as a signed integer.

Exceptions

\n
RangeError

Thrown if bits is negative or greater than 253 - 1.

Description

\n
\n

The BigInt.asIntN method truncates a BigInt value to the given number of bits, and interprets the result as a signed integer. For example, for BigInt.asIntN(3, 25n), the value 25n is truncated to 1n:

25n = 00011001 (base 2)\n          ^=== Use only the three remaining bits\n===>       001 (base 2) = 1n\n

If the leading bit of the remaining number is 1, the result is negative. For example, BigInt.asIntN(4, 25n) yields -7n, because 1001 is the encoding of -7 under two's complement:

25n = 00011001 (base 2)\n         ^==== Use only the four remaining bits\n===>      1001 (base 2) = -7n\n

Note: BigInt values are always encoded as two's complement in binary.

Unlike similar language APIs such as Number.prototype.toExponential(), asIntN is a static property of BigInt, so you always use it as BigInt.asIntN(), rather than as a method of a BigInt value. Exposing asIntN() as a \"standard library function\" allows interop with asm.js.

\n

Examples

\n

Staying in 64-bit ranges

\n
\n

The BigInt.asIntN() method can be useful to stay in the range of 64-bit arithmetic.

\n

js

\n
const max = 2n ** (64n - 1n) - 1n;\n\nBigInt.asIntN(64, max); // 9223372036854775807n\n\nBigInt.asIntN(64, max + 1n); // -9223372036854775808n\n// negative because the 64th bit of 2^63 is 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint.asintn
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
asIntN677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asIntN\n

\n
\n", + "global_objects/bigint/asuintn": "

BigInt.asUintN()

The BigInt.asUintN() static method truncates a BigInt value to the given number of least significant bits and returns that value as an unsigned integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
BigInt.asUintN(bits, bigint)\n
\n

Parameters

\n
bits

The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive.

bigint

The BigInt value to truncate to fit into the supplied bits.

Return value

\n

The value of bigint modulo 2^bits, as an unsigned integer.

Exceptions

\n
RangeError

Thrown if bits is negative or greater than 253 - 1.

Description

\n
\n

The BigInt.asUintN method truncates a BigInt value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for BigInt.asUintN(4, 25n), the value 25n is truncated to 9n:

25n = 00011001 (base 2)\n         ^==== Use only the four remaining bits\n===>      1001 (base 2) = 9n\n

Note: BigInt values are always encoded as two's complement in binary.

Unlike similar language APIs such as Number.prototype.toExponential(), asUintN is a static property of BigInt, so you always use it as BigInt.asUintN(), rather than as a method of a BigInt value. Exposing asUintN() as a \"standard library function\" allows interop with asm.js.

\n

Examples

\n

Staying in 64-bit ranges

\n
\n

The BigInt.asUintN() method can be useful to stay in the range of 64-bit arithmetic.

\n

js

\n
const max = 2n ** 64n - 1n;\n\nBigInt.asUintN(64, max); // 18446744073709551615n\n\nBigInt.asUintN(64, max + 1n); // 0n\n// zero because of overflow: the lowest 64 bits are all zeros\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint.asuintn
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
asUintN677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN\n

\n
\n", + "global_objects/bigint/tostring": "

BigInt.prototype.toString()

The toString() method of BigInt values returns a string representing the specified BigInt value. The trailing \"n\" is not part of the string.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\ntoString(radix)\n
\n

Parameters

\n
\nradix Optional\n

An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10.

Return value

\n

A string representing the specified BigInt value.

Exceptions

\n
RangeError

Thrown if radix is less than 2 or greater than 36.

Description

\n
\n

The BigInt object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For BigInt values, the toString() method returns a string representation of the value in the specified radix.

For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a through f are used.

If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a - sign, not the two's complement of the BigInt value.

The toString() method requires its this value to be a BigInt primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to BigInt values.

Because BigInt doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a BigInt object is used in a context expecting a string, such as in a template literal. However, BigInt primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

\n

js

\n
BigInt.prototype.toString = () => \"Overridden\";\nconsole.log(`${1n}`); // \"1\"\nconsole.log(`${Object(1n)}`); // \"Overridden\"\n
\n
\n

Examples

\n

Using toString()

\n
\n

js

\n
17n.toString(); // \"17\"\n66n.toString(2); // \"1000010\"\n254n.toString(16); // \"fe\"\n(-10n).toString(2); // \"-1010\"\n(-0xffn).toString(2); // \"-11111111\"\n
\n

Negative-zero BigInt

\n
\n

There is no negative-zero BigInt as there are no negative zeros in integers. -0.0 is an IEEE floating-point concept that only appears in the JavaScript Number type.

\n

js

\n
(-0n).toString(); // \"0\"\nBigInt(-0).toString(); // \"0\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString\n

\n
\n", + "global_objects/bigint/tolocalestring": "

BigInt.prototype.toLocaleString()

\n

The toLocaleString() method of BigInt values returns a string with a language-sensitive representation of this BigInt. In implementations with Intl.NumberFormat API support, this method simply calls Intl.NumberFormat.

When formatting large numbers of numbers, it is better to create a Intl.NumberFormat object and use the function provided by its format() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n
\n

Parameters

\n
\n

The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.NumberFormat API, these parameters correspond exactly to the Intl.NumberFormat() constructor's parameters. Implementations without Intl.NumberFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.NumberFormat() constructor.

In implementations without Intl.NumberFormat support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.NumberFormat() constructor.

In implementations without Intl.NumberFormat support, this parameter is ignored.

See the Intl.NumberFormat() constructor for details on these parameters and how to use them.

\n

Return value

\n
\n

A string with a language-sensitive representation of the given BigInt.

In implementations with Intl.NumberFormat, this is equivalent to new Intl.NumberFormat(locales, options).format(number).

\n

Examples

\n

Using toLocaleString\n

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const bigint = 3500n;\n\nconsole.log(bigint.toLocaleString());\n// \"3,500\" if in U.S. English locale\n
\n
\n

Checking for support for locales and options parameters

\n
\n

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString() always uses the system's locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

\n

js

\n
function toLocaleStringSupportsLocales() {\n  return (\n    typeof Intl === \"object\" &&\n    !!Intl &&\n    typeof Intl.NumberFormat === \"function\"\n  );\n}\n
\n
\n

Using locales\n

\n
\n

This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const bigint = 123456789123456789n;\n\n// German uses period for thousands\nconsole.log(bigint.toLocaleString(\"de-DE\"));\n// 123.456.789.123.456.789\n\n// Arabic in most Arabic speaking countries uses Eastern Arabic digits\nconsole.log(bigint.toLocaleString(\"ar-EG\"));\n// ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩\n\n// India uses thousands/lakh/crore separators\nconsole.log(bigint.toLocaleString(\"en-IN\"));\n// 1,23,45,67,89,12,34,56,789\n\n// the nu extension key requests a numbering system, e.g. Chinese decimal\nconsole.log(bigint.toLocaleString(\"zh-Hans-CN-u-nu-hanidec\"));\n// 一二三,四五六,七八九,一二三,四五六,七八九\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(bigint.toLocaleString([\"ban\", \"id\"]));\n// 123.456.789.123.456.789\n
\n
\n

Using options\n

\n
\n

The results provided by toLocaleString can be customized using the options argument:

\n

js

\n
const bigint = 123456789123456789n;\n\n// request a currency format\nconsole.log(\n  bigint.toLocaleString(\"de-DE\", { style: \"currency\", currency: \"EUR\" }),\n);\n// 123.456.789.123.456.789,00 €\n\n// the Japanese yen doesn't use a minor unit\nconsole.log(\n  bigint.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" }),\n);\n// ¥123,456,789,123,456,789\n\n// limit to three significant digits\nconsole.log(bigint.toLocaleString(\"en-IN\", { maximumSignificantDigits: 3 }));\n// 1,23,00,00,00,00,00,00,000\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sup-bigint.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString677968No541467676848149.01.010.4.0
locales767970NoNo14767679541412.01.8
1.0–1.8Only the locale data for en-US is available.
\n
12.9.0
options767970NoNo14767679541412.0?12.9.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toLocaleString\n

\n
\n", + "global_objects/bigint/valueof": "

BigInt.prototype.valueOf()

The valueOf() method of BigInt values returns the wrapped primitive value of a BigInt object.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

A BigInt representing the primitive value of the specified BigInt object.

Examples

\n

Using valueOf\n

\n
\n

js

\n
typeof Object(1n); // object\ntypeof Object(1n).valueOf(); // bigint\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-bigint.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf677968No541467676848149.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/valueOf\n

\n
\n", + "global_objects/math/e": "

Math.E

The Math.E static data property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙴 = e 2.718 \\mathtt{\\mi{Math.E}} = e \\approx 2.718

\n
Property attributes of Math.E\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because E is a static property of Math, you always use it as Math.E, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.E

\n
\n

The following function returns e:

\n

js

\n
function getNapier() {\n  return Math.E;\n}\n\ngetNapier(); // 2.718281828459045\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.e
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
E11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E\n

\n
\n", + "global_objects/math/ln10": "

Math.LN10

The Math.LN10 static data property represents the natural logarithm of 10, approximately 2.302.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙻𝙽𝟷𝟶 = ln ( 10 ) 2.302 \\mathtt{\\mi{Math.LN10}} = \\ln(10) \\approx 2.302

\n
Property attributes of Math.LN10\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because LN10 is a static property of Math, you always use it as Math.LN10, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.LN10

\n
\n

The following function returns the natural log of 10:

\n

js

\n
function getNatLog10() {\n  return Math.LN10;\n}\n\ngetNatLog10(); // 2.302585092994046\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.ln10
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
LN1011213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN10\n

\n
\n", + "global_objects/math/ln2": "

Math.LN2

The Math.LN2 static data property represents the natural logarithm of 2, approximately 0.693:

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙻𝙽𝟸 = ln ( 2 ) 0.693 \\mathtt{\\mi{Math.LN2}} = \\ln(2) \\approx 0.693

\n
Property attributes of Math.LN2\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because LN2 is a static property of Math, you always use it as Math.LN2, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.LN2

\n
\n

The following function returns the natural log of 2:

\n

js

\n
function getNatLog2() {\n  return Math.LN2;\n}\n\ngetNatLog2(); // 0.6931471805599453\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.ln2
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
LN211213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN2\n

\n
\n", + "global_objects/math/log10e": "

Math.LOG10E

The Math.LOG10E static data property represents the base 10 logarithm of e, approximately 0.434.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟷𝟶𝙴 = log 10 ( e ) 0.434 \\mathtt{\\mi{Math.LOG10E}} = \\log_{10}(\\mathrm{e}) \\approx 0.434

\n
Property attributes of Math.LOG10E\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because LOG10E is a static property of Math, you always use it as Math.LOG10E, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.LOG10E

\n
\n

The following function returns the base 10 logarithm of e:

\n

js

\n
function getLog10e() {\n  return Math.LOG10E;\n}\n\ngetLog10e(); // 0.4342944819032518\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log10e
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
LOG10E11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG10E\n

\n
\n", + "global_objects/math/log2e": "

Math.LOG2E

The Math.LOG2E static data property represents the base 2 logarithm of e, approximately 1.442.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟸𝙴 = log 2 ( e ) 1.442 \\mathtt{\\mi{Math.LOG2E}} = \\log_2(\\mathrm{e}) \\approx 1.442

\n
Property attributes of Math.LOG2E\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because LOG2E is a static property of Math, you always use it as Math.LOG2E, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.LOG2E

\n
\n

The following function returns the base 2 logarithm of e:

\n

js

\n
function getLog2e() {\n  return Math.LOG2E;\n}\n\ngetLog2e(); // 1.4426950408889634\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log2e
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
LOG2E11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG2E\n

\n
\n", + "global_objects/math/pi": "

Math.PI

The Math.PI static data property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝙿𝙸 = π 3.14159 \\mathtt{\\mi{Math.PI}} = \\pi \\approx 3.14159

\n
Property attributes of Math.PI\n
Writable no
Enumerable no
Configurable no
\n

Description

\n

Because PI is a static property of Math, you always use it as Math.PI, rather than as a property of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.PI

\n
\n

The following function uses Math.PI to calculate the circumference of a circle with a passed radius.

\n

js

\n
function calculateCircumference(radius) {\n  return Math.PI * (radius + radius);\n}\n\ncalculateCircumference(1); // 6.283185307179586\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.pi
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
PI11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI\n

\n
\n", + "global_objects/math/sqrt1_2": "

Math.SQRT1_2

The Math.SQRT1_2 static data property represents the square root of 1/2, which is approximately 0.707.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟷_𝟸 = 1 2 0.707 \\mathtt{\\mi{Math.SQRT1_2}} = \\sqrt{\\frac{1}{2}} \\approx 0.707

\n
Property attributes of Math.SQRT1_2\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Math.SQRT1_2 is a constant and a more performant equivalent to Math.sqrt(0.5).

Because SQRT1_2 is a static property of Math, you always use it as Math.SQRT1_2, rather than as a property of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.SQRT1_2

\n
\n

The following function returns 1 over the square root of 2:

\n

js

\n
function getRoot1_2() {\n  return Math.SQRT1_2;\n}\n\ngetRoot1_2(); // 0.7071067811865476\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sqrt1_2
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
SQRT1_211213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2\n

\n
\n", + "global_objects/math/sqrt2": "

Math.SQRT2

The Math.SQRT2 static data property represents the square root of 2, approximately 1.414.

\n

Try it

\n

Value

\n
\n

𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟸 = 2 1.414 \\mathtt{\\mi{Math.SQRT2}} = \\sqrt{2} \\approx 1.414

\n
Property attributes of Math.SQRT2\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

Math.SQRT2 is a constant and a more performant equivalent to Math.sqrt(2).

Because SQRT2 is a static property of Math, you always use it as Math.SQRT2, rather than as a property of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.SQRT2

\n
\n

The following function returns the square root of 2:

\n

js

\n
function getRoot2() {\n  return Math.SQRT2;\n}\n\ngetRoot2(); // 1.4142135623730951\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sqrt2
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
SQRT211213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT2\n

\n
\n", + "global_objects/math/abs": "

Math.abs()

The Math.abs() static method returns the absolute value of a number.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.abs(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The absolute value of x. If x is negative (including -0), returns -x. Otherwise, returns x. The result is therefore always a positive number or 0.

Description

\n

Because abs() is a static method of Math, you always use it as Math.abs(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.abs()

\n
\n

js

\n
Math.abs(-Infinity); // Infinity\nMath.abs(-1); // 1\nMath.abs(-0); // 0\nMath.abs(0); // 0\nMath.abs(1); // 1\nMath.abs(Infinity); // Infinity\n
\n

Coercion of parameter

\n
\n

Math.abs() coerces its parameter to a number. Non-coercible values will become NaN, making Math.abs() also return NaN.

\n

js

\n
Math.abs(\"-1\"); // 1\nMath.abs(-2); // 2\nMath.abs(null); // 0\nMath.abs(\"\"); // 0\nMath.abs([]); // 0\nMath.abs([2]); // 2\nMath.abs([1, 2]); // NaN\nMath.abs({}); // NaN\nMath.abs(\"string\"); // NaN\nMath.abs(); // NaN\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.abs
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
abs11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs\n

\n
\n", + "global_objects/math/acos": "

Math.acos()

\n

The Math.acos() static method returns the inverse cosine (in radians) of a number. That is,

x [ 1 , 1 ] , 𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜 ( 𝚡 ) = arccos ( x ) = the unique y [ 0 , π ] such that cos ( y ) = x \\forall x \\in [{-1}, 1],;\\mathtt{\\operatorname{Math.acos}(x)} = \\arccos(x) = \\text{the unique } y \\in [0, \\pi] \\text{ such that } \\cos(y) = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.acos(x)\n
\n

Parameters

\n
x

A number between -1 and 1, inclusive, representing the angle's cosine value.

Return value

\n

The inverse cosine (angle in radians between 0 and π, inclusive) of x. If x is less than -1 or greater than 1, returns NaN.

Description

\n

Because acos() is a static method of Math, you always use it as Math.acos(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.acos()

\n
\n

js

\n
Math.acos(-2); // NaN\nMath.acos(-1); // 3.141592653589793 (π)\nMath.acos(0); // 1.5707963267948966 (π/2)\nMath.acos(0.5); // 1.0471975511965979 (π/3)\nMath.acos(1); // 0\nMath.acos(2); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.acos
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
acos11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos\n

\n
\n", + "global_objects/math/acosh": "

Math.acosh()

\n

The Math.acosh() static method returns the inverse hyperbolic cosine of a number. That is,

x 1 , 𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜𝚑 ( 𝚡 ) = arcosh ( x ) = the unique y 0 such that cosh ( y ) = x = ln ( x + x 2 1 ) \\begin{aligned}\\forall x \\geq 1,;\\mathtt{\\operatorname{Math.acosh}(x)} &= \\operatorname{arcosh}(x) = \\text{the unique } y \\geq 0 \\text{ such that } \\cosh(y) = x\\&= \\ln\\left(x + \\sqrt{x^2 - 1}\\right)\\end{aligned}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.acosh(x)\n
\n

Parameters

\n
x

A number greater than or equal to 1.

Return value

\n

The inverse hyperbolic cosine of x. If x is less than 1, returns NaN.

Description

\n

Because acosh() is a static method of Math, you always use it as Math.acosh(), rather than as a method of a Math object you created (Math is no constructor).

Examples

\n

Using Math.acosh()

\n
\n

js

\n
Math.acosh(0); // NaN\nMath.acosh(1); // 0\nMath.acosh(2); // 1.3169578969248166\nMath.acosh(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.acosh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
acosh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acosh\n

\n
\n", + "global_objects/math/asin": "

Math.asin()

\n

The Math.asin() static method returns the inverse sine (in radians) of a number. That is,

x [ 1 , 1 ] , 𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗 ( 𝚡 ) = arcsin ( x ) = the unique y [ π 2 , π 2 ] such that sin ( y ) = x \\forall x \\in [{-1}, 1],;\\mathtt{\\operatorname{Math.asin}(x)} = \\arcsin(x) = \\text{the unique } y \\in \\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right] \\text{ such that } \\sin(y) = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.asin(x)\n
\n

Parameters

\n
x

A number between -1 and 1, inclusive, representing the angle's sine value.

Return value

\n

The inverse sine (angle in radians between - π 2 -\\frac{\\pi}{2} and π 2 \\frac{\\pi}{2} , inclusive) of x. If x is less than -1 or greater than 1, returns NaN.

Description

\n

Because asin() is a static method of Math, you always use it as Math.asin(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.asin()

\n
\n

js

\n
Math.asin(-2); // NaN\nMath.asin(-1); // -1.5707963267948966 (-π/2)\nMath.asin(-0); // -0\nMath.asin(0); // 0\nMath.asin(0.5); // 0.5235987755982989 (π/6)\nMath.asin(1); // 1.5707963267948966 (π/2)\nMath.asin(2); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.asin
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
asin11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin\n

\n
\n", + "global_objects/math/asinh": "

Math.asinh()

\n

The Math.asinh() static method returns the inverse hyperbolic sine of a number. That is,

𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗𝚑 ( 𝚡 ) = arsinh ( x ) = the unique y such that sinh ( y ) = x = ln ( x + x 2 + 1 ) \\begin{aligned}\\mathtt{\\operatorname{Math.asinh}(x)} &= \\operatorname{arsinh}(x) = \\text{the unique } y \\text{ such that } \\sinh(y) = x \\&= \\ln\\left(x + \\sqrt{x^2 + 1}\\right)\\end{aligned}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.asinh(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The inverse hyperbolic sine of x.

Description

\n

Because asinh() is a static method of Math, you always use it as Math.asinh(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.asinh()

\n
\n

js

\n
Math.asinh(-Infinity); // -Infinity\nMath.asinh(-1); // -0.881373587019543\nMath.asinh(-0); // -0\nMath.asinh(0); // 0\nMath.asinh(1); // 0.881373587019543\nMath.asinh(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.asinh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
asinh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asinh\n

\n
\n", + "global_objects/math/atan": "

Math.atan()

\n

The Math.atan() static method returns the inverse tangent (in radians) of a number, that is

𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗 ( 𝚡 ) = arctan ( x ) = the unique y [ π 2 , π 2 ] such that tan ( y ) = x \\mathtt{\\operatorname{Math.atan}(x)} = \\arctan(x) = \\text{the unique } y \\in \\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right] \\text{ such that } \\tan(y) = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.atan(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The inverse tangent (angle in radians between - π 2 -\\frac{\\pi}{2} and π 2 \\frac{\\pi}{2} , inclusive) of x. If x is Infinity, it returns π 2 \\frac{\\pi}{2} . If x is -Infinity, it returns - π 2 -\\frac{\\pi}{2} .

Description

\n

Because atan() is a static method of Math, you always use it as Math.atan(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.atan()

\n
\n
\n

js

\n
Math.atan(-Infinity); // -1.5707963267948966 (-π/2)\nMath.atan(-0); // -0\nMath.atan(0); // 0\nMath.atan(1); // 0.7853981633974483  (π/4)\nMath.atan(Infinity); // 1.5707963267948966  (π/2)\n\n// The angle that the line (0,0) -- (x,y) forms with the x-axis in a Cartesian coordinate system\nconst theta = (x, y) => Math.atan(y / x);\n
\n

Note that you may want to avoid the theta function and use Math.atan2() instead, which has a wider range (between -π and π) and avoids outputting NaN for cases such as when x is 0.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.atan
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
atan11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan\n

\n
\n", + "global_objects/math/atan2": "

Math.atan2()

The Math.atan2() static method returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for Math.atan2(y, x).

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.atan2(y, x)\n
\n

Parameters

\n
y

The y coordinate of the point.

x

The x coordinate of the point.

Return value

\n

The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y).

Description

\n
\n

The Math.atan2() method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point (x, y). Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

\"A

Math.atan2() is passed separate x and y arguments, while Math.atan() is passed the ratio of those two arguments. Math.atan2(y, x) differs from Math.atan(y / x) in the following cases:

x y Math.atan2(y, x) Math.atan(y / x)
Infinity Infinity π / 4 NaN
Infinity -Infinity -π / 4 NaN
-Infinity Infinity 3π / 4 NaN
-Infinity -Infinity -3π / 4 NaN
0 0 0 NaN
0 -0 -0 NaN
< 0 (including -0) 0 π 0
< 0 (including -0) -0 0
-Infinity > 0 π -0
-0 > 0 π / 2 -π / 2
-Infinity < 0 0
-0 < 0 -π / 2 π / 2

In addition, for points in the second and third quadrants (x < 0), Math.atan2() would output an angle less than - π 2 -\\frac{\\pi}{2} or greater than π 2 \\frac{\\pi}{2} .

Because atan2() is a static method of Math, you always use it as Math.atan2(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.atan2()

\n
\n

js

\n
Math.atan2(90, 15); // 1.4056476493802699\nMath.atan2(15, 90); // 0.16514867741462683\n
\n

Difference between Math.atan2(y, x) and Math.atan(y / x)

\n
\n

The following script prints all inputs that produce a difference between Math.atan2(y, x) and Math.atan(y / x).

\n

js

\n
const formattedNumbers = new Map([\n  [-Math.PI, \"-π\"],\n  [(-3 * Math.PI) / 4, \"-3π/4\"],\n  [-Math.PI / 2, \"-π/2\"],\n  [-Math.PI / 4, \"-π/4\"],\n  [Math.PI / 4, \"π/4\"],\n  [Math.PI / 2, \"π/2\"],\n  [(3 * Math.PI) / 4, \"3π/4\"],\n  [Math.PI, \"π\"],\n  [-Infinity, \"-∞\"],\n  [Infinity, \"∞\"],\n]);\n\nfunction format(template, ...args) {\n  return String.raw(\n    { raw: template },\n    ...args.map((num) =>\n      (Object.is(num, -0)\n        ? \"-0\"\n        : formattedNumbers.get(num) ?? String(num)\n      ).padEnd(5),\n    ),\n  );\n}\n\nconsole.log(`| x     | y     | atan2 | atan  |\n|-------|-------|-------|-------|`);\n\nfor (const x of [-Infinity, -1, -0, 0, 1, Infinity]) {\n  for (const y of [-Infinity, -1, -0, 0, 1, Infinity]) {\n    const atan2 = Math.atan2(y, x);\n    const atan = Math.atan(y / x);\n    if (!Object.is(atan2, atan)) {\n      console.log(format`| ${x} | ${y} | ${atan2} | ${atan} |`);\n    }\n  }\n}\n
\n

The output is:

| x     | y     | atan2 | atan  |\n|-------|-------|-------|-------|\n| -∞    | -∞    | -3π/4 | NaN   |\n| -∞    | -1    | -π    | 0     |\n| -∞    | -0    | -π    | 0     |\n| -∞    | 0     | π     | -0    |\n| -∞    | 1     | π     | -0    |\n| -∞    | ∞     | 3π/4  | NaN   |\n| -1    | -∞    | -π/2  | π/2   |\n| -1    | -1    | -3π/4 | π/4   |\n| -1    | -0    | -π    | 0     |\n| -1    | 0     | π     | -0    |\n| -1    | 1     | 3π/4  | -π/4  |\n| -1    | ∞     | π/2   | -π/2  |\n| -0    | -∞    | -π/2  | π/2   |\n| -0    | -1    | -π/2  | π/2   |\n| -0    | -0    | -π    | NaN   |\n| -0    | 0     | π     | NaN   |\n| -0    | 1     | π/2   | -π/2  |\n| -0    | ∞     | π/2   | -π/2  |\n| 0     | -0    | -0    | NaN   |\n| 0     | 0     | 0     | NaN   |\n| ∞     | -∞    | -π/4  | NaN   |\n| ∞     | ∞     | π/4   | NaN   |\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.atan2
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
atan211214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2\n

\n
\n", + "global_objects/math/atanh": "

Math.atanh()

\n

The Math.atanh() static method returns the inverse hyperbolic tangent of a number. That is,

x ( 1 , 1 ) , 𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗𝚑 ( 𝚡 ) = artanh ( x ) = the unique y such that tanh ( y ) = x = 1 2 ln ( 1 + x 1 x ) \\begin{aligned}\\forall x \\in ({-1}, 1),;\\mathtt{\\operatorname{Math.atanh}(x)} &= \\operatorname{artanh}(x) = \\text{the unique } y \\text{ such that } \\tanh(y) = x \\&= \\frac{1}{2},\\ln\\left(\\frac{1+x}{1-x}\\right)\\end{aligned}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.atanh(x)\n
\n

Parameters

\n
x

A number between -1 and 1, inclusive.

Return value

\n

The inverse hyperbolic tangent of x. If x is 1, returns Infinity. If x is -1, returns -Infinity. If x is less than -1 or greater than 1, returns NaN.

Description

\n

Because atanh() is a static method of Math, you always use it as Math.atanh(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.atanh()

\n
\n

js

\n
Math.atanh(-2); // NaN\nMath.atanh(-1); // -Infinity\nMath.atanh(-0); // -0\nMath.atanh(0); // 0\nMath.atanh(0.5); // 0.5493061443340548\nMath.atanh(1); // Infinity\nMath.atanh(2); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.atanh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
atanh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atanh\n

\n
\n", + "global_objects/math/cbrt": "

Math.cbrt()

\n

The Math.cbrt() static method returns the cube root of a number. That is

𝙼𝚊𝚝𝚑.𝚌𝚋𝚛𝚝 ( 𝚡 ) = x 3 = the unique y such that y 3 = x \\mathtt{\\operatorname{Math.cbrt}(x)} = \\sqrt[3]{x} = \\text{the unique } y \\text{ such that } y^3 = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.cbrt(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The cube root of x.

Description

\n

Because cbrt() is a static method of Math, you always use it as Math.cbrt(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.cbrt()

\n
\n

js

\n
Math.cbrt(-Infinity); // -Infinity\nMath.cbrt(-1); // -1\nMath.cbrt(-0); // -0\nMath.cbrt(0); // 0\nMath.cbrt(1); // 1\nMath.cbrt(2); // 1.2599210498948732\nMath.cbrt(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.cbrt
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
cbrt381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt\n

\n
\n", + "global_objects/math/ceil": "

Math.ceil()

The Math.ceil() static method always rounds up and returns the smallest integer greater than or equal to a given number.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.ceil(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The smallest integer greater than or equal to x. It's the same value as -Math.floor(-x).

Description

\n

Because ceil() is a static method of Math, you always use it as Math.ceil(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.ceil()

\n
\n

js

\n
Math.ceil(-Infinity); // -Infinity\nMath.ceil(-7.004); // -7\nMath.ceil(-4); // -4\nMath.ceil(-0.95); // -0\nMath.ceil(-0); // -0\nMath.ceil(0); // 0\nMath.ceil(0.95); // 1\nMath.ceil(4); // 4\nMath.ceil(7.004); // 8\nMath.ceil(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.ceil
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ceil11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil\n

\n
\n", + "global_objects/math/clz32": "

Math.clz32()

The Math.clz32() static method returns the number of leading zero bits in the 32-bit binary representation of a number.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.clz32(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The number of leading zero bits in the 32-bit binary representation of x.

Description

\n
\n

clz32 is short for CountLeadingZeros32.

If x is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer.

If the converted 32-bit unsigned integer is 0, 32 is returned, because all bits are 0. If the most significant bit is 1 (i.e. the number is greater than or equal to 231), 0 is returned.

This function is particularly useful for systems that compile to JS, like Emscripten.

\n

Examples

\n

Using Math.clz32()

\n
\n

js

\n
Math.clz32(1); // 31\nMath.clz32(1000); // 22\nMath.clz32(); // 32\n\nconst stuff = [\n  NaN,\n  Infinity,\n  -Infinity,\n  0,\n  -0,\n  false,\n  null,\n  undefined,\n  \"foo\",\n  {},\n  [],\n];\nstuff.every((n) => Math.clz32(n) === 32); // true\n\nMath.clz32(true); // 31\nMath.clz32(3.5); // 30\n
\n

Implementing Count Leading Ones and beyond

\n
\n

At present, there is no Math.clon for \"Count Leading Ones\" (named \"clon\", not \"clo\", because \"clo\" and \"clz\" are too similar especially for non-English-speaking people). However, a clon function can easily be created by inverting the bits of a number and passing the result to Math.clz32. Doing this will work because the inverse of 1 is 0 and vice versa. Thus, inverting the bits will inverse the measured quantity of 0's (from Math.clz32), thereby making Math.clz32 count the number of ones instead of counting the number of zeros.

Consider the following 32-bit word:

\n

js

\n
const a = 32776; // 00000000000000001000000000001000 (16 leading zeros)\nMath.clz32(a); // 16\n\nconst b = ~32776; // 11111111111111110111111111110111 (32776 inverted, 0 leading zeros)\nMath.clz32(b); // 0 (this is equal to how many leading one's there are in a)\n
\n

Using this logic, a clon function can be created as follows:

\n

js

\n
const clz = Math.clz32;\n\nfunction clon(integer) {\n  return clz(~integer);\n}\n
\n

Further, this technique could be extended to create a jumpless \"Count Trailing Zeros\" function, as seen below. The ctrz function takes a bitwise AND of the integer with its two's complement. By how two's complement works, all trailing zeros will be converted to ones, and then when adding 1, it would be carried over until the first 0 (which was originally a 1) is reached. All bits higher than this one stay the same and are inverses of the original integer's bits. Therefore, when doing bitwise AND with the original integer, all higher bits become 0, which can be counted with clz. The number of trailing zeros, plus the first 1 bit, plus the leading bits that were counted by clz, total to 32.

\n

js

\n
function ctrz(integer) {\n  integer >>>= 0; // coerce to Uint32\n  if (integer === 0) {\n    // skipping this step would make it return -1\n    return 32;\n  }\n  integer &= -integer; // equivalent to `int = int & (~int + 1)`\n  return 31 - clz(integer);\n}\n
\n

Then we can define a \"Count Trailing Ones\" function like so:

\n

js

\n
function ctron(integer) {\n  return ctrz(~integer);\n}\n
\n

These helper functions can be made into an asm.js module for a potential performance improvement.

\n

js

\n
const countTrailsMethods = (function (stdlib, foreign, heap) {\n  \"use asm\";\n  const clz = stdlib.Math.clz32;\n\n  // count trailing zeros\n  function ctrz(integer) {\n    integer = integer | 0; // coerce to an integer\n    if ((integer | 0) == 0) {\n      // skipping this step would make it return -1\n      return 32;\n    }\n    // Note: asm.js doesn't have compound assignment operators such as &=\n    integer = integer & -integer; // equivalent to `int = int & (~int + 1)`\n    return (31 - clz(integer)) | 0;\n  }\n\n  // count trailing ones\n  function ctron(integer) {\n    integer = integer | 0; // coerce to an integer\n    return ctrz(~integer) | 0;\n  }\n\n  // asm.js demands plain objects:\n  return { ctrz: ctrz, ctron: ctron };\n})(window, null, null);\n\nconst { ctrz, ctron } = countTrailsMethods;\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.clz32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
clz32381231No2573838312573.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32\n

\n
\n", + "global_objects/math/cos": "

Math.cos()

The Math.cos() static method returns the cosine of a number in radians.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.cos(x)\n
\n

Parameters

\n
x

A number representing an angle in radians.

Return value

\n

The cosine of x, between -1 and 1, inclusive. If x is Infinity, -Infinity, or NaN, returns NaN.

Description

\n

Because cos() is a static method of Math, you always use it as Math.cos(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.cos()

\n
\n

js

\n
Math.cos(-Infinity); // NaN\nMath.cos(-0); // 1\nMath.cos(0); // 1\nMath.cos(1); // 0.5403023058681398\nMath.cos(Math.PI); // -1\nMath.cos(2 * Math.PI); // 1\nMath.cos(Infinity); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.cos
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
cos11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos\n

\n
\n", + "global_objects/math/cosh": "

Math.cosh()

\n

The Math.cosh() static method returns the hyperbolic cosine of a number. That is,

𝙼𝚊𝚝𝚑.𝚌𝚘𝚜𝚑 ( 𝚡 ) = cosh ( x ) = e x + e x 2 \\mathtt{\\operatorname{Math.cosh}(x)} = \\cosh(x) = \\frac{\\mathrm{e}^x + \\mathrm{e}^{-x}}{2}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.cosh(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The hyperbolic cosine of x.

Description

\n

Because cosh() is a static method of Math, you always use it as Math.cosh(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.cosh()

\n
\n

js

\n
Math.cosh(-Infinity); // Infinity\nMath.cosh(-1); // 1.5430806348152437\nMath.cosh(-0); // 1\nMath.cosh(0); // 1\nMath.cosh(1); // 1.5430806348152437\nMath.cosh(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.cosh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
cosh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cosh\n

\n
\n", + "global_objects/math/exp": "

Math.exp()

\n

The Math.exp() static method returns e raised to the power of a number. That is

𝙼𝚊𝚝𝚑.𝚎𝚡𝚙 ( 𝚡 ) = e x \\mathtt{\\operatorname{Math.exp}(x)} = \\mathrm{e}^x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.exp(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

A nonnegative number representing ex, where e is the base of the natural logarithm.

Description

\n
\n

Because exp() is a static method of Math, you always use it as Math.exp(), rather than as a method of a Math object you created (Math is not a constructor).

Beware that e to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use Math.expm1 instead, and obtain a much higher-precision fractional part of the answer.

\n

Examples

\n

Using Math.exp()

\n
\n

js

\n
Math.exp(-Infinity); // 0\nMath.exp(-1); // 0.36787944117144233\nMath.exp(0); // 1\nMath.exp(1); // 2.718281828459045\nMath.exp(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.exp
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
exp11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp\n

\n
\n", + "global_objects/math/expm1": "

Math.expm1()

\n

The Math.expm1() static method returns e raised to the power of a number, subtracted by 1. That is

𝙼𝚊𝚝𝚑.𝚎𝚡𝚙𝚖𝟷 ( 𝚡 ) = e x 1 \\mathtt{\\operatorname{Math.expm1}(x)} = \\mathrm{e}^x - 1

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.expm1(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

A number representing ex - 1, where e is the base of the natural logarithm.

Description

\n
\n

For very small values of x, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.

When you calculate e x \\mathrm{e}^x where x is a number very close to 0, you should get an answer very close to 1 + x, because lim x 0 e x 1 x = 1 \\lim_{x \\to 0} \\frac{\\mathrm{e}^x - 1}{x} = 1 . If you calculate Math.exp(1.1111111111e-15) - 1, you should get an answer close to 1.1111111111e-15. Instead, due to the highest significant figure in the result of Math.exp being the units digit 1, the final value ends up being 1.1102230246251565e-15, with only 3 correct digits. If, instead, you calculate Math.exp1m(1.1111111111e-15), you will get a much more accurate answer 1.1111111111000007e-15, with 11 correct digits of precision.

Because expm1() is a static method of Math, you always use it as Math.expm1(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.expm1()

\n
\n

js

\n
Math.expm1(-Infinity); // -1\nMath.expm1(-1); // -0.6321205588285577\nMath.expm1(-0); // -0\nMath.expm1(0); // 0\nMath.expm1(1); // 1.718281828459045\nMath.expm1(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.expm1
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
expm1381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1\n

\n
\n", + "global_objects/math/floor": "

Math.floor()

The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.floor(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The largest integer smaller than or equal to x. It's the same value as -Math.ceil(-x).

Description

\n

Because floor() is a static method of Math, you always use it as Math.floor(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.floor()

\n
\n

js

\n
Math.floor(-Infinity); // -Infinity\nMath.floor(-45.95); // -46\nMath.floor(-45.05); // -46\nMath.floor(-0); // -0\nMath.floor(0); // 0\nMath.floor(4); // 4\nMath.floor(45.05); // 45\nMath.floor(45.95); // 45\nMath.floor(Infinity); // Infinity\n
\n

Decimal adjustment

\n
\n

In this example, we implement a method called decimalAdjust() that is an enhancement method of Math.floor(), Math.ceil(), and Math.round(). While the three Math functions always adjust the input to the units digit, decimalAdjust accepts an exp parameter that specifies the number of digits to the left of the decimal point to which the number should be adjusted. For example, -1 means it would leave one digit after the decimal point (as in \"× 10-1\"). In addition, it allows you to select the means of adjustment — round, floor, or ceil — through the type parameter.

It does so by multiplying the number by a power of 10, then rounding the result to the nearest integer, then dividing by the power of 10. To better preserve precision, it takes advantage of Number's toString() method, which represents large or small numbers in scientific notation (like 6.02e23).

\n

js

\n
/**\n * Adjusts a number to the specified digit.\n *\n * @param {\"round\" | \"floor\" | \"ceil\"} type The type of adjustment.\n * @param {number} value The number.\n * @param {number} exp The exponent (the 10 logarithm of the adjustment base).\n * @returns {number} The adjusted value.\n */\nfunction decimalAdjust(type, value, exp) {\n  type = String(type);\n  if (![\"round\", \"floor\", \"ceil\"].includes(type)) {\n    throw new TypeError(\n      \"The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.\",\n    );\n  }\n  exp = Number(exp);\n  value = Number(value);\n  if (exp % 1 !== 0 || Number.isNaN(value)) {\n    return NaN;\n  } else if (exp === 0) {\n    return Math[type](value);\n  }\n  const [magnitude, exponent = 0] = value.toString().split(\"e\");\n  const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`);\n  // Shift back\n  const [newMagnitude, newExponent = 0] = adjustedValue.toString().split(\"e\");\n  return Number(`${newMagnitude}e${+newExponent + exp}`);\n}\n\n// Decimal round\nconst round10 = (value, exp) => decimalAdjust(\"round\", value, exp);\n// Decimal floor\nconst floor10 = (value, exp) => decimalAdjust(\"floor\", value, exp);\n// Decimal ceil\nconst ceil10 = (value, exp) => decimalAdjust(\"ceil\", value, exp);\n\n// Round\nround10(55.55, -1); // 55.6\nround10(55.549, -1); // 55.5\nround10(55, 1); // 60\nround10(54.9, 1); // 50\nround10(-55.55, -1); // -55.5\nround10(-55.551, -1); // -55.6\nround10(-55, 1); // -50\nround10(-55.1, 1); // -60\n// Floor\nfloor10(55.59, -1); // 55.5\nfloor10(59, 1); // 50\nfloor10(-55.51, -1); // -55.6\nfloor10(-51, 1); // -60\n// Ceil\nceil10(55.51, -1); // 55.6\nceil10(51, 1); // 60\nceil10(-55.59, -1); // -55.5\nceil10(-59, 1); // -50\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.floor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
floor11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor\n

\n
\n", + "global_objects/math/fround": "

Math.fround()

The Math.fround() static method returns the nearest 32-bit single precision float representation of a number.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.fround(doubleFloat)\n
\n

Parameters

\n
doubleFloat

A number.

Return value

\n

The nearest 32-bit single precision float representation of x.

Description

\n
\n

JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a Float32Array. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.

To solve this, Math.fround() can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a \"round to even\" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, Infinity or -Infinity is returned.

Because fround() is a static method of Math, you always use it as Math.fround(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.fround()

\n
\n

The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:

\n

js

\n
Math.fround(1.5); // 1.5\nMath.fround(1.5) === 1.5; // true\n
\n

However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:

\n

js

\n
Math.fround(1.337); // 1.3370000123977661\nMath.fround(1.337) === 1.337; // false\n
\n

2 150 2^150 is too big for a 32-bit float, so Infinity is returned:

\n

js

\n
2 ** 150; // 1.42724769270596e+45\nMath.fround(2 ** 150); // Infinity\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.fround
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fround381226No2583838262583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround\n

\n
\n", + "global_objects/math/hypot": "

Math.hypot()

\n

The Math.hypot() static method returns the square root of the sum of squares of its arguments. That is,

𝙼𝚊𝚝𝚑.𝚑𝚢𝚙𝚘𝚝 ( v 1 , v 2 , , v n ) = i = 1 n v i 2 = v 1 2 + v 2 2 + + v n 2 \\mathtt{\\operatorname{Math.hypot}(v_1, v_2, \\dots, v_n)} = \\sqrt{\\sum_{i=1}^n v_i^2} = \\sqrt{v_1^2 + v_2^2 + \\dots + v_n^2}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.hypot()\nMath.hypot(value1)\nMath.hypot(value1, value2)\nMath.hypot(value1, value2, /* …, */ valueN)\n
\n

Parameters

\n
\nvalue1, …, valueN\n

Numbers.

Return value

\n

The square root of the sum of squares of the given arguments. Returns Infinity if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to NaN, returns NaN. Returns 0 if no arguments are given or all arguments are ±0.

Description

\n
\n

Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula Math.sqrt(v1*v1 + v2*v2), where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4).

This function makes this calculation easier and faster; you call Math.hypot(v1, v2), or Math.hypot(v1, /* …, */, vN).

Math.hypot also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is Number.MAX_VALUE, which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity. If you use hypot() instead, you get a better answer: Math.hypot(1e200, 1e200) = 1.4142...e+200 . This is also true with very small numbers. Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, but Math.hypot(1e-200, 1e-200) = 1.4142...e-200.

With one argument, Math.hypot() is equivalent to Math.abs(). Math.hypot.length is 2, which weakly signals that it's designed to handle at least two parameters.

Because hypot() is a static method of Math, you always use it as Math.hypot(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.hypot()

\n
\n

js

\n
Math.hypot(3, 4); // 5\nMath.hypot(3, 4, 5); // 7.0710678118654755\nMath.hypot(); // 0\nMath.hypot(NaN); // NaN\nMath.hypot(NaN, Infinity); // Infinity\nMath.hypot(3, 4, \"foo\"); // NaN, since +'foo' => NaN\nMath.hypot(3, 4, \"5\"); // 7.0710678118654755, +'5' => 5\nMath.hypot(-3); // 3, the same as Math.abs(-3)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.hypot
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hypot381227No2583838272583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot\n

\n
\n", + "global_objects/math/imul": "

Math.imul()

The Math.imul() static method returns the result of the C-like 32-bit multiplication of the two parameters.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.imul(a, b)\n
\n

Parameters

\n
a

First number.

b

Second number.

Return value

\n

The result of the C-like 32-bit multiplication of the given arguments.

Description

\n
\n

Math.imul() allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten.

Because imul() is a static method of Math, you always use it as Math.imul(), rather than as a method of a Math object you created (Math is not a constructor).

If you use normal JavaScript floating point numbers in imul(), you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. However, with asm.js, which allows JIT-optimizers to more confidently use integers in JavaScript, multiplying two numbers stored internally as integers (which is only possible with asm.js) with imul() could be potentially more performant.

\n

Examples

\n

Using Math.imul()

\n
\n

js

\n
Math.imul(2, 4); // 8\nMath.imul(-1, 8); // -8\nMath.imul(-2, -2); // 4\nMath.imul(0xffffffff, 5); // -5\nMath.imul(0xfffffffe, 5); // -10\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.imul
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
imul281220No1674.428201571.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul\n

\n
\n", + "global_objects/math/log": "

Math.log()

\n

The Math.log() static method returns the natural logarithm (base e) of a number. That is

x > 0 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐 ( 𝚡 ) = ln ( x ) = the unique y such that e y = x \\forall x > 0,;\\mathtt{\\operatorname{Math.log}(x)} = \\ln(x) = \\text{the unique } y \\text{ such that } e^y = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.log(x)\n
\n

Parameters

\n
x

A number greater than or equal to 0.

Return value

\n

The natural logarithm (base e) of x. If x is ±0, returns -Infinity. If x < 0, returns NaN.

Description

\n
\n

Because log() is a static method of Math, you always use it as Math.log(), rather than as a method of a Math object you created (Math is not a constructor).

If you need the natural log of 2 or 10, use the constants Math.LN2 or Math.LN10. If you need a logarithm to base 2 or 10, use Math.log2() or Math.log10(). If you need a logarithm to other bases, use Math.log(x) / Math.log(otherBase) as in the example below; you might want to precalculate 1 / Math.log(otherBase) since multiplication in Math.log(x) * constant is much faster.

Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use Math.log1p instead.

\n

Examples

\n

Using Math.log()

\n
\n

js

\n
Math.log(-1); // NaN\nMath.log(-0); // -Infinity\nMath.log(0); // -Infinity\nMath.log(1); // 0\nMath.log(10); // 2.302585092994046\nMath.log(Infinity); // Infinity\n
\n

Using Math.log() with a different base

\n
\n

The following function returns the logarithm of y with base x (i.e. log x y \\log_x y ):

\n

js

\n
function getBaseLog(x, y) {\n  return Math.log(y) / Math.log(x);\n}\n
\n

If you run getBaseLog(10, 1000), it returns 2.9999999999999996 due to floating-point rounding, but still very close to the actual answer of 3.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
log11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log\n

\n
\n", + "global_objects/math/log10": "

Math.log10()

\n

The Math.log10() static method returns the base 10 logarithm of a number. That is

x > 0 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝟶 ( 𝚡 ) = log 10 ( x ) = the unique y such that 10 y = x \\forall x > 0,;\\mathtt{\\operatorname{Math.log10}(x)} = \\log_{10}(x) = \\text{the unique } y \\text{ such that } 10^y = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.log10(x)\n
\n

Parameters

\n
x

A number greater than or equal to 0.

Return value

\n

The base 10 logarithm of x. If x < 0, returns NaN.

Description

\n
\n

Because log10() is a static method of Math, you always use it as Math.log10(), rather than as a method of a Math object you created (Math is not a constructor).

This function is the equivalent of Math.log(x) / Math.log(10). For log10(e), use the constant Math.LOG10E, which is 1 / Math.LN10.

\n

Examples

\n

Using Math.log10()

\n
\n

js

\n
Math.log10(-2); // NaN\nMath.log10(-0); // -Infinity\nMath.log10(0); // -Infinity\nMath.log10(1); // 0\nMath.log10(2); // 0.3010299956639812\nMath.log10(100000); // 5\nMath.log10(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log10
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
log10381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10\n

\n
\n", + "global_objects/math/log1p": "

Math.log1p()

\n

The Math.log1p() static method returns the natural logarithm (base e) of 1 + x, where x is the argument. That is:

x > 1 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝚙 ( 𝚡 ) = ln ( 1 + x ) \\forall x > -1,;\\mathtt{\\operatorname{Math.log1p}(x)} = \\ln(1 + x)

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.log1p(x)\n
\n

Parameters

\n
x

A number greater than or equal to -1.

Return value

\n

The natural logarithm (base e) of x + 1. If x is -1, returns -Infinity. If x < -1, returns NaN.

Description

\n
\n

For very small values of x, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.

When you calculate log(1 + x) where x is a small positive number, you should get an answer very close to x, because lim x 0 log ( 1 + x ) x = 1 \\lim_{x \\to 0} \\frac{\\log(1+x)}{x} = 1 . If you calculate Math.log(1 + 1.1111111111e-15), you should get an answer close to 1.1111111111e-15. Instead, you will end up taking the logarithm of 1.00000000000000111022 (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate Math.log1p(1.1111111111e-15), you will get a much more accurate answer 1.1111111110999995e-15, with 15 correct digits of precision (actually 16 in this case).

If the value of x is less than -1, the return value is always NaN.

Because log1p() is a static method of Math, you always use it as Math.log1p(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.log1p()

\n
\n

js

\n
Math.log1p(-2); // NaN\nMath.log1p(-1); // -Infinity\nMath.log1p(-0); // -0\nMath.log1p(0); // 0\nMath.log1p(1); // 0.6931471805599453\nMath.log1p(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log1p
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
log1p381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log1p\n

\n
\n", + "global_objects/math/log2": "

Math.log2()

\n

The Math.log2() static method returns the base 2 logarithm of a number. That is

x > 0 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟸 ( 𝚡 ) = log 2 ( x ) = the unique y such that 2 y = x \\forall x > 0,;\\mathtt{\\operatorname{Math.log2}(x)} = \\log_2(x) = \\text{the unique } y \\text{ such that } 2^y = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.log2(x)\n
\n

Parameters

\n
x

A number greater than or equal to 0.

Return value

\n

The base 2 logarithm of x. If x < 0, returns NaN.

Description

\n
\n

Because log2() is a static method of Math, you always use it as Math.log2(), rather than as a method of a Math object you created (Math is not a constructor).

This function is the equivalent of Math.log(x) / Math.log(2). For log2(e), use the constant Math.LOG2E, which is 1 / Math.LN2.

\n

Examples

\n

Using Math.log2()

\n
\n

js

\n
Math.log2(-2); // NaN\nMath.log2(-0); // -Infinity\nMath.log2(0); // -Infinity\nMath.log2(1); // 0\nMath.log2(2); // 1\nMath.log2(3); // 1.584962500721156\nMath.log2(1024); // 10\nMath.log2(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.log2
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
log2381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2\n

\n
\n", + "global_objects/math/max": "

Math.max()

The Math.max() static method returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.max()\nMath.max(value1)\nMath.max(value1, value2)\nMath.max(value1, value2, /* …, */ valueN)\n
\n

Parameters

\n
\nvalue1, …, valueN\n

Zero or more numbers among which the largest value will be selected and returned.

Return value

\n

The largest of the given numbers. Returns NaN if any of the parameters is or is converted into NaN. Returns -Infinity if no parameters are provided.

Description

\n
\n

Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).

Math.max.length is 2, which weakly signals that it's designed to handle at least two parameters.

\n

Examples

\n

Using Math.max()

\n
\n

js

\n
Math.max(10, 20); // 20\nMath.max(-10, -20); // -10\nMath.max(-10, 20); // 20\n
\n

Getting the maximum element of an array

\n
\n

Array.prototype.reduce() can be used to find the maximum element in a numeric array, by comparing each value:

\n

js

\n
const arr = [1, 2, 3];\nconst max = arr.reduce((a, b) => Math.max(a, b), -Infinity);\n
\n

The following function uses Function.prototype.apply() to get the maximum of an array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays. This should only be used for arrays with relatively few elements.

\n

js

\n
function getMaxOfArray(numArray) {\n  return Math.max.apply(null, numArray);\n}\n
\n

The spread syntax is a shorter way of writing the apply solution to get the maximum of an array:

\n

js

\n
const arr = [1, 2, 3];\nconst max = Math.max(...arr);\n
\n

However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See Using apply and built-in functions for more details. The reduce solution does not have this problem.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.max
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
max11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max\n

\n
\n", + "global_objects/math/min": "

Math.min()

The Math.min() static method returns the smallest of the numbers given as input parameters, or Infinity if there are no parameters.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.min()\nMath.min(value1)\nMath.min(value1, value2)\nMath.min(value1, value2, /* …, */ valueN)\n
\n

Parameters

\n
\nvalue1, …, valueN\n

Zero or more numbers among which the lowest value will be selected and returned.

Return value

\n

The smallest of the given numbers. Returns NaN if any of the parameters is or is converted into NaN. Returns Infinity if no parameters are provided.

Description

\n
\n

Because min() is a static method of Math, you always use it as Math.min(), rather than as a method of a Math object you created (Math is not a constructor).

Math.min.length is 2, which weakly signals that it's designed to handle at least two parameters.

\n

Examples

\n

Using Math.min()

\n
\n

This finds the min of x and y and assigns it to z:

\n

js

\n
const x = 10;\nconst y = -20;\nconst z = Math.min(x, y); // -20\n
\n
\n

Clipping a value with Math.min()

\n
\n

Math.min() is often used to clip a value so that it is always less than or equal to a boundary. For instance, this

\n

js

\n
let x = f(foo);\n\nif (x > boundary) {\n  x = boundary;\n}\n
\n

may be written as this

\n

js

\n
const x = Math.min(f(foo), boundary);\n
\n

Math.max() can be used in a similar way to clip a value at the other end.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.min
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
min11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min\n

\n
\n", + "global_objects/math/pow": "

Math.pow()

\n

The Math.pow() static method returns the value of a base raised to a power. That is

𝙼𝚊𝚝𝚑.𝚙𝚘𝚠 ( 𝚡 , 𝚢 ) = x y \\mathtt{\\operatorname{Math.pow}(x, y)} = x^y

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.pow(base, exponent)\n
\n

Parameters

\n
base

The base number.

exponent

The exponent number.

Return value

\n
\n

A number representing base taken to the power of exponent. Returns NaN in one of the following cases:

\n

Description

\n
\n

Math.pow() is equivalent to the ** operator, except Math.pow() only accepts numbers.

Math.pow(NaN, 0) (and the equivalent NaN ** 0) is the only case where NaN doesn't propagate through mathematical operations — it returns 1 despite the operand being NaN. In addition, the behavior where base is 1 and exponent is non-finite (±Infinity or NaN) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns NaN to preserve backward compatibility with its original behavior.

Because pow() is a static method of Math, use it as Math.pow(), rather than as a method of a Math object you created (Math is not a constructor).

\n

Examples

\n

Using Math.pow()

\n
\n

js

\n
// Simple cases\nMath.pow(7, 2); // 49\nMath.pow(7, 3); // 343\nMath.pow(2, 10); // 1024\n\n// Fractional exponents\nMath.pow(4, 0.5); // 2 (square root of 4)\nMath.pow(8, 1 / 3); // 2 (cube root of 8)\nMath.pow(2, 0.5); // 1.4142135623730951 (square root of 2)\nMath.pow(2, 1 / 3); // 1.2599210498948732 (cube root of 2)\n\n// Signed exponents\nMath.pow(7, -2); // 0.02040816326530612 (1/49)\nMath.pow(8, -1 / 3); // 0.5\n\n// Signed bases\nMath.pow(-7, 2); // 49 (squares are positive)\nMath.pow(-7, 3); // -343 (cubes can be negative)\nMath.pow(-7, 0.5); // NaN (negative numbers don't have a real square root)\n// Due to \"even\" and \"odd\" roots laying close to each other,\n// and limits in the floating number precision,\n// negative bases with fractional exponents always return NaN,\n// even when the mathematical result is real\nMath.pow(-7, 1 / 3); // NaN\n\n// Zero and infinity\nMath.pow(0, 0); // 1 (anything ** ±0 is 1)\nMath.pow(Infinity, 0.1); // Infinity (positive exponent)\nMath.pow(Infinity, -1); // 0 (negative exponent)\nMath.pow(-Infinity, 1); // -Infinity (positive odd integer exponent)\nMath.pow(-Infinity, 1.5); // Infinity (positive exponent)\nMath.pow(-Infinity, -1); // -0 (negative odd integer exponent)\nMath.pow(-Infinity, -1.5); // 0 (negative exponent)\nMath.pow(0, 1); // 0 (positive exponent)\nMath.pow(0, -1); // Infinity (negative exponent)\nMath.pow(-0, 1); // -0 (positive odd integer exponent)\nMath.pow(-0, 1.5); // 0 (positive exponent)\nMath.pow(-0, -1); // -Infinity (negative odd integer exponent)\nMath.pow(-0, -1.5); // Infinity (negative exponent)\nMath.pow(0.9, Infinity); // 0\nMath.pow(1, Infinity); // NaN\nMath.pow(1.1, Infinity); // Infinity\nMath.pow(0.9, -Infinity); // Infinity\nMath.pow(1, -Infinity); // NaN\nMath.pow(1.1, -Infinity); // 0\n\n// NaN: only Math.pow(NaN, 0) does not result in NaN\nMath.pow(NaN, 0); // 1\nMath.pow(NaN, 1); // NaN\nMath.pow(1, NaN); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.pow
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
pow11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow\n

\n
\n", + "global_objects/math/random": "

Math.random()

\n

The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.random()\n
\n

Parameters

\n

None.

Return value

\n

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples

\n

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to reach the usually-excluded upper bound.

Getting a random number between 0 (inclusive) and 1 (exclusive)

\n
\n

js

\n
function getRandom() {\n  return Math.random();\n}\n
\n

Getting a random number between two values

\n
\n

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

\n

js

\n
function getRandomArbitrary(min, max) {\n  return Math.random() * (max - min) + min;\n}\n
\n
\n

Getting a random integer between two values

\n
\n

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.

\n

js

\n
function getRandomInt(min, max) {\n  min = Math.ceil(min);\n  max = Math.floor(max);\n  return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive\n}\n
\n

Note: It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

\n

Getting a random integer between two values, inclusive

\n
\n

While the getRandomInt() function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

\n

js

\n
function getRandomIntInclusive(min, max) {\n  min = Math.ceil(min);\n  max = Math.floor(max);\n  return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.random
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
random11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random\n

\n
\n", + "global_objects/math/round": "

Math.round()

The Math.round() static method returns the value of a number rounded to the nearest integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.round(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The value of x rounded to the nearest integer.

Description

\n
\n

If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.

Note: This differs from many languages' round() functions, which often round half-increments away from zero, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

Math.round(x) is not exactly the same as Math.floor(x + 0.5). When x is -0, or -0.5 ≤ x < 0, Math.round(x) returns -0, while Math.floor(x + 0.5) returns 0. However, neglecting that difference and potential precision errors, Math.round(x) and Math.floor(x + 0.5) are generally equivalent.

Because round() is a static method of Math, you always use it as Math.round(), rather than as a method of a Math object you created (Math has no constructor).

\n

Examples

\n

Using round

\n
\n

js

\n
Math.round(-Infinity); // -Infinity\nMath.round(-20.51); // -21\nMath.round(-20.5); // -20\nMath.round(-0.1); // -0\nMath.round(0); // 0\nMath.round(20.49); // 20\nMath.round(20.5); // 21\nMath.round(42); // 42\nMath.round(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.round
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
round11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n

\n
\n", + "global_objects/math/sign": "

Math.sign()

The Math.sign() static method returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.sign(x)\n
\n

Parameters

\n
x

A number.

Return value

\n
\n

A number representing the sign of x:

\n

Description

\n

Because sign() is a static method of Math, you always use it as Math.sign(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.sign()

\n
\n

js

\n
Math.sign(3); // 1\nMath.sign(-3); // -1\nMath.sign(\"-3\"); // -1\nMath.sign(0); // 0\nMath.sign(-0); // -0\nMath.sign(NaN); // NaN\nMath.sign(\"foo\"); // NaN\nMath.sign(); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sign
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sign381225No2593838252593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign\n

\n
\n", + "global_objects/math/sin": "

Math.sin()

The Math.sin() static method returns the sine of a number in radians.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.sin(x)\n
\n

Parameters

\n
x

A number representing an angle in radians.

Return value

\n

The sine of x, between -1 and 1, inclusive. If x is Infinity, -Infinity, or NaN, returns NaN.

Description

\n

Because sin() is a static method of Math, you always use it as Math.sin(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.sin()

\n
\n

js

\n
Math.sin(-Infinity); // NaN\nMath.sin(-0); // -0\nMath.sin(0); // 0\nMath.sin(1); // 0.8414709848078965\nMath.sin(Math.PI / 2); // 1\nMath.sin(Infinity); // NaN\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sin
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sin11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin\n

\n
\n", + "global_objects/math/sinh": "

Math.sinh()

\n

The Math.sinh() static method returns the hyperbolic sine of a number. That is,

𝙼𝚊𝚝𝚑.𝚜𝚒𝚗𝚑 ( 𝚡 ) = sinh ( x ) = e x e x 2 \\mathtt{\\operatorname{Math.sinh}(x)} = \\sinh(x) = \\frac{\\mathrm{e}^x - \\mathrm{e}^{-x}}{2}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.sinh(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The hyperbolic sine of x.

Description

\n

Because sinh() is a static method of Math, you always use it as Math.sinh(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.sinh()

\n
\n

js

\n
Math.sinh(-Infinity); // -Infinity\nMath.sinh(-0); // -0\nMath.sinh(0); // 0\nMath.sinh(1); // 1.1752011936438014\nMath.sinh(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sinh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sinh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sinh\n

\n
\n", + "global_objects/math/sqrt": "

Math.sqrt()

\n

The Math.sqrt() static method returns the square root of a number. That is

x 0 , 𝙼𝚊𝚝𝚑.𝚜𝚚𝚛𝚝 ( 𝚡 ) = x = the unique y 0 such that y 2 = x \\forall x \\geq 0,;\\mathtt{\\operatorname{Math.sqrt}(x)} = \\sqrt{x} = \\text{the unique } y \\geq 0 \\text{ such that } y^2 = x

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.sqrt(x)\n
\n

Parameters

\n
x

A number greater than or equal to 0.

Return value

\n

The square root of x, a nonnegative number. If x < 0, returns NaN.

Description

\n

Because sqrt() is a static method of Math, you always use it as Math.sqrt(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.sqrt()

\n
\n

js

\n
Math.sqrt(-1); // NaN\nMath.sqrt(-0); // -0\nMath.sqrt(0); // 0\nMath.sqrt(1); // 1\nMath.sqrt(2); // 1.414213562373095\nMath.sqrt(9); // 3\nMath.sqrt(Infinity); // Infinity\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.sqrt
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sqrt11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt\n

\n
\n", + "global_objects/math/tan": "

Math.tan()

The Math.tan() static method returns the tangent of a number in radians.

\n

Try it

\n

Syntax

\n
\n

js

\n
Math.tan(x)\n
\n

Parameters

\n
x

A number representing an angle in radians.

Return value

\n
\n

The tangent of x. If x is Infinity, -Infinity, or NaN, returns NaN.

Note: Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not NaN.

\n

Description

\n

Because tan() is a static method of Math, you always use it as Math.tan(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.tan()

\n
\n

js

\n
Math.tan(-Infinity); // NaN\nMath.tan(-0); // -0\nMath.tan(0); // 0\nMath.tan(1); // 1.5574077246549023\nMath.tan(Math.PI / 4); // 0.9999999999999999 (Floating point error)\nMath.tan(Infinity); // NaN\n
\n

Math.tan() and π/2

\n
\n

It's not possible to calculate tan(π/2) exactly.

\n

js

\n
Math.tan(Math.PI / 2); // 16331239353195370\nMath.tan(Math.PI / 2 + Number.EPSILON); // -6218431163823738\n
\n
\n

Using Math.tan() with a degree value

\n
\n

Because the Math.tan() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.

\n

js

\n
function getTanDeg(deg) {\n  const rad = (deg * Math.PI) / 180;\n  return Math.tan(rad);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.tan
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
tan11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan\n

\n
\n", + "global_objects/math/tanh": "

Math.tanh()

\n

The Math.tanh() static method returns the hyperbolic tangent of a number. That is,

𝙼𝚊𝚝𝚑.𝚝𝚊𝚗𝚑 ( 𝚡 ) = tanh ( x ) = sinh ( x ) cosh ( x ) = e x e x e x + e x = e 2 x 1 e 2 x + 1 \\mathtt{\\operatorname{Math.tanh}(x)} = \\tanh(x) = \\frac{\\sinh(x)}{\\cosh(x)} = \\frac{\\mathrm{e}^x - \\mathrm{e}^{-x}}{\\mathrm{e}^x + \\mathrm{e}^{-x}} = \\frac{\\mathrm{e}^{2x} - 1}{\\mathrm{e}^{2x}+1}

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Math.tanh(x)\n
\n

Parameters

\n
x

A number.

Return value

\n

The hyperbolic tangent of x.

Description

\n

Because tanh() is a static method of Math, you always use it as Math.tanh(), rather than as a method of a Math object you created (Math is not a constructor).

Examples

\n

Using Math.tanh()

\n
\n

js

\n
Math.tanh(-Infinity); // -1\nMath.tanh(-0); // -0\nMath.tanh(0); // 0\nMath.tanh(1); // 0.7615941559557649\nMath.tanh(Infinity); // 1\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-math.tanh
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
tanh381225No2583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tanh\n

\n
\n", + "global_objects/date/gettime": "

Date.prototype.getTime()

The getTime() method of Date instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

\n

Try it

\n

Syntax

\n
\n

js

\n
getTime()\n
\n

Parameters

\n

None.

Return value

\n

A number representing the timestamp, in milliseconds, of this date. Returns NaN if the date is invalid.

Description

\n

Date objects are fundamentally represented by a timestamp, and this method allows you to retrieve the timestamp. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.

Reduced time precision

\n
\n

To offer protection against timing attacks and fingerprinting, the precision of new Date().getTime() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 2ms. You can also enable privacy.resistFingerprinting, in which case the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger.

\n

js

\n
// reduced time precision (2ms) in Firefox 60\nnew Date().getTime();\n// 1519211809934\n// 1519211810362\n// 1519211811670\n// …\n\n// reduced time precision with `privacy.resistFingerprinting` enabled\nnew Date().getTime();\n// 1519129853500\n// 1519129858900\n// 1519129864400\n// …\n
\n
\n

Examples

\n

Using getTime() for copying dates

\n
\n

Constructing a date object with the identical time value.

\n

js

\n
// Since month is zero based, birthday will be January 10, 1995\nconst birthday = new Date(1994, 12, 10);\nconst copy = new Date();\ncopy.setTime(birthday.getTime());\n
\n
\n

Measuring execution time

\n
\n

Subtracting two subsequent getTime() calls on newly generated Date objects, give the time span between these two calls. This can be used to calculate the executing time of some operations. See also Date.now() to prevent instantiating unnecessary Date objects.

\n

js

\n
let end, start;\n\nstart = new Date();\nfor (let i = 0; i < 1000; i++) {\n  Math.sqrt(i);\n}\nend = new Date();\n\nconsole.log(`Operation took ${end.getTime() - start.getTime()} msec`);\n
\n

Note: In browsers that support the Web Performance API's high-resolution time feature, Performance.now() can provide more reliable and precise measurements of elapsed time than Date.now().

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.gettime
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getTime11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime\n

\n
\n", + "global_objects/date/settime": "

Date.prototype.setTime()

The setTime() method of Date instances changes the timestamp for this date, which is the number of milliseconds since the epoch, defined as the midnight at the beginning of January 1, 1970, UTC.

\n

Try it

\n

Syntax

\n
\n

js

\n
setTime(timeValue)\n
\n

Parameters

\n
timeValue

An integer representing the new timestamp — the number of milliseconds since the midnight at the beginning of January 1, 1970, UTC.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If timeValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Examples

\n

Using setTime()

\n
\n

js

\n
const theBigDay = new Date(\"1999-07-01\");\nconst sameAsBigDay = new Date();\nsameAsBigDay.setTime(theBigDay.getTime());\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.settime
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setTime11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime\n

\n
\n", + "global_objects/date/valueof": "

Date.prototype.valueOf()

The valueOf() method of Date instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

A number representing the timestamp, in milliseconds, of this date. Returns NaN if the date is invalid.

Description

\n
\n

The valueOf() method is part of the type coercion protocol. Because Date has a [@@toPrimitive]() method, that method always takes priority over valueOf() when a Date object is implicitly coerced to a number. However, Date.prototype[@@toPrimitive]() still calls this.valueOf() internally.

The Date object overrides the valueOf() method of Object. Date.prototype.valueOf() returns the timestamp of the date, which is functionally equivalent to the Date.prototype.getTime() method.

\n

Examples

\n

Using valueOf()

\n
\n

js

\n
const d = new Date(0); // 1970-01-01T00:00:00.000Z\nconsole.log(d.valueOf()); // 0\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf\n

\n
\n", + "global_objects/date/@@toprimitive": "

Date.prototype[@@toPrimitive]()

The [@@toPrimitive]() method of Date instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.

\n

Try it

\n

Syntax

\n
\n

js

\n
date[Symbol.toPrimitive](hint)\n
\n

Parameters

\n
hint

A string representing the type of the primitive value to return. The following values are valid:

  • \n\"string\" or \"default\": The method should return a string.
  • \n\"number\": The method should return a number.

Return value

\n
\n

If hint is \"string\" or \"default\", this method returns a string by coercing the this value to a string (first trying toString() then trying valueOf()).

If hint is \"number\", this method returns a number by coercing the this value to a number (first trying valueOf() then trying toString()).

\n

Exceptions

\n
TypeError

Thrown if the hint argument is not one of the three valid values.

Description

\n
\n

The [@@toPrimitive]() method is part of the type coercion protocol. JavaScript always calls the [@@toPrimitive]() method in priority to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

The [@@toPrimitive]() method of the Date object returns a primitive value by either invoking this.valueOf() and returning a number, or invoking this.toString() and returning a string. It exists to override the default primitive coercion process to return a string instead of a number, because primitive coercion, by default, calls valueOf() before toString(). With the custom [@@toPrimitive](), new Date(0) + 1 returns \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1\" (a string) instead of 1 (a number).

\n

Examples

\n

Using [@@toPrimitive]()

\n
\n

js

\n
const d = new Date(0); // 1970-01-01T00:00:00.000Z\n\nd[Symbol.toPrimitive](\"string\"); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nd[Symbol.toPrimitive](\"number\"); // 0\nd[Symbol.toPrimitive](\"default\"); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype-@@toprimitive
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@toPrimitive471544No341047474434105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive\n

\n
\n", + "global_objects/date/now": "

Date.now()

The Date.now() static method returns the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

\n

Try it

\n

Syntax

\n
\n

js

\n
Date.now()\n
\n

Parameters

\n

None.

Return value

\n

A number representing the timestamp, in milliseconds, of the current time.

Description

\n

Reduced time precision

\n
\n

To offer protection against timing attacks and fingerprinting, the precision of Date.now() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 2ms. You can also enable privacy.resistFingerprinting, in which case the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger.

\n

js

\n
// reduced time precision (2ms) in Firefox 60\nDate.now();\n// 1519211809934\n// 1519211810362\n// 1519211811670\n// …\n\n// reduced time precision with `privacy.resistFingerprinting` enabled\nDate.now();\n// 1519129853500\n// 1519129858900\n// 1519129864400\n// …\n
\n
\n

Examples

\n

Measuring time elapsed

\n
\n

You can use Date.now() to get the current time in milliseconds, then subtract a previous time to find out how much time elapsed between the two calls.

\n

js

\n
const start = Date.now();\ndoSomeLongRunningProcess();\nconsole.log(`Time elapsed: ${Date.now() - start} ms`);\n
\n

For more complex scenarios, you may want to use the performance API instead.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.now
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
now1121910.544.41841441.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now\n

\n
\n", + "global_objects/date/parse": "

Date.parse()

\n

The Date.parse() static method parses a string representation of a date, and returns the date's timestamp.

Only the date time string format is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Date.parse(dateString)\n
\n

Parameters

\n
dateString

A string in the date time string format. See the linked reference for caveats on using different formats.

Return value

\n

A number representing the timestamp of the given date. If dateString fails to be parsed as a valid date, NaN is returned.

Description

\n
\n

This function is useful for setting date values based on string values, for example in conjunction with the setTime() method.

Because parse() is a static method of Date, you always use it as Date.parse(), rather than as a method of a Date object you created.

\n

Examples

\n

Using Date.parse()

\n
\n

The following calls all return 1546300800000. The first will imply UTC time because it's date-only, and the others explicitly specify the UTC timezone.

\n

js

\n
Date.parse(\"2019-01-01\");\nDate.parse(\"2019-01-01T00:00:00.000Z\");\nDate.parse(\"2019-01-01T00:00:00.000+00:00\");\n
\n

The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system, because it has both date and time.

\n

js

\n
Date.parse(\"2019-01-01T00:00:00\");\n
\n
\n

Non-standard date strings

\n
\n

Note: This section contains implementation-specific behavior that can be inconsistent across implementations.

Implementations usually default to the local time zone when the date string is non-standard. For consistency, we will assume that the code uses the UTC timezone.

\n

js

\n
Date.parse(\"Jan 1, 1970\"); // 0 in all implementations\n\nDate.parse(\"Thu, 01 Jan 1970 00:00:00\"); // 0 in all implementations\n\nDate.parse(\"1970,1,1\"); // 0 in Chrome and Firefox, NaN in Safari\n\nDate.parse(\"02 01 1970\");\n// 2678400000 in Chrome and Firefox (Sun Feb 01 1970 00:00:00 GMT+0000);\n// NaN in Safari\n\n// With explicit timezone\nDate.parse(\"Thu, 01 Jan 1970 00:00:00 GMT+0300\");\n// -10800000 in all implementations in all timezones\n\n// Single number\nDate.parse(\"0\");\n// 946684800000 in Chrome (Sat Jan 01 2000 00:00:00 GMT+0000);\n// NaN in Firefox;\n// -62167219200000 in Safari (Sat Jan 01 0000 00:00:00 GMT+0000)\n\n// Two-digit number that may be a month\nDate.parse(\"28\"); // NaN in all implementations\n\n// Two-digit year\nDate.parse(\"70/01/01\"); // 0 in all implementations\n\n// Out-of-bounds date components\nDate.parse(\"2014-25-23\"); // NaN in all implementations\nDate.parse(\"Mar 32, 2014\"); // NaN in all implementations\nDate.parse(\"2014/25/23\"); // NaN in all implementations\n\nDate.parse(\"2014-02-30\");\n// NaN in Safari and Firefox;\n// 1393718400000 in Chrome (Sun Mar 02 2014 00:00:00 GMT+0000)\nDate.parse(\"02/30/2014\"); // 1393718400000 in all implementations\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.parse
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
parse11213314.418410.111.01.00.10.0
iso_86016124965.1≤3718410.151.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse\n

\n
\n", + "global_objects/date/utc": "

Date.UTC()

The Date.UTC() static method accepts parameters representing the date and time components similar to the Date constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

\n

Try it

\n

Syntax

\n
\n

js

\n
Date.UTC(year)\nDate.UTC(year, monthIndex)\nDate.UTC(year, monthIndex, day)\nDate.UTC(year, monthIndex, day, hour)\nDate.UTC(year, monthIndex, day, hour, minute)\nDate.UTC(year, monthIndex, day, hour, minute, second)\nDate.UTC(year, monthIndex, day, hour, minute, second, millisecond)\n
\n

Parameters

\n
year

Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year. See the example.

\nmonthIndex Optional\n

Integer value representing the month, beginning with 0 for January to 11 for December. Defaults to 0.

\nday Optional\n

Integer value representing the day of the month. Defaults to 1.

\nhours Optional\n

Integer value between 0 and 23 representing the hour of the day. Defaults to 0.

\nminutes Optional\n

Integer value representing the minute segment of a time. Defaults to 0.

\nseconds Optional\n

Integer value representing the second segment of a time. Defaults to 0.

\nmilliseconds Optional\n

Integer value representing the millisecond segment of a time. Defaults to 0.

Return value

\n

A number representing the timestamp of the given date. Returns NaN if the date is invalid.

Description

\n
\n

Years between 0 and 99 are converted to a year in the 20th century (1900 + year). For example, 95 is converted to the year 1995.

The UTC() method differs from the Date() constructor in three ways:

  1. \nDate.UTC() uses universal time instead of the local time.
  2. \nDate.UTC() returns a time value as a number instead of creating a Date object.
  3. When passed a single number, Date.UTC() interprets it as a year instead of a timestamp.

If a parameter is outside of the expected range, the UTC() method updates the other parameters to accommodate the value. For example, if 15 is used for monthIndex, the year will be incremented by 1 (year + 1) and 3 will be used for the month.

Because UTC() is a static method of Date, you always use it as Date.UTC(), rather than as a method of a Date object you created.

\n

Examples

\n

Using Date.UTC()

\n
\n

The following statement creates a Date object with the arguments treated as UTC instead of local:

\n

js

\n
const utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));\n
\n
\n

Behavior of Date.UTC() with one argument

\n
\n

Date.UTC() when passed one argument used to have inconsistent behavior, because implementations only kept the behavior consistent with the Date() constructor, which does not interpret a single argument as the year number. Implementations are now required to treat omitted monthIndex as 0, instead of coercing it to NaN.

\n

js

\n
Date.UTC(2017); // 1483228800000\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.utc
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
UTC11213314.418410.111.01.00.10.0
optional_monthIndex577954No441257575443127.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC\n

\n
\n", + "global_objects/date/date": "

Date() constructor

The Date() constructor creates Date objects. When called as a function, it returns a string representing the current time.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Date()\nnew Date(value)\nnew Date(dateString)\nnew Date(dateObject)\n\nnew Date(year, monthIndex)\nnew Date(year, monthIndex, day)\nnew Date(year, monthIndex, day, hours)\nnew Date(year, monthIndex, day, hours, minutes)\nnew Date(year, monthIndex, day, hours, minutes, seconds)\nnew Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)\n\nDate()\n
\n

Note: Date() can be called with or without new, but with different effects. See Return value.

\n

Parameters

\n
\n

There are five basic forms for the Date() constructor:

No parameters

When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation. The returned date's timestamp is the same as the number returned by Date.now().

Time value or timestamp number

value

An integer value representing the timestamp (the number of milliseconds since midnight at the beginning of January 1, 1970, UTC — a.k.a. the epoch).

Date string

dateString

A string value representing a date, parsed and interpreted using the same algorithm implemented by Date.parse(). See date time string format for caveats on using different formats.

Date object

dateObject

An existing Date object. This effectively makes a copy of the existing Date object with the same date and time. This is equivalent to new Date(dateObject.valueOf()), except the valueOf() method is not called.

When one parameter is passed to the Date() constructor, Date instances are specially treated. All other values are converted to primitives. If the result is a string, it will be parsed as a date string. Otherwise, the resulting primitive is further coerced to a number and treated as a timestamp.

Individual date and time component values

Given at least a year and month, this form of Date() returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (1 for day and 0 for every other component). The parameter values are all evaluated against the local time zone, rather than UTC. Date.UTC() accepts similar parameters but interprets the components as UTC and returns a timestamp.

If any parameter overflows its defined bounds, it \"carries over\". For example, if a monthIndex greater than 11 is passed in, those months will cause the year to increment; if a minutes greater than 59 is passed in, hours will increment accordingly, etc. Therefore, new Date(1990, 12, 1) will return January 1st, 1991; new Date(2020, 5, 19, 25, 65) will return 2:05 A.M. June 20th, 2020.

Similarly, if any parameter underflows, it \"borrows\" from the higher positions. For example, new Date(2020, 5, 0) will return May 31st, 2020.

year

Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year. See the example.

monthIndex

Integer value representing the month, beginning with 0 for January to 11 for December.

\nday Optional\n

Integer value representing the day of the month. Defaults to 1.

\nhours Optional\n

Integer value between 0 and 23 representing the hour of the day. Defaults to 0.

\nminutes Optional\n

Integer value representing the minute segment of a time. Defaults to 0.

\nseconds Optional\n

Integer value representing the second segment of a time. Defaults to 0.

\nmilliseconds Optional\n

Integer value representing the millisecond segment of a time. Defaults to 0.

\n

Return value

\n
\n

Calling new Date() (the Date() constructor) returns a Date object. If called with an invalid date string, or if the date to be constructed will have a timestamp less than -8,640,000,000,000,000 or greater than 8,640,000,000,000,000 milliseconds, it returns an invalid date (a Date object whose toString() method returns \"Invalid Date\" and valueOf() method returns NaN).

Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does. Any arguments given in a Date() function call (without the new keyword) are ignored; regardless of whether it's called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time.

\n

Examples

\n

Several ways to create a Date object

\n
\n

The following examples show several ways to create JavaScript dates:

\n

js

\n
const today = new Date();\nconst birthday = new Date(\"December 17, 1995 03:24:00\"); // DISCOURAGED: may not work in all runtimes\nconst birthday = new Date(\"1995-12-17T03:24:00\"); // This is standardized and will work reliably\nconst birthday = new Date(1995, 11, 17); // the month is 0-indexed\nconst birthday = new Date(1995, 11, 17, 3, 24, 0);\nconst birthday = new Date(628021800000); // passing epoch timestamp\n
\n
\n

Passing a non-Date, non-string, non-number value

\n
\n

If the Date() constructor is called with one parameter which is not a Date instance, it will be coerced to a primitive and then checked whether it's a string. For example, new Date(undefined) is different from new Date():

\n

js

\n
console.log(new Date(undefined)); // Invalid Date\n
\n

This is because undefined is already a primitive but not a string, so it will be coerced to a number, which is NaN and therefore not a valid timestamp. On the other hand, null will be coerced to 0.

\n

js

\n
console.log(new Date(null)); // 1970-01-01T00:00:00.000Z\n
\n

Arrays would be coerced to a string via Array.prototype.toString(), which joins the elements with commas. However, the resulting string for any array with more than one element is not a valid ISO 8601 date string, so its parsing behavior would be implementation-defined. Date()

\n

js

\n
console.log(new Date([\"2020-06-19\", \"17:13\"]));\n// 2020-06-19T17:13:00.000Z in Chrome, since it recognizes \"2020-06-19,17:13\"\n// \"Invalid Date\" in Firefox\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Date11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date\n

\n
\n", + "global_objects/date/gettimezoneoffset": "

Date.prototype.getTimezoneOffset()

The getTimezoneOffset() method of Date instances returns the difference, in minutes, between this date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.

\n

Try it

\n

Syntax

\n
\n

js

\n
getTimezoneOffset()\n
\n

Parameters

\n

None.

Return value

\n

A number representing the difference, in minutes, between the date as evaluated in the UTC time zone and as evaluated in the local time zone. The actual local time algorithm is implementation-defined, and the return value is allowed to be zero in runtimes without appropriate data. Returns NaN if the date is invalid.

Description

\n

date.getTimezoneOffset() returns the difference, in minutes, between date as evaluated in the UTC time zone and as evaluated in the local time zone — that is, the time zone of the host system in which the browser is being used (if the code is run from the Web in a browser), or otherwise the host system of whatever JavaScript runtime (for example, a Node.js environment) the code is executed in.

Negative values and positive values

\n
\n

The number of minutes returned by getTimezoneOffset() is positive if the local time zone is behind UTC, and negative if the local time zone is ahead of UTC. For example, for UTC+10, -600 will be returned.

Current time zone Return value
UTC-8 480
UTC 0
UTC+3 -180
\n

Varied results in Daylight Saving Time (DST) regions

\n
\n

In a region that annually shifts in and out of Daylight Saving Time (DST), as date varies, the number of minutes returned by calling getTimezoneOffset() can be non-uniform.

Note: getTimezoneOffset()'s behavior will never differ based on the time when the code is run — its behavior is always consistent when running in the same region. Only the value of date affects the result.

In most implementations, the IANA time zone database (tzdata) is used to precisely determine the offset of the local timezone at the moment of the date. However, if such information is unavailable, an implementation may return zero.

\n

Examples

\n

Using getTimezoneOffset()

\n
\n

js

\n
// Create a Date instance for the current time\nconst currentLocalDate = new Date();\n// Create a Date instance for 03:24 GMT-0200 on May 1st in 2016\nconst laborDay2016at0324GMTminus2 = new Date(\"2016-05-01T03:24:00-02:00\");\ncurrentLocalDate.getTimezoneOffset() ===\n  laborDay2016at0324GMTminus2.getTimezoneOffset();\n// true, always, in any timezone that doesn't annually shift in and out of DST\n// false, sometimes, in any timezone that annually shifts in and out of DST\n
\n

getTimezoneOffset() and DST

\n
\n

In regions that use DST, the return value may change based on the time of the year date is in. Below is the output in a runtime in New York, where the timezone is UTC-05:00.

\n

js

\n
const nyOffsetSummer = new Date(\"2022-02-01\").getTimezoneOffset(); // 300\nconst nyOffsetWinter = new Date(\"2022-08-01\").getTimezoneOffset(); // 240\n
\n
\n

getTimezoneOffset() and historical data

\n
\n

Due to historical reasons, the timezone a region is in can be constantly changing, even disregarding DST. For example, below is the output in a runtime in Shanghai, where the timezone is UTC+08:00.

\n

js

\n
const shModernOffset = new Date(\"2022-01-27\").getTimezoneOffset(); // -480\nconst shHistoricalOffset = new Date(\"1943-01-27\").getTimezoneOffset(); // -540\n
\n

This is because during the Sino-Japanese War when Shanghai was under Japanese control, the timezone was changed to UTC+09:00 to align with Japan's (in effect, it was a \"year-round DST\"), and this was recorded in the IANA database.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.gettimezoneoffset
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getTimezoneOffset11215314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset\n

\n
\n", + "global_objects/date/getfullyear": "

Date.prototype.getFullYear()

\n

The getFullYear() method of Date instances returns the year for this date according to local time.

Use this method instead of the getYear() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
getFullYear()\n
\n

Parameters

\n

None.

Return value

\n

An integer representing the year for the given date according to local time. Returns NaN if the date is invalid.

Description

\n

Unlike getYear(), the value returned by getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

Examples

\n

Using getFullYear()

\n
\n

The fullYear variable has value 1995, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst fullYear = xmas95.getFullYear();\n\nconsole.log(fullYear); // 1995\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getfullyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getFullYear11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear\n

\n
\n", + "global_objects/date/setfullyear": "

Date.prototype.setFullYear()

The setFullYear() method of Date instances changes the year, month, and/or day of month for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setFullYear(yearValue)\nsetFullYear(yearValue, monthValue)\nsetFullYear(yearValue, monthValue, dateValue)\n
\n

Parameters

\n
yearValue

An integer representing the year. For example, 1995.

\nmonthValue Optional\n

An integer representing the month: 0 for January, 1 for February, and so on.

\ndateValue Optional\n

An integer between 1 and 31 representing the day of the month. If you specify dateValue, you must also specify monthValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the monthValue and dateValue parameters, the same values as what are returned by getMonth() and getDate() are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the Date object are updated accordingly. For example, if you specify 15 for monthValue, the year is incremented by 1 (yearValue + 1), and 3 is used for the month.

\n

Examples

\n

Using setFullYear()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setFullYear(1997);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setfullyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setFullYear11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear\n

\n
\n", + "global_objects/date/getutcfullyear": "

Date.prototype.getUTCFullYear()

The getUTCFullYear() method of Date instances returns the year for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCFullYear()\n
\n

Parameters

\n

None.

Return value

\n

An integer representing the year for the given date according to universal time. Returns NaN if the date is invalid.

Description

\n

Unlike getYear(), the value returned by getUTCFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

Examples

\n

Using getUTCFullYear()

\n
\n

The following example assigns the four-digit value of the current year to the variable year.

\n

js

\n
const today = new Date();\nconst year = today.getUTCFullYear();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcfullyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCFullYear11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear\n

\n
\n", + "global_objects/date/setutcfullyear": "

Date.prototype.setUTCFullYear()

The setUTCFullYear() method of Date instances changes the year for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCFullYear(yearValue)\nsetUTCFullYear(yearValue, monthValue)\nsetUTCFullYear(yearValue, monthValue, dateValue)\n
\n

Parameters

\n
yearValue

An integer representing the year. For example, 1995.

\nmonthValue Optional\n

An integer representing the month: 0 for January, 1 for February, and so on.

\ndateValue Optional\n

An integer between 1 and 31 representing the day of the month. If you specify dateValue, you must also specify monthValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the monthValue and dateValue parameters, the values returned from the getUTCMonth() and getUTCDate() methods are used.

If a parameter you specify is outside of the expected range, setUTCFullYear() attempts to update the other parameters and the date information in the Date object accordingly. For example, if you specify 15 for monthValue, the year is incremented by 1 (yearValue + 1), and 3 is used for the month.

\n

Examples

\n

Using setUTCFullYear()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCFullYear(1997);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcfullyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCFullYear11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear\n

\n
\n", + "global_objects/date/getmonth": "

Date.prototype.getMonth()

The getMonth() method of Date instances returns the month for this date according to local time, as a zero-based value (where zero indicates the first month of the year).

\n

Try it

\n

Syntax

\n
\n

js

\n
getMonth()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 11, representing the month for the given date according to local time: 0 for January, 1 for February, and so on. Returns NaN if the date is invalid.

Description

\n
\n

The return value of getMonth() is zero-based, which is useful for indexing into arrays of months, for example:

\n

js

\n
const valentines = new Date(\"1995-02-14\");\nconst month = valentines.getMonth();\nconst monthNames = [\"January\", \"February\", \"March\" /* , … */];\n\nconsole.log(monthNames[month]); // \"February\"\n
\n

However, for the purpose of internationalization, you should prefer using Intl.DateTimeFormat with the options parameter instead.

\n

js

\n
const options = { month: \"long\" };\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(valentines));\n// \"February\"\nconsole.log(new Intl.DateTimeFormat(\"de-DE\", options).format(valentines));\n// \"Februar\"\n
\n
\n

Examples

\n

Using getMonth()

\n
\n

The month variable has value 11, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst month = xmas95.getMonth();\n\nconsole.log(month); // 11\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getmonth
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getMonth11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth\n

\n
\n", + "global_objects/date/setmonth": "

Date.prototype.setMonth()

The setMonth() method of Date instances changes the month and/or day of the month for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setMonth(monthValue)\nsetMonth(monthValue, dateValue)\n
\n

Parameters

\n
monthValue

An integer representing the month: 0 for January, 1 for February, and so on.

\ndateValue Optional\n

An integer from 1 to 31 representing the day of the month.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the dateValue parameter, the same value as what is returned by getDate() is used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the Date object are updated accordingly. For example, if you specify 15 for monthValue, the year is incremented by 1, and 3 is used for month.

The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

\n

Examples

\n

Using setMonth()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setMonth(6);\n\n//Watch out for end of month transitions\nconst endOfMonth = new Date(2016, 7, 31);\nendOfMonth.setMonth(1);\nconsole.log(endOfMonth); //Wed Mar 02 2016 00:00:00\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setmonth
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setMonth11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth\n

\n
\n", + "global_objects/date/getutcmonth": "

Date.prototype.getUTCMonth()

The getUTCMonth() method of Date instances returns the month for this date according to universal time, as a zero-based value (where zero indicates the first month of the year).

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCMonth()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 11, representing the month for the given date according to universal time: 0 for January, 1 for February, and so on. Returns NaN if the date is invalid.

Examples

\n

Using getUTCMonth()

\n
\n

The following example assigns the month portion of the current date to the variable month.

\n

js

\n
const today = new Date();\nconst month = today.getUTCMonth();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcmonth
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCMonth11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth\n

\n
\n", + "global_objects/date/setutcmonth": "

Date.prototype.setUTCMonth()

The setUTCMonth() method of Date instances changes the month and/or day of the month for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCMonth(monthValue)\nsetUTCMonth(monthValue, dateValue)\n
\n

Parameters

\n
monthValue

An integer representing the month: 0 for January, 1 for February, and so on.

\ndateValue Optional\n

An integer from 1 to 31 representing the day of the month.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the dateValue parameter, the value returned from the getUTCDate() method is used.

If a parameter you specify is outside of the expected range, setUTCMonth() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.

\n

Examples

\n

Using setUTCMonth()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCMonth(11);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcmonth
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCMonth11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth\n

\n
\n", + "global_objects/date/getdate": "

Date.prototype.getDate()

The getDate() method of Date instances returns the day of the month for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getDate()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 1 and 31, representing the day of the month for the given date according to local time. Returns NaN if the date is invalid.

Examples

\n

Using getDate()

\n
\n

The day variable has value 25, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst day = xmas95.getDate();\n\nconsole.log(day); // 25\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getdate
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getDate11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate\n

\n
\n", + "global_objects/date/setdate": "

Date.prototype.setDate()

The setDate() method of Date instances changes the day of the month for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setDate(dateValue)\n
\n

Parameters

\n
dateValue

An integer representing the day of the month.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If dateValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n

If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if the Date object holds June 1st, a dateValue of 40 changes the date to July 10th, while a dateValue of 0 changes the date to the last day of the previous month, May 31st.

Examples

\n

Using setDate()

\n
\n

js

\n
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed)\nconst theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962)\nconst theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962)\nconst theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962)\nconst theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962)\nconst theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962)\nconst theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setdate
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setDate11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate\n

\n
\n", + "global_objects/date/getutcdate": "

Date.prototype.getUTCDate()

The getUTCDate() method of Date instances returns the day of the month for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCDate()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 1 and 31, representing day of month for the given date according to universal time. Returns NaN if the date is invalid.

Examples

\n

Using getUTCDate()

\n
\n

The following example assigns the day of month of the current date to the variable dayOfMonth.

\n

js

\n
const today = new Date();\nconst dayOfMonth = today.getUTCDate();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcdate
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCDate11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate\n

\n
\n", + "global_objects/date/setutcdate": "

Date.prototype.setUTCDate()

The setUTCDate() method of Date instances changes the day of the month for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCDate(dateValue)\n
\n

Parameters

\n
dateValue

An integer from 1 to 31 representing the day of the month.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If dateValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If the dateValue is outside of the range of date values for the month, setDate() will update the Date object accordingly.

For example, if 0 is provided for dateValue, the date will be set to the last day of the previous month. If you use 40 for dateValue, and the month stored in the Date object is June, the day will be changed to 10 and the month will be incremented to July.

If a negative number is provided for dateValue, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.

\n

Examples

\n

Using setUTCDate()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCDate(20);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcdate
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCDate11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate\n

\n
\n", + "global_objects/date/gethours": "

Date.prototype.getHours()

The getHours() method of Date instances returns the hours for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getHours()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 23, representing the hours for the given date according to local time. Returns NaN if the date is invalid.

Examples

\n

Using getHours()

\n
\n

The hours variable has value 23, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst hours = xmas95.getHours();\n\nconsole.log(hours); // 23\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.gethours
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getHours11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours\n

\n
\n", + "global_objects/date/sethours": "

Date.prototype.setHours()

The setHours() method of Date instances changes the hours, minutes, seconds, and/or milliseconds for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setHours(hoursValue)\nsetHours(hoursValue, minutesValue)\nsetHours(hoursValue, minutesValue, secondsValue)\nsetHours(hoursValue, minutesValue, secondsValue, msValue)\n
\n

Parameters

\n
hoursValue

An integer between 0 and 23 representing the hours.

\nminutesValue Optional\n

An integer between 0 and 59 representing the minutes.

\nsecondsValue Optional\n

An integer between 0 and 59 representing the seconds. If you specify secondsValue, you must also specify minutesValue.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds. If you specify msValue, you must also specify minutesValue and secondsValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the minutesValue, secondsValue, and msValue parameters, the same values as what are returned by getMinutes(), getSeconds(), and getMilliseconds() are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the Date object are updated accordingly. For example, if you specify 100 for secondsValue, the minutes are incremented by 1 (minutesValue + 1), and 40 is used for seconds.

\n

Examples

\n

Using setHours()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setHours(7);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.sethours
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setHours11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours\n

\n
\n", + "global_objects/date/getutchours": "

Date.prototype.getUTCHours()

The getUTCHours() method of Date instances returns the hours for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCHours()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 23, representing the hours for the given date according to universal time. Returns NaN if the date is invalid.

Examples

\n

Using getUTCHours()

\n
\n

The following example assigns the hours portion of the current time to the variable hours.

\n

js

\n
const today = new Date();\nconst hours = today.getUTCHours();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutchours
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCHours11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours\n

\n
\n", + "global_objects/date/setutchours": "

Date.prototype.setUTCHours()

The setUTCHours() method of Date instances changes the hours, minutes, seconds, and/or milliseconds for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCHours(hoursValue)\nsetUTCHours(hoursValue, minutesValue)\nsetUTCHours(hoursValue, minutesValue, secondsValue)\nsetUTCHours(hoursValue, minutesValue, secondsValue, msValue)\n
\n

Parameters

\n
hoursValue

An integer between 0 and 23 representing the hours.

\nminutesValue Optional\n

An integer between 0 and 59 representing the minutes.

\nsecondsValue Optional\n

An integer between 0 and 59 representing the seconds. If you specify secondsValue, you must also specify minutesValue.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds. If you specify msValue, you must also specify minutesValue and secondsValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the minutesValue, secondsValue, and msValue parameters, the values returned from the getUTCMinutes(), getUTCSeconds(), and getUTCMilliseconds() methods are used.

If a parameter you specify is outside of the expected range, setUTCHours() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes will be incremented by 1 (minutesValue + 1), and 40 will be used for seconds.

\n

Examples

\n

Using setUTCHours()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCHours(8);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutchours
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCHours11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours\n

\n
\n", + "global_objects/date/getminutes": "

Date.prototype.getMinutes()

The getMinutes() method of Date instances returns the minutes for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getMinutes()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 59, representing the minutes for the given date according to local time. Returns NaN if the date is invalid.

Examples

\n

Using getMinutes()

\n
\n

The minutes variable has value 15, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst minutes = xmas95.getMinutes();\n\nconsole.log(minutes); // 15\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getminutes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getMinutes11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes\n

\n
\n", + "global_objects/date/setminutes": "

Date.prototype.setMinutes()

The setMinutes() method of Date instances changes the minutes for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setMinutes(minutesValue)\nsetMinutes(minutesValue, secondsValue)\nsetMinutes(minutesValue, secondsValue, msValue)\n
\n

Parameters

\n
minutesValue

An integer between 0 and 59 representing the minutes.

\nsecondsValue Optional\n

An integer between 0 and 59 representing the seconds. If you specify secondsValue, you must also specify minutesValue.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds. If you specify msValue, you must also specify minutesValue and secondsValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the secondsValue and msValue parameters, the same values as what are returned by getSeconds() and getMilliseconds() are used.

If a parameter you specify is outside of the expected range, other parameters and the date information in the Date object are updated accordingly. For example, if you specify 100 for secondsValue, the minutes is incremented by 1 (minutesValue + 1), and 40 is used for seconds.

\n

Examples

\n

Using setMinutes()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setMinutes(45);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setminutes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setMinutes11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes\n

\n
\n", + "global_objects/date/getutcminutes": "

Date.prototype.getUTCMinutes()

The getUTCMinutes() method of Date instances returns the minutes for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCMinutes()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 59, representing the minutes for the given date according to universal time. Returns NaN if the date is invalid.

Examples

\n

Using getUTCMinutes()

\n
\n

The following example assigns the minutes portion of the current time to the variable minutes.

\n

js

\n
const today = new Date();\nconst minutes = today.getUTCMinutes();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcminutes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCMinutes11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes\n

\n
\n", + "global_objects/date/setutcminutes": "

Date.prototype.setUTCMinutes()

The setUTCMinutes() method of Date instances changes the minutes for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCMinutes(minutesValue)\nsetUTCMinutes(minutesValue, secondsValue)\nsetUTCMinutes(minutesValue, secondsValue, msValue)\n
\n

Parameters

\n
minutesValue

An integer between 0 and 59 representing the minutes.

\nsecondsValue Optional\n

An integer between 0 and 59 representing the seconds. If you specify secondsValue, you must also specify minutesValue.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds. If you specify msValue, you must also specify minutesValue and secondsValue.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the secondsValue and msValue parameters, the values returned from getUTCSeconds() and getUTCMilliseconds() methods are used.

If a parameter you specify is outside of the expected range, setUTCMinutes() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes will be incremented by 1 (minutesValue + 1), and 40 will be used for seconds.

\n

Examples

\n

Using setUTCMinutes()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCMinutes(43);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcminutes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCMinutes11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes\n

\n
\n", + "global_objects/date/getseconds": "

Date.prototype.getSeconds()

The getSeconds() method of Date instances returns the seconds for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getSeconds()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 59, representing the seconds for the given date according to local time. Returns NaN if the date is invalid.

Examples

\n

Using getSeconds()

\n
\n

The seconds variable has value 30, based on the value of the Date object xmas95.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst seconds = xmas95.getSeconds();\n\nconsole.log(seconds); // 30\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getSeconds11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds\n

\n
\n", + "global_objects/date/setseconds": "

Date.prototype.setSeconds()

The setSeconds() method of Date instances changes the seconds and/or milliseconds for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setSeconds(secondsValue)\nsetSeconds(secondsValue, msValue)\n
\n

Parameters

\n
secondsValue

An integer between 0 and 59 representing the seconds.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the msValue parameter, the value returned from the getMilliseconds() method is used.

If a parameter you specify is outside of the expected range, setSeconds() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds.

\n

Examples

\n

Using setSeconds()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setSeconds(30);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setSeconds11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds\n

\n
\n", + "global_objects/date/getutcseconds": "

Date.prototype.getUTCSeconds()

The getUTCSeconds() method of Date instances returns the seconds in the specified date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCSeconds()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 59, representing the seconds for the given date according to universal time. Returns NaN if the date is invalid.

Examples

\n

Using getUTCSeconds()

\n
\n

The following example assigns the seconds portion of the current time to the variable seconds.

\n

js

\n
const today = new Date();\nconst seconds = today.getUTCSeconds();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCSeconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds\n

\n
\n", + "global_objects/date/setutcseconds": "

Date.prototype.setUTCSeconds()

The setUTCSeconds() method of Date instances changes the seconds and/or milliseconds for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCSeconds(secondsValue)\nsetUTCSeconds(secondsValue, msValue)\n
\n

Parameters

\n
secondsValue

An integer between 0 and 59 representing the seconds.

\nmsValue Optional\n

An integer between 0 and 999 representing the milliseconds.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If a parameter is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n
\n

If you do not specify the msValue parameter, the value returned from the getUTCMilliseconds() method is used.

If a parameter you specify is outside of the expected range, setUTCSeconds() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds.

\n

Examples

\n

Using setUTCSeconds()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCSeconds(20);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCSeconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds\n

\n
\n", + "global_objects/date/getmilliseconds": "

Date.prototype.getMilliseconds()

The getMilliseconds() method of Date instances returns the milliseconds for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getMilliseconds()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 999, representing the milliseconds for the given date according to local time. Returns NaN if the date is invalid.

Examples

\n

Using getMilliseconds()

\n
\n

The milliseconds variable has value 0, based on the value of the Date object xmas95, which doesn't specify the milliseconds component, so it defaults to 0.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst milliseconds = xmas95.getMilliseconds();\n\nconsole.log(milliseconds); // 0\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getmilliseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getMilliseconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds\n

\n
\n", + "global_objects/date/setmilliseconds": "

Date.prototype.setMilliseconds()

The setMilliseconds() method of Date instances changes the milliseconds for this date according to local time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setMilliseconds(millisecondsValue)\n
\n

Parameters

\n
millisecondsValue

An integer between 0 and 999 representing the milliseconds.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If millisecondsValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n

If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.

Examples

\n

Using setMilliseconds()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setMilliseconds(100);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setmilliseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setMilliseconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds\n

\n
\n", + "global_objects/date/getutcmilliseconds": "

Date.prototype.getUTCMilliseconds()

The getUTCMilliseconds() method of Date instances returns the milliseconds for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCMilliseconds()\n
\n

Parameters

\n

None.

Return value

\n
\n

An integer, between 0 and 999, representing the milliseconds for the given date according to universal time. Returns NaN if the date is invalid.

Not to be confused with the timestamp. To get the total milliseconds since the epoch, use the getTime() method.

\n

Examples

\n

Using getUTCMilliseconds()

\n
\n

The following example assigns the milliseconds portion of the current time to the variable milliseconds.

\n

js

\n
const today = new Date();\nconst milliseconds = today.getUTCMilliseconds();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcmilliseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCMilliseconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds\n

\n
\n", + "global_objects/date/setutcmilliseconds": "

Date.prototype.setUTCMilliseconds()

The setUTCMilliseconds() method of Date instances changes the milliseconds for this date according to universal time.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUTCMilliseconds(millisecondsValue)\n
\n

Parameters

\n
millisecondsValue

An integer between 0 and 999 representing the milliseconds.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If millisecondsValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n

If a parameter you specify is outside of the expected range, setUTCMilliseconds() attempts to update the date information in the Date object accordingly. For example, if you use 1100 for millisecondsValue, the seconds stored in the Date object will be incremented by 1, and 100 will be used for milliseconds.

Examples

\n

Using setUTCMilliseconds()

\n
\n

js

\n
const theBigDay = new Date();\ntheBigDay.setUTCMilliseconds(500);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setutcmilliseconds
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUTCMilliseconds11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds\n

\n
\n", + "global_objects/date/getday": "

Date.prototype.getDay()

The getDay() method of Date instances returns the day of the week for this date according to local time, where 0 represents Sunday. For the day of the month, see Date.prototype.getDate().

\n

Try it

\n

Syntax

\n
\n

js

\n
getDay()\n
\n

Parameters

\n

None.

Return value

\n

An integer, between 0 and 6, representing the day of the week for the given date according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Returns NaN if the date is invalid.

Description

\n
\n

The return value of getDay() is zero-based, which is useful for indexing into arrays of days, for example:

\n

js

\n
const valentines = new Date(\"1995-02-14\");\nconst day = valentines.getDay();\nconst dayNames = [\"Sunday\", \"Monday\", \"Tuesday\" /* , … */];\n\nconsole.log(dayNames[day]); // \"Monday\"\n
\n

However, for the purpose of internationalization, you should prefer using Intl.DateTimeFormat with the options parameter instead.

\n

js

\n
const options = { weekday: \"long\" };\nconsole.log(new Intl.DateTimeFormat(\"en-US\", options).format(valentines));\n// \"Monday\"\nconsole.log(new Intl.DateTimeFormat(\"de-DE\", options).format(valentines));\n// \"Montag\"\n
\n
\n

Examples

\n

Using getDay()

\n
\n

The weekday variable has value 1, based on the value of the Date object xmas95, because December 25, 1995 is a Monday.

\n

js

\n
const xmas95 = new Date(\"1995-12-25T23:15:30\");\nconst weekday = xmas95.getDay();\n\nconsole.log(weekday); // 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getday
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getDay11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay\n

\n
\n", + "global_objects/date/getutcday": "

Date.prototype.getUTCDay()

The getUTCDay() method of Date instances returns the day of the week for this date according to universal time, where 0 represents Sunday.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUTCDay()\n
\n

Parameters

\n

None.

Return value

\n

An integer corresponding to the day of the week for the given date according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Returns NaN if the date is invalid.

Examples

\n

Using getUTCDay()

\n
\n

The following example assigns the weekday portion of the current date to the variable weekday.

\n

js

\n
const today = new Date();\nconst weekday = today.getUTCDay();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getutcday
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUTCDay11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay\n

\n
\n", + "global_objects/date/getyear": "

Date.prototype.getYear()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The getYear() method of Date instances returns the year for this date according to local time. Because getYear() does not return full years (\"year 2000 problem\"), it is deprecated and has been replaced by the getFullYear() method.

\n
\n

Syntax

\n
\n

js

\n
getYear()\n
\n

Parameters

\n

None.

Return value

\n
\n

An integer representing the year for the given date according to local time, minus 1900. Returns NaN if the date is invalid.

This method essentially returns the value of getFullYear() minus 1900. You should use getFullYear() instead, so that the year is specified in full.

\n

Examples

\n

Years between 1900 and 1999

\n
\n

The second statement assigns the value 95 to the variable year.

\n

js

\n
const xmas = new Date(\"1995-12-25\");\nconst year = xmas.getYear(); // returns 95\n
\n
\n

Years above 1999

\n
\n

The second statement assigns the value 100 to the variable year.

\n

js

\n
const xmas = new Date(\"2000-12-25\");\nconst year = xmas.getYear(); // returns 100\n
\n
\n

Years below 1900

\n
\n

The second statement assigns the value -100 to the variable year.

\n

js

\n
const xmas = new Date(\"1800-12-25\");\nconst year = xmas.getYear(); // returns -100\n
\n
\n

Setting and getting a year between 1900 and 1999

\n
\n

The third statement assigns the value 95 to the variable year, representing the year 1995.

\n

js

\n
const xmas = new Date(\"2015-12-25\");\nxmas.setYear(95);\nconst year = xmas.getYear(); // returns 95\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.getyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getYear11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear\n

\n
\n", + "global_objects/date/setyear": "

Date.prototype.setYear()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The setYear() method of Date instances sets the year for a specified date according to local time.

However, the way the legacy setYear() method sets year values is different from how the preferred setFullYear() method sets year values — and in some cases, also different from how new Date() and Date.parse() set year values. Specifically, given two-digit numbers, such as 22 and 61:

Because of those differences in behavior, you should no longer use the legacy setYear() method, but should instead use the preferred setFullYear() method.

\n
\n

Syntax

\n
\n

js

\n
setYear(yearValue)\n
\n

Parameters

\n
yearValue

An integer.

Return value

\n

Changes the Date object in place, and returns its new timestamp. If yearValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

Description

\n

If yearValue is a number between 0 and 99 (inclusive), then the year for dateObj is set to 1900 + yearValue. Otherwise, the year for dateObj is set to yearValue.

Examples

\n

Using setYear()

\n
\n

The first two lines set the year to 1996. The third sets the year to 2000.

\n

js

\n
const theBigDay = new Date();\n\ntheBigDay.setYear(96);\ntheBigDay.setYear(1996);\ntheBigDay.setYear(2000);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.setyear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setYear11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setYear\n

\n
\n", + "global_objects/date/toisostring": "

Date.prototype.toISOString()

The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always UTC, as denoted by the suffix Z.

\n

Try it

\n

Syntax

\n
\n

js

\n
toISOString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the given date in the date time string format according to universal time. It's the same format as the one required to be recognized by Date.parse().

Exceptions

\n
RangeError

Thrown if the date is invalid or if it corresponds to a year that cannot be represented in the date string format.

Examples

\n

Using toISOString()

\n
\n

js

\n
const d = new Date(0);\n\nconsole.log(d.toISOString()); // \"1970-01-01T00:00:00.000Z\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.toisostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toISOString3121910.54≤37184113.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString\n

\n
\n", + "global_objects/date/tojson": "

Date.prototype.toJSON()

The toJSON() method of Date instances returns a string representing this date in the same ISO format as toISOString().

\n

Try it

\n

Syntax

\n
\n

js

\n
toJSON()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the given date in the date time string format according to universal time, or null when the date is invalid. For valid dates, the return value is the same as that of toISOString().

Description

\n
\n

The toJSON() method is automatically called by JSON.stringify() when a Date object is stringified. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor as the reviver of JSON.parse().

The method first attempts to convert its this value to a primitive by calling its [@@toPrimitive]() (with \"number\" as hint), valueOf(), and toString() methods, in that order. If the result is a non-finite number, null is returned. (This generally corresponds to an invalid date, whose valueOf() returns NaN.) Otherwise, if the converted primitive is not a number or is a finite number, the return value of this.toISOString() is returned.

Note that the method does not check whether the this value is a valid Date object. However, calling Date.prototype.toJSON() on non-Date objects fails unless the object's number primitive representation is NaN, or the object also has a toISOString() method.

\n

Examples

\n

Using toJSON()

\n
\n

js

\n
const jsonDate = new Date(0).toJSON(); // '1970-01-01T00:00:00.000Z'\nconst backToDate = new Date(jsonDate);\n\nconsole.log(jsonDate); // 1970-01-01T00:00:00.000Z\n
\n

Serialization round-tripping

\n
\n

When parsing JSON containing date strings, you can use the Date() constructor to revive them into the original date objects.

\n

js

\n
const fileData = {\n  author: \"Maria\",\n  title: \"Date.prototype.toJSON()\",\n  createdAt: new Date(2019, 3, 15),\n  updatedAt: new Date(2020, 6, 26),\n};\nconst response = JSON.stringify(fileData);\n\n// Imagine transmission through network\n\nconst data = JSON.parse(response, (key, value) => {\n  if (key === \"createdAt\" || key === \"updatedAt\") {\n    return new Date(value);\n  }\n  return value;\n});\n\nconsole.log(data);\n
\n

Note: The reviver of JSON.parse() must be specific to the payload shape you expect, because the serialization is lossy: it's not possible to distinguish between a string that represents a Date and a normal string.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.tojson
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toJSON3121810.54≤37184113.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON\n

\n
\n", + "global_objects/date/tostring": "

Date.prototype.toString()

The toString() method of Date instances returns a string representing this date interpreted in the local timezone.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the given date (see description for the format). Returns \"Invalid Date\" if the date is invalid.

Description

\n
\n

The toString() method is part of the type coercion protocol. Because Date has a [@@toPrimitive]() method, that method always takes priority over toString() when a Date object is implicitly coerced to a string. However, Date.prototype[@@toPrimitive]() still calls this.toString() internally.

The Date object overrides the toString() method of Object. Date.prototype.toString() returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in toDateString() and toTimeString() together, adding a space in between. For example: \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\".

Date.prototype.toString() must be called on Date instances. If the this value does not inherit from Date.prototype, a TypeError is thrown.

\n

Examples

\n

Using toString()

\n
\n

js

\n
const d = new Date(0);\nconsole.log(d.toString()); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString\n

\n
\n", + "global_objects/date/todatestring": "

Date.prototype.toDateString()

The toDateString() method of Date instances returns a string representing the date portion of this date interpreted in the local timezone.

\n

Try it

\n

Syntax

\n
\n

js

\n
toDateString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the date portion of the given date (see description for the format). Returns \"Invalid Date\" if the date is invalid.

Description

\n
\n

Date instances refer to a specific point in time. toDateString() interprets the date in the local timezone and formats the date part in English. It always uses the following format, separated by spaces:

  1. First three letters of the week day name
  2. First three letters of the month name
  3. Two-digit day of the month, padded on the left a zero if necessary
  4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign

For example: \"Thu Jan 01 1970\".

\n

Examples

\n

Using toDateString()

\n
\n

js

\n
const d = new Date(0);\n\nconsole.log(d.toString()); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nconsole.log(d.toDateString()); // \"Thu Jan 01 1970\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.todatestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toDateString11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString\n

\n
\n", + "global_objects/date/totimestring": "

Date.prototype.toTimeString()

The toTimeString() method of Date instances returns a string representing the time portion of this date interpreted in the local timezone.

\n

Try it

\n

Syntax

\n
\n

js

\n
toTimeString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the time portion of the given date (see description for the format). Returns \"Invalid Date\" if the date is invalid.

Description

\n
\n

Date instances refer to a specific point in time. toTimeString() interprets the date in the local timezone and formats the time part in English. It always uses the format of hh:mm:ss GMT±xxxx (TZ), where:

Format String Description
hh Hour, as two digits with leading zero if required
mm Minute, as two digits with leading zero if required
ss Seconds, as two digits with leading zero if required
±xxxx The local timezone's offset — two digits for hours and two digits for minutes (e.g. -0500, +0800)
TZ The timezone's name (e.g. PDT, PST)

For example: \"04:42:04 GMT+0000 (Coordinated Universal Time)\".

\n

Examples

\n

Using toTimeString()

\n
\n

js

\n
const d = new Date(0);\n\nconsole.log(d.toString()); // \"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)\"\nconsole.log(d.toTimeString()); // \"00:00:00 GMT+0000 (Coordinated Universal Time)\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.totimestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toTimeString11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString\n

\n
\n", + "global_objects/date/toutcstring": "

Date.prototype.toUTCString()

The toUTCString() method of Date instances returns a string representing this date in the RFC 7231 format, with negative years allowed. The timezone is always UTC. toGMTString() is an alias of this method.

\n

Try it

\n

Syntax

\n
\n

js

\n
toUTCString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the given date using the UTC time zone (see description for the format). Returns \"Invalid Date\" if the date is invalid.

Description

\n
\n

The value returned by toUTCString() is a string in the form Www, dd Mmm yyyy hh:mm:ss GMT, where:

Format String Description
Www Day of week, as three letters (e.g. Sun, Mon)
dd Day of month, as two digits with leading zero if required
Mmm Month, as three letters (e.g. Jan, Feb)
yyyy Year, as four or more digits with leading zeroes if required
hh Hour, as two digits with leading zero if required
mm Minute, as two digits with leading zero if required
ss Seconds, as two digits with leading zero if required
\n

Aliasing

\n
\n

JavaScript's Date API was inspired by Java's java.util.Date library (while the latter had become de facto legacy since Java 1.1 in 1997). In particular, the Java Date class had a method called toGMTString — which was poorly named, because the Greenwich Mean Time is not equivalent to the Coordinated Universal Time, while JavaScript dates always operate by UTC time. For web compatibility reasons, toGMTString remains as an alias to toUTCString, and they refer to the exact same function object. This means:

\n

js

\n
Date.prototype.toGMTString.name === \"toUTCString\";\n
\n
\n

Examples

\n

Using toUTCString()

\n
\n

js

\n
const d = new Date(0);\nconsole.log(d.toUTCString()); // 'Thu, 01 Jan 1970 00:00:00 GMT'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.toutcstring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toUTCString11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString\n

\n
\n", + "global_objects/date/tolocaledatestring": "

Date.prototype.toLocaleDateString()

\n

The toLocaleDateString() method of Date instances returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.

When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use its format() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleDateString()\ntoLocaleDateString(locales)\ntoLocaleDateString(locales, options)\n
\n

Parameters

\n
\n

The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.DateTimeFormat API, these parameters correspond exactly to the Intl.DateTimeFormat() constructor's parameters. Implementations without Intl.DateTimeFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.DateTimeFormat() constructor.

In implementations without Intl.DateTimeFormat support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.DateTimeFormat() constructor. The timeStyle option must be undefined, or a TypeError would be thrown. If weekday, year, month, and day are all undefined, then year, month, and day will be set to \"numeric\".

In implementations without Intl.DateTimeFormat support, this parameter is ignored.

See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them.

\n

Return value

\n
\n

A string representing the date portion of the given Date instance according to language-specific conventions.

In implementations with Intl.DateTimeFormat, this is equivalent to new Intl.DateTimeFormat(locales, options).format(date), where options has been normalized as described above.

\n

Examples

\n

Using toLocaleDateString()

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));\n\n// toLocaleDateString() without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(date.toLocaleDateString());\n// \"12/11/2012\" if run in en-US locale with time zone America/Los_Angeles\n
\n
\n

Checking for support for locales and options parameters

\n
\n

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleDateString() always uses the system's locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

\n

js

\n
function toLocaleDateStringSupportsLocales() {\n  return (\n    typeof Intl === \"object\" &&\n    !!Intl &&\n    typeof Intl.DateTimeFormat === \"function\"\n  );\n}\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized date formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// formats below assume the local time zone of the locale;\n// America/Los_Angeles for the US\n\n// US English uses month-day-year order\nconsole.log(date.toLocaleDateString(\"en-US\"));\n// \"12/20/2012\"\n\n// British English uses day-month-year order\nconsole.log(date.toLocaleDateString(\"en-GB\"));\n// \"20/12/2012\"\n\n// Korean uses year-month-day order\nconsole.log(date.toLocaleDateString(\"ko-KR\"));\n// \"2012. 12. 20.\"\n\n// Event for Persian, It's hard to manually convert date to Solar Hijri\nconsole.log(date.toLocaleDateString(\"fa-IR\"));\n// \"۱۳۹۱/۹/۳۰\"\n\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(date.toLocaleDateString(\"ar-EG\"));\n// \"٢٠‏/١٢‏/٢٠١٢\"\n\n// for Japanese, applications may want to use the Japanese calendar,\n// where 2012 was the year 24 of the Heisei era\nconsole.log(date.toLocaleDateString(\"ja-JP-u-ca-japanese\"));\n// \"24/12/20\"\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(date.toLocaleDateString([\"ban\", \"id\"]));\n// \"20/12/2012\"\n
\n
\n

Using options

\n
\n

The results provided by toLocaleDateString() can be customized using the options argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// request a weekday along with a long date\nconst options = {\n  weekday: \"long\",\n  year: \"numeric\",\n  month: \"long\",\n  day: \"numeric\",\n};\nconsole.log(date.toLocaleDateString(\"de-DE\", options));\n// \"Donnerstag, 20. Dezember 2012\"\n\n// an application may want to use UTC and make that visible\noptions.timeZone = \"UTC\";\noptions.timeZoneName = \"short\";\nconsole.log(date.toLocaleDateString(\"en-US\", options));\n// \"Thursday, December 20, 2012, UTC\"\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.tolocaledatestring
ECMAScript Internationalization API Specification
# sup-date.prototype.tolocaledatestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleDateString11215.5514.418410.111.01.00.10.0
iana_time_zone_names241452No1574.425561471.51.80.12.0
locales2412291115104.4255614101.51.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options2412291115104.4255614101.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString\n

\n
\n", + "global_objects/date/tolocaletimestring": "

Date.prototype.toLocaleTimeString()

\n

The toLocaleTimeString() method of Date instances returns a string with a language-sensitive representation of the time portion of the date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.

When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use its format() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleTimeString()\ntoLocaleTimeString(locales)\ntoLocaleTimeString(locales, options)\n
\n

Parameters

\n
\n

The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.DateTimeFormat API, these parameters correspond exactly to the Intl.DateTimeFormat() constructor's parameters. Implementations without Intl.DateTimeFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.DateTimeFormat() constructor.

In implementations without Intl.DateTimeFormat support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.DateTimeFormat() constructor. If dayPeriod, hour, minute, second, and fractionalSecondDigits are all undefined, then hour, minute, second will be set to \"numeric\".

In implementations without Intl.DateTimeFormat support, this parameter is ignored.

See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them.

\n

Return value

\n
\n

A string representing the time portion of the given Date instance according to language-specific conventions.

In implementations with Intl.DateTimeFormat, this is equivalent to new Intl.DateTimeFormat(locales, options).format(date), where options has been normalized as described above.

\n

Examples

\n

Using toLocaleTimeString()

\n
\n

Basic use of this method without specifying a locale returns a formatted string in the default locale and with default options.

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));\n\n// toLocaleTimeString() without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(date.toLocaleTimeString());\n// \"7:00:00 PM\" if run in en-US locale with time zone America/Los_Angeles\n
\n
\n

Checking for support for locales and options parameters

\n
\n

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleTimeString() always uses the system's locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

\n

js

\n
function toLocaleTimeStringSupportsLocales() {\n  return (\n    typeof Intl === \"object\" &&\n    !!Intl &&\n    typeof Intl.DateTimeFormat === \"function\"\n  );\n}\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// formats below assume the local time zone of the locale;\n// America/Los_Angeles for the US\n\n// US English uses 12-hour time with AM/PM\nconsole.log(date.toLocaleTimeString(\"en-US\"));\n// \"7:00:00 PM\"\n\n// British English uses 24-hour time without AM/PM\nconsole.log(date.toLocaleTimeString(\"en-GB\"));\n// \"03:00:00\"\n\n// Korean uses 12-hour time with AM/PM\nconsole.log(date.toLocaleTimeString(\"ko-KR\"));\n// \"오후 12:00:00\"\n\n// Arabic in most Arabic speaking countries uses real Arabic digits\nconsole.log(date.toLocaleTimeString(\"ar-EG\"));\n// \"٧:٠٠:٠٠ م\"\n\n// when requesting a language that may not be supported, such as\n// Balinese, include a fallback language, in this case Indonesian\nconsole.log(date.toLocaleTimeString([\"ban\", \"id\"]));\n// \"11.00.00\"\n
\n
\n

Using options

\n
\n

The results provided by toLocaleTimeString() can be customized using the options argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// an application may want to use UTC and make that visible\nconst options = { timeZone: \"UTC\", timeZoneName: \"short\" };\nconsole.log(date.toLocaleTimeString(\"en-US\", options));\n// \"3:00:00 AM GMT\"\n\n// sometimes even the US needs 24-hour time\nconsole.log(date.toLocaleTimeString(\"en-US\", { hour12: false }));\n// \"19:00:00\"\n\n// show only hours and minutes, use options with the default locale - use an empty array\nconsole.log(\n  date.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" }),\n);\n// \"20:01\"\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.tolocaletimestring
ECMAScript Internationalization API Specification
# sup-date.prototype.tolocaletimestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleTimeString11215.5514.418410.111.01.00.10.0
iana_time_zone_names241452No1574.425561471.51.80.12.0
locales2412291115104.4255614101.51.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options2412291115104.4255614101.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString\n

\n
\n", + "global_objects/date/tolocalestring": "

Date.prototype.toLocaleString()

The toLocaleString() method of Date instances returns a string with a language-sensitive representation of this date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n
\n

Parameters

\n
\n

The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.DateTimeFormat API, these parameters correspond exactly to the Intl.DateTimeFormat() constructor's parameters. Implementations without Intl.DateTimeFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.DateTimeFormat() constructor.

In implementations without Intl.DateTimeFormat support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.DateTimeFormat() constructor. If weekday, year, month, day, dayPeriod, hour, minute, second, and fractionalSecondDigits are all undefined, then year, month, day, hour, minute, second will be set to \"numeric\".

In implementations without Intl.DateTimeFormat support, this parameter is ignored.

See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them.

\n

Return value

\n
\n

A string representing the given date according to language-specific conventions.

In implementations with Intl.DateTimeFormat, this is equivalent to new Intl.DateTimeFormat(locales, options).format(date).

Note: Most of the time, the formatting returned by toLocaleString() is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of toLocaleString() to static values.

\n

Examples

\n

Using toLocaleString()

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));\n\n// toLocaleString() without arguments depends on the\n// implementation, the default locale, and the default time zone\nconsole.log(date.toLocaleString());\n// \"12/11/2012, 7:00:00 PM\" if run in en-US locale with time zone America/Los_Angeles\n
\n
\n

Checking for support for locales and options parameters

\n
\n

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString() always uses the system's locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

\n

js

\n
function toLocaleStringSupportsLocales() {\n  return (\n    typeof Intl === \"object\" &&\n    !!Intl &&\n    typeof Intl.DateTimeFormat === \"function\"\n  );\n}\n
\n
\n

Using locales

\n
\n

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// Formats below assume the local time zone of the locale;\n// America/Los_Angeles for the US\n\n// US English uses month-day-year order and 12-hour time with AM/PM\nconsole.log(date.toLocaleString(\"en-US\"));\n// \"12/19/2012, 7:00:00 PM\"\n\n// British English uses day-month-year order and 24-hour time without AM/PM\nconsole.log(date.toLocaleString(\"en-GB\"));\n// \"20/12/2012 03:00:00\"\n\n// Korean uses year-month-day order and 12-hour time with AM/PM\nconsole.log(date.toLocaleString(\"ko-KR\"));\n// \"2012. 12. 20. 오후 12:00:00\"\n\n// Arabic in most Arabic-speaking countries uses Eastern Arabic numerals\nconsole.log(date.toLocaleString(\"ar-EG\"));\n// \"٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص\"\n\n// For Japanese, applications may want to use the Japanese calendar,\n// where 2012 was the year 24 of the Heisei era\nconsole.log(date.toLocaleString(\"ja-JP-u-ca-japanese\"));\n// \"24/12/20 12:00:00\"\n\n// When requesting a language that may not be supported, such as\n// Balinese, include a fallback language (in this case, Indonesian)\nconsole.log(date.toLocaleString([\"ban\", \"id\"]));\n// \"20/12/2012 11.00.00\"\n
\n
\n

Using options

\n
\n

The results provided by toLocaleString() can be customized using the options argument:

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// Request a weekday along with a long date\nconst options = {\n  weekday: \"long\",\n  year: \"numeric\",\n  month: \"long\",\n  day: \"numeric\",\n};\n\nconsole.log(date.toLocaleString(\"de-DE\", options));\n// \"Donnerstag, 20. Dezember 2012\"\n\n// An application may want to use UTC and make that visible\noptions.timeZone = \"UTC\";\noptions.timeZoneName = \"short\";\n\nconsole.log(date.toLocaleString(\"en-US\", options));\n// \"Thursday, December 20, 2012, GMT\"\n\n// Sometimes even the US needs 24-hour time\nconsole.log(date.toLocaleString(\"en-US\", { hour12: false }));\n// \"12/19/2012, 19:00:00\"\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-date.prototype.tolocalestring
ECMAScript Internationalization API Specification
# sup-date.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString11213314.418410.111.01.00.10.0
iana_time_zone_names241452No1574.425561471.51.80.12.0
locales2412291115104.4255614101.51.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options2412291115104.4255614101.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString\n

\n
\n", + "global_objects/string/length": "

String: length

The length data property of a String value contains the length of the string in UTF-16 code units.

\n

Try it

\n

Value

\n
\n

A non-negative integer.

\n
Property attributes of String: length\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by length to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.

The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.

For an empty string, length is 0.

The static property String.length is unrelated to the length of strings. It's the arity of the String function (loosely, the number of formal parameters it has), which is 1.

Since length counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:

\n

js

\n
function getCharacterLength(str) {\n  // The string iterator that is used here iterates over characters,\n  // not mere code units\n  return [...str].length;\n}\n\nconsole.log(getCharacterLength(\"A\\uD87E\\uDC04Z\")); // 3\n
\n
\n

Examples

\n

Basic usage

\n
\n

js

\n
const x = \"Mozilla\";\nconst empty = \"\";\n\nconsole.log(`${x} is ${x.length} code units long`);\n// Mozilla is 7 code units long\n\nconsole.log(`The empty string has a length of ${empty.length}`);\n// The empty string has a length of 0\n
\n

Strings with length not equal to the number of characters

\n
\n

js

\n
const emoji = \"😄\";\nconsole.log(emoji.length); // 2\nconsole.log([...emoji].length); // 1\nconst adlam = \"𞤲𞥋𞤣𞤫\";\nconsole.log(adlam.length); // 8\nconsole.log([...adlam].length); // 4\nconst formula = \"∀𝑥∈ℝ,𝑥²≥0\";\nconsole.log(formula.length); // 11\nconsole.log([...formula].length); // 9\n
\n

Assigning to length

\n
\n

Because string is a primitive, attempting to assign a value to a string's length property has no observable effect, and will throw in strict mode.

\n

js

\n
const myString = \"bluebells\";\n\nmyString.length = 4;\nconsole.log(myString); // \"bluebells\"\nconsole.log(myString.length); // 9\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-properties-of-string-instances-length
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
length11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length\n

\n
\n", + "global_objects/string/indexof": "

String.prototype.indexOf()

The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

\n

Try it

\n

Syntax

\n
\n

js

\n
indexOf(searchString)\nindexOf(searchString, position)\n
\n

Parameters

\n
searchString

Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string \"undefined\", which is rarely what you want.

\nposition Optional\n

The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position, which defaults to 0. If position is greater than the length of the calling string, the method doesn't search the calling string at all. If position is less than zero, the method behaves as it would if position were 0.

  • \n'hello world hello'.indexOf('o', -5) returns 4 — because it causes the method to behave as if the second argument were 0, and the first occurrence of o at a position greater or equal to 0 is at position 4.
  • \n'hello world hello'.indexOf('world', 12) returns -1 — because, while it's true the substring world occurs at index 6, that position is not greater than or equal to 12.
  • \n'hello world hello'.indexOf('o', 99) returns -1 — because 99 is greater than the length of hello world hello, which causes the method to not search the string at all.

Return value

\n
\n

The index of the first occurrence of searchString found, or -1 if not found.

Return value when using an empty search string

Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument:

\n

js

\n
\"hello world\".indexOf(\"\"); // returns 0\n\"hello world\".indexOf(\"\", 0); // returns 0\n\"hello world\".indexOf(\"\", 3); // returns 3\n\"hello world\".indexOf(\"\", 8); // returns 8\n
\n

However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length:

\n

js

\n
\"hello world\".indexOf(\"\", 11); // returns 11\n\"hello world\".indexOf(\"\", 13); // returns 11\n\"hello world\".indexOf(\"\", 22); // returns 11\n
\n

In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.

\n

Description

\n
\n

Strings are zero-indexed: The index of a string's first character is 0, and the index of a string's last character is the length of the string minus 1.

\n

js

\n
\"Blue Whale\".indexOf(\"Blue\"); // returns  0\n\"Blue Whale\".indexOf(\"Blute\"); // returns -1\n\"Blue Whale\".indexOf(\"Whale\", 0); // returns  5\n\"Blue Whale\".indexOf(\"Whale\", 5); // returns  5\n\"Blue Whale\".indexOf(\"Whale\", 7); // returns -1\n\"Blue Whale\".indexOf(\"\"); // returns  0\n\"Blue Whale\".indexOf(\"\", 9); // returns  9\n\"Blue Whale\".indexOf(\"\", 10); // returns 10\n\"Blue Whale\".indexOf(\"\", 11); // returns 10\n
\n

The indexOf() method is case sensitive. For example, the following expression returns -1:

\n

js

\n
\"Blue Whale\".indexOf(\"blue\"); // returns -1\n
\n
\n

Checking occurrences

\n
\n

When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1:

\n

js

\n
\"Blue Whale\".indexOf(\"Blue\") !== -1; // true; found 'Blue' in 'Blue Whale'\n\"Blue Whale\".indexOf(\"Bloe\") !== -1; // false; no 'Bloe' in 'Blue Whale'\n
\n
\n

Examples

\n

Using indexOf()

\n
\n

The following example uses indexOf() to locate substrings in the string \"Brave new world\".

\n

js

\n
const str = \"Brave new world\";\n\nconsole.log(str.indexOf(\"w\")); // 8\nconsole.log(str.indexOf(\"new\")); // 6\n
\n
\n

indexOf() and case-sensitivity

\n
\n

The following example defines two string variables.

The variables contain the same string, except that the second string contains uppercase letters. The first console.log() method displays 19. But because the indexOf() method is case sensitive, the string \"cheddar\" is not found in myCapString, so the second console.log() method displays -1.

\n

js

\n
const myString = \"brie, pepper jack, cheddar\";\nconst myCapString = \"Brie, Pepper Jack, Cheddar\";\n\nconsole.log(myString.indexOf(\"cheddar\")); // 19\nconsole.log(myCapString.indexOf(\"cheddar\")); // -1\n
\n
\n

Using indexOf() to count occurrences of a letter in a string

\n
\n

The following example sets count to the number of occurrences of the letter e in the string str:

\n

js

\n
const str = \"To be, or not to be, that is the question.\";\nlet count = 0;\nlet position = str.indexOf(\"e\");\n\nwhile (position !== -1) {\n  count++;\n  position = str.indexOf(\"e\", position + 1);\n}\n\nconsole.log(count); // 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.indexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
indexOf11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf\n

\n
\n", + "global_objects/string/substring": "

String.prototype.substring()

The substring() method of String values returns the part of this string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.

\n

Try it

\n

Syntax

\n
\n

js

\n
substring(indexStart)\nsubstring(indexStart, indexEnd)\n
\n

Parameters

\n
indexStart

The index of the first character to include in the returned substring.

\nindexEnd Optional\n

The index of the first character to exclude from the returned substring.

Return value

\n

A new string containing the specified part of the given string.

Description

\n
\n

substring() extracts characters from indexStart up to but not including indexEnd. In particular:

Any argument value that is less than 0 or greater than str.length is treated as if it were 0 and str.length, respectively.

Any argument value that is NaN is treated as if it were 0.

\n

Examples

\n

Using substring()

\n
\n

The following example uses substring() to display characters from the string \"Mozilla\":

\n

js

\n
const anyString = \"Mozilla\";\n\nconsole.log(anyString.substring(0, 1)); // \"M\"\nconsole.log(anyString.substring(1, 0)); // \"M\"\n\nconsole.log(anyString.substring(0, 6)); // \"Mozill\"\n\nconsole.log(anyString.substring(4)); // \"lla\"\nconsole.log(anyString.substring(4, 7)); // \"lla\"\nconsole.log(anyString.substring(7, 4)); // \"lla\"\n\nconsole.log(anyString.substring(0, 7)); // \"Mozilla\"\nconsole.log(anyString.substring(0, 10)); // \"Mozilla\"\n
\n
\n

Using substring() with length property

\n
\n

The following example uses the substring() method and length property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

\n

js

\n
const text = \"Mozilla\";\n\n// Takes 4 last characters of string\nconsole.log(text.substring(text.length - 4)); // prints \"illa\"\n\n// Takes 5 last characters of string\nconsole.log(text.substring(text.length - 5)); // prints \"zilla\"\n
\n
\n

The difference between substring() and substr()

\n
\n

There are subtle differences between the substring() and substr() methods, so you should be careful not to get them confused.

Furthermore, substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.

\n

js

\n
const text = \"Mozilla\";\nconsole.log(text.substring(2, 5)); // \"zil\"\nconsole.log(text.substr(2, 3)); // \"zil\"\n
\n
\n

Differences between substring() and slice()

\n
\n

The substring() and slice() methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice() method returns an empty string if this is the case.

\n

js

\n
const text = \"Mozilla\";\nconsole.log(text.substring(5, 2)); // \"zil\"\nconsole.log(text.slice(5, 2)); // \"\"\n
\n

If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.

\n

js

\n
console.log(text.substring(-5, 2)); // \"Mo\"\nconsole.log(text.substring(-5, -2)); // \"\"\n
\n

slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.

\n

js

\n
console.log(text.slice(-5, 2)); // \"\"\nconsole.log(text.slice(-5, -2)); // \"zil\"\n
\n

See the slice() page for more examples with negative numbers.

\n

Replacing a substring within a string

\n
\n

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string Brave New World to Brave New Web.

\n

js

\n
// Replaces oldS with newS in the string fullS\nfunction replaceString(oldS, newS, fullS) {\n  for (let i = 0; i < fullS.length; ++i) {\n    if (fullS.substring(i, i + oldS.length) === oldS) {\n      fullS =\n        fullS.substring(0, i) +\n        newS +\n        fullS.substring(i + oldS.length, fullS.length);\n    }\n  }\n  return fullS;\n}\n\nreplaceString(\"World\", \"Web\", \"Brave New World\");\n
\n

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace \"World\" with \"OtherWorld\" here.

A better method for replacing strings is as follows:

\n

js

\n
function replaceString(oldS, newS, fullS) {\n  return fullS.split(oldS).join(newS);\n}\n
\n

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use String.prototype.replace().

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.substring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
substring11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring\n

\n
\n", + "global_objects/string/charat": "

String.prototype.charAt()

\n

The charAt() method of String values returns a new string consisting of the single UTF-16 code unit at the given index.

charAt() always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at the given index, use String.prototype.codePointAt() and String.fromCodePoint().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
charAt(index)\n
\n

Parameters

\n
index

Zero-based index of the character to be returned. Converted to an integerundefined is converted to 0.

Return value

\n

A string representing the character (exactly one UTF-16 code unit) at the specified index. If index is out of the range of 0str.length - 1, charAt() returns an empty string.

Description

\n
\n

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called str is str.length - 1.

Unicode code points range from 0 to 1114111 (0x10FFFF). charAt() always returns a character whose value is less than 65536, because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to get a full character with value greater than 65535, it is necessary to retrieve not only charAt(i), but also charAt(i + 1) (as if manipulating a string with two characters), or to use codePointAt(i) and String.fromCodePoint() instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

charAt() is very similar to using bracket notation to access a character at the specified index. The main differences are:

\n

Examples

\n

Using charAt()

\n
\n

The following example displays characters at different locations in the string \"Brave new world\":

\n

js

\n
const anyString = \"Brave new world\";\nconsole.log(`The character at index 0   is '${anyString.charAt()}'`);\n// No index was provided, used 0 as default\n\nconsole.log(`The character at index 0   is '${anyString.charAt(0)}'`);\nconsole.log(`The character at index 1   is '${anyString.charAt(1)}'`);\nconsole.log(`The character at index 2   is '${anyString.charAt(2)}'`);\nconsole.log(`The character at index 3   is '${anyString.charAt(3)}'`);\nconsole.log(`The character at index 4   is '${anyString.charAt(4)}'`);\nconsole.log(`The character at index 999 is '${anyString.charAt(999)}'`);\n
\n

These lines display the following:

The character at index 0   is 'B'\n\nThe character at index 0   is 'B'\nThe character at index 1   is 'r'\nThe character at index 2   is 'a'\nThe character at index 3   is 'v'\nThe character at index 4   is 'e'\nThe character at index 999 is ''\n

charAt() may return lone surrogates, which are not valid Unicode characters.

\n

js

\n
const str = \"𠮷𠮾\";\nconsole.log(str.charAt(0)); // \"\\ud842\", which is not a valid Unicode character\nconsole.log(str.charAt(1)); // \"\\udfb7\", which is not a valid Unicode character\n
\n

To get the full Unicode code point at the given index, use an indexing method that splits by Unicode code points, such as String.prototype.codePointAt() and spreading strings into an array of Unicode code points.

\n

js

\n
const str = \"𠮷𠮾\";\nconsole.log(String.fromCodePoint(str.codePointAt(0))); // \"𠮷\"\nconsole.log([...str][0]); // \"𠮷\"\n
\n

Note: Avoid re-implementing the solutions above using charAt(). The detection of lone surrogates and their pairing is complex, and built-in APIs may be more performant as they directly use the internal representation of the string. Install a polyfill for the APIs mentioned above if necessary.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.charat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
charAt11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt\n

\n
\n", + "global_objects/string/touppercase": "

String.prototype.toUpperCase()

The toUpperCase() method of String values returns this string converted to uppercase.

\n

Try it

\n

Syntax

\n
\n

js

\n
toUpperCase()\n
\n

Parameters

\n

None.

Return value

\n

A new string representing the calling string converted to upper case.

Description

\n

The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.

Examples

\n

Basic usage

\n
\n

js

\n
console.log(\"alphabet\".toUpperCase()); // 'ALPHABET'\n
\n

Conversion of non-string this values to strings

\n
\n

This method will convert any non-string value to a string, when you set its this to a value that is not a string:

\n

js

\n
const a = String.prototype.toUpperCase.call({\n  toString() {\n    return \"abcdef\";\n  },\n});\n\nconst b = String.prototype.toUpperCase.call(true);\n\n// prints out 'ABCDEF TRUE'.\nconsole.log(a, b);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.touppercase
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toUpperCase11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase\n

\n
\n", + "global_objects/string/tolowercase": "

String.prototype.toLowerCase()

The toLowerCase() method of String values returns this string converted to lower case.

\n

Try it

\n

Syntax

\n
\n

js

\n
toLowerCase()\n
\n

Parameters

\n

None.

Return value

\n

A new string representing the calling string converted to lower case.

Description

\n

The toLowerCase() method returns the value of the string converted to lower case. toLowerCase() does not affect the value of the string str itself.

Examples

\n

Using toLowerCase()\n

\n
\n

js

\n
console.log(\"ALPHABET\".toLowerCase()); // 'alphabet'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.tolowercase
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLowerCase11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase\n

\n
\n", + "global_objects/string/tolocalelowercase": "

String.prototype.toLocaleLowerCase()

The toLocaleLowerCase() method of String values returns this string converted to lower case, according to any locale-specific case mappings.

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleLowerCase()\ntoLocaleLowerCase(locales)\n
\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

Unlike other methods that use the locales argument, toLocaleLowerCase() does not allow locale matching. Therefore, after checking the validity of the locales argument, toLocaleLowerCase() always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.

Return value

\n

A new string representing the calling string converted to lower case, according to any locale-specific case mappings.

Description

\n

The toLocaleLowerCase() method returns the value of the string converted to lower case according to any locale-specific case mappings. toLocaleLowerCase() does not affect the value of the string itself. In most cases, this will produce the same result as toLowerCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.

Examples

\n

Using toLocaleLowerCase()

\n
\n

js

\n
\"ALPHABET\".toLocaleLowerCase(); // 'alphabet'\n\n\"\\u0130\".toLocaleLowerCase(\"tr\") === \"i\"; // true\n\"\\u0130\".toLocaleLowerCase(\"en-US\") === \"i\"; // false\n\nconst locales = [\"tr\", \"TR\", \"tr-TR\", \"tr-u-co-search\", \"tr-x-turkish\"];\n\"\\u0130\".toLocaleLowerCase(locales) === \"i\"; // true\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.tolocalelowercase
ECMAScript Internationalization API Specification
# sup-string.prototype.tolocalelowercase
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleLowerCase11215.541.34.418410.111.01.00.10.0
locale5812556451058585543107.01.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase\n

\n
\n", + "global_objects/string/localecompare": "

String.prototype.localeCompare()

\n

The localeCompare() method of String values returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order. In implementations with Intl.Collator API support, this method simply calls Intl.Collator.

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare() method.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
localeCompare(compareString)\nlocaleCompare(compareString, locales)\nlocaleCompare(compareString, locales, options)\n
\n

Parameters

\n
\n

The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.Collator API, these parameters correspond exactly to the Intl.Collator() constructor's parameters. Implementations without Intl.Collator support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be consistent.

compareString

The string against which the referenceStr is compared. All values are coerced to strings, so omitting it or passing undefined causes localeCompare() to compare against the string \"undefined\", which is rarely what you want.

\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.Collator() constructor.

In implementations without Intl.Collator support, this parameter is ignored and the host's locale is usually used.

\noptions Optional\n

An object adjusting the output format. Corresponds to the options parameter of the Intl.Collator() constructor.

In implementations without Intl.Collator support, this parameter is ignored.

See the Intl.Collator() constructor for details on the locales and options parameters and how to use them.

\n

Return value

\n
\n

A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent.

In implementations with Intl.Collator, this is equivalent to new Intl.Collator(locales, options).compare(referenceStr, compareString).

\n

Description

\n
\n

Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareString.

Warning: Do not rely on exact return values of -1 or 1!

Negative and positive integer results vary between browsers (as well as between browser versions) because the ECMAScript specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value.

\n

Examples

\n

Using localeCompare()

\n
\n

js

\n
// The letter \"a\" is before \"c\" yielding a negative value\n\"a\".localeCompare(\"c\"); // -2 or -1 (or some other negative value)\n\n// Alphabetically the word \"check\" comes after \"against\" yielding a positive value\n\"check\".localeCompare(\"against\"); // 2 or 1 (or some other positive value)\n\n// \"a\" and \"a\" are equivalent yielding a neutral value of zero\n\"a\".localeCompare(\"a\"); // 0\n
\n

Sort an array

\n
\n

localeCompare() enables case-insensitive sorting for an array.

\n

js

\n
const items = [\"réservé\", \"Premier\", \"Cliché\", \"communiqué\", \"café\", \"Adieu\"];\nitems.sort((a, b) => a.localeCompare(b, \"fr\", { ignorePunctuation: true }));\n// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']\n
\n
\n

Check browser support for extended arguments

\n
\n

The locales and options arguments are not supported in all browsers yet.

To check whether an implementation supports them, use the \"i\" argument (a requirement that illegal language tags are rejected) and look for a RangeError exception:

\n

js

\n
function localeCompareSupportsLocales() {\n  try {\n    \"foo\".localeCompare(\"bar\", \"i\");\n  } catch (e) {\n    return e.name === \"RangeError\";\n  }\n  return false;\n}\n
\n
\n

Using locales

\n
\n

The results provided by localeCompare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

\n

js

\n
console.log(\"ä\".localeCompare(\"z\", \"de\")); // a negative value: in German, ä sorts before z\nconsole.log(\"ä\".localeCompare(\"z\", \"sv\")); // a positive value: in Swedish, ä sorts after z\n
\n
\n

Using options

\n
\n

The results provided by localeCompare() can be customized using the options argument:

\n

js

\n
// in German, ä has a as the base letter\nconsole.log(\"ä\".localeCompare(\"a\", \"de\", { sensitivity: \"base\" })); // 0\n\n// in Swedish, ä and a are separate base letters\nconsole.log(\"ä\".localeCompare(\"a\", \"sv\", { sensitivity: \"base\" })); // a positive value\n
\n
\n

Numeric sorting

\n
\n

js

\n
// by default, \"2\" > \"10\"\nconsole.log(\"2\".localeCompare(\"10\")); // 1\n\n// numeric using options:\nconsole.log(\"2\".localeCompare(\"10\", undefined, { numeric: true })); // -1\n\n// numeric using locales tag:\nconsole.log(\"2\".localeCompare(\"10\", \"en-u-kn-true\")); // -1\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.localecompare
ECMAScript Internationalization API Specification
# sup-String.prototype.localeCompare
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
localeCompare11215.5734.418410.111.01.00.10.0
locales241229111510No2656No101.51.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options241229111510No2656No101.51.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare\n

\n
\n", + "global_objects/intl/collator/collator": "

Intl.Collator() constructor

The Intl.Collator() constructor creates Intl.Collator objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.Collator()\nnew Intl.Collator(locales)\nnew Intl.Collator(locales, options)\n\nIntl.Collator()\nIntl.Collator(locales)\nIntl.Collator(locales, options)\n
\n

Note: Intl.Collator() can be called with or without new. Both create a new Intl.Collator instance.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

The following Unicode extension keys are allowed:

co

See collation.

kn

See numeric.

kf

See caseFirst.

These keys can also be set with options (as listed below). When both are set, the options property takes precedence.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

usage

Whether the comparison is for sorting a list of strings or fuzzy (for the Latin script diacritic-insensitive and case-insensitive) filtering a list of strings by key. Possible values are:

\n\"sort\" (default)

For sorting a list of strings.

\"search\"

For filtering a list of strings by testing each list item for a full-string match against a key. With \"search\", the caller should only pay attention to whether compare() returns zero or non-zero and should not distinguish the non-zero return values from each other. That is, it is inappropriate to use \"search\" for sorting/ordering.

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

collation

Variant collations for certain locales, such as \"emoji\", \"pinyin\", \"stroke\", and so on. For a list of supported collation types, see Intl.Locale.prototype.getCollations(); the default is \"default\". This option can also be set through the co Unicode extension key; if both are provided, this options property takes precedence.

numeric

Whether numeric collation should be used, such that \"1\" < \"2\" < \"10\". Possible values are true and false; the default is false. This option can also be set through the kn Unicode extension key; if both are provided, this options property takes precedence.

caseFirst

Whether upper case or lower case should sort first. Possible values are \"upper\", \"lower\", and \"false\" (use the locale's default); the default is \"false\". This option can also be set through the kf Unicode extension key; if both are provided, this options property takes precedence.

sensitivity

Which differences in the strings should lead to non-zero result values. Possible values are:

\"base\"

Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.

\"accent\"

Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.

\"case\"

Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.

\"variant\"

Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.

The default is \"variant\" for usage \"sort\"; it's locale dependent for usage \"search\" per spec, but the core functionality of \"search\" is accent-insensitive and case-insensitive filtering, so \"base\" makes the most sense (and perhaps \"case\").

ignorePunctuation

Whether punctuation should be ignored. Possible values are true and false; the default is false.

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Using Collator

\n
\n

The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:

\n

js

\n
console.log(new Intl.Collator().compare(\"a\", \"c\")); // -1, or some other negative value\nconsole.log(new Intl.Collator().compare(\"c\", \"a\")); // 1, or some other positive value\nconsole.log(new Intl.Collator().compare(\"a\", \"a\")); // 0\n
\n

Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.

When usage is \"search\", the caller should only pay attention to whether the return value of compare() is zero or non-zero. It is inappropriate to use a Collator with usage \"search\" for sorting.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-the-intl-collator-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Collator2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the Collator instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options_caseFirst_parameter241855No15114.4255614111.51.80.12.0
options_collation_parameter878785No7314.1878785No14.514.01.815.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator\n

\n
\n", + "global_objects/string/valueof": "

String.prototype.valueOf()

The valueOf() method of String values returns this string value.

\n

Try it

\n

Syntax

\n
\n

js

\n
valueOf()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the primitive value of a given String object.

Description

\n
\n

The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.toString().

This method is usually called internally by JavaScript and not explicitly in code.

\n

Examples

\n

Using valueOf()\n

\n
\n

js

\n
const x = new String(\"Hello world\");\nconsole.log(x.valueOf()); // 'Hello world'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.valueof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
valueOf11214314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf\n

\n
\n", + "global_objects/string/@@iterator": "

String.prototype[@@iterator]()

The [@@iterator]() method of String values implements the iterable protocol and allows strings to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a string iterator object that yields the Unicode code points of the string value as individual strings.

\n

Try it

\n

Syntax

\n
\n

js

\n
string[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object that yields the Unicode code points of the string value as individual strings.

Description

\n
\n

Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved.

\n

js

\n
// \"Backhand Index Pointing Right: Dark Skin Tone\"\n[...\"👉🏿\"]; // ['👉', '🏿']\n// splits into the basic \"Backhand Index Pointing Right\" emoji and\n// the \"Dark skin tone\" emoji\n\n// \"Family: Man, Boy\"\n[...\"👨‍👦\"]; // [ '👨', '‍', '👦' ]\n// splits into the \"Man\" and \"Boy\" emoji, joined by a ZWJ\n
\n
\n

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes strings iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const str = \"A\\uD835\\uDC68B\\uD835\\uDC69C\\uD835\\uDC6A\";\n\nfor (const v of str) {\n  console.log(v);\n}\n// \"A\"\n// \"\\uD835\\uDC68\"\n// \"B\"\n// \"\\uD835\\uDC69\"\n// \"C\"\n// \"\\uD835\\uDC6A\"\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const str = \"A\\uD835\\uDC68\";\n\nconst strIter = str[Symbol.iterator]();\n\nconsole.log(strIter.next().value); // \"A\"\nconsole.log(strIter.next().value); // \"\\uD835\\uDC68\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No259383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
2593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator\n

\n
\n", + "global_objects/string/fromcharcode": "

String.fromCharCode()

The String.fromCharCode() static method returns a string created from the specified sequence of UTF-16 code units.

\n

Try it

\n

Syntax

\n
\n

js

\n
String.fromCharCode()\nString.fromCharCode(num1)\nString.fromCharCode(num1, num2)\nString.fromCharCode(num1, num2, /* …, */ numN)\n
\n

Parameters

\n
\nnum1, …, numN\n

A number between 0 and 65535 (0xFFFF) representing a UTF-16 code unit. Numbers greater than 0xFFFF are truncated to the last 16 bits. No validity checks are performed.

Return value

\n

A string of length N consisting of the N specified UTF-16 code units.

Description

\n
\n

Because fromCharCode() is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String value you created.

Unicode code points range from 0 to 1114111 (0x10FFFF). charCodeAt() always returns a value that is less than 65536, because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to produce a full character with value greater than 65535, it is necessary to provide two code units (as if manipulating a string with two characters). For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Because fromCharCode() only works with 16-bit values (same as the \\u escape sequence), a surrogate pair is required in order to return a supplementary character. For example, both String.fromCharCode(0xd83c, 0xdf03) and \"\\ud83c\\udf03\" return code point U+1F303 \"Night with Stars\". While there is a mathematical relationship between the supplementary code point value (e.g. 0x1f303) and both surrogate values that represent it (e.g., 0xd83c and 0xdf03), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. For this reason, it's more convenient to use String.fromCodePoint(), which allows for returning supplementary characters based on their actual code point value. For example, String.fromCodePoint(0x1f303) returns code point U+1F303 \"Night with Stars\".

\n

Examples

\n

Using fromCharCode()

\n
\n

BMP characters, in UTF-16, use a single code unit:

\n

js

\n
String.fromCharCode(65, 66, 67); // returns \"ABC\"\nString.fromCharCode(0x2014); // returns \"—\"\nString.fromCharCode(0x12014); // also returns \"—\"; the digit 1 is truncated and ignored\nString.fromCharCode(8212); // also returns \"—\"; 8212 is the decimal form of 0x2014\n
\n

Supplementary characters, in UTF-16, require two code units (i.e. a surrogate pair):

\n

js

\n
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 \"Night with\nString.fromCharCode(55356, 57091); // Stars\" === \"\\uD83C\\uDF03\"\n\nString.fromCharCode(0xd834, 0xdf06, 0x61, 0xd834, 0xdf07); // \"\\uD834\\uDF06a\\uD834\\uDF07\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.fromcharcode
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fromCharCode11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode\n

\n
\n", + "global_objects/string/fromcodepoint": "

String.fromCodePoint()

The String.fromCodePoint() static method returns a string created from the specified sequence of code points.

\n

Try it

\n

Syntax

\n
\n

js

\n
String.fromCodePoint()\nString.fromCodePoint(num1)\nString.fromCodePoint(num1, num2)\nString.fromCodePoint(num1, num2, /* …, */ numN)\n
\n

Parameters

\n
\nnum1, …, numN\n

An integer between 0 and 0x10FFFF (inclusive) representing a Unicode code point.

Return value

\n

A string created by using the specified sequence of code points.

Exceptions

\n
RangeError

Thrown if numN is not an integer, is less than 0, or is greater than 0x10FFFF after being converted to a number.

Description

\n
\n

Because fromCodePoint() is a static method of String, you always use it as String.fromCodePoint(), rather than as a method of a String value you created.

Unicode code points range from 0 to 1114111 (0x10FFFF). In UTF-16, each string index is a code unit with value 065535. Higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, fromCodePoint() may return a string whose length (in UTF-16 code units) is larger than the number of arguments passed. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

\n

Examples

\n

Using fromCodePoint()

\n
\n

Valid input:

\n

js

\n
String.fromCodePoint(42); // \"*\"\nString.fromCodePoint(65, 90); // \"AZ\"\nString.fromCodePoint(0x404); // \"\\u0404\" === \"Є\"\nString.fromCodePoint(0x2f804); // \"\\uD87E\\uDC04\"\nString.fromCodePoint(194564); // \"\\uD87E\\uDC04\"\nString.fromCodePoint(0x1d306, 0x61, 0x1d307); // \"\\uD834\\uDF06a\\uD834\\uDF07\"\n
\n

Invalid input:

\n

js

\n
String.fromCodePoint(\"_\"); // RangeError\nString.fromCodePoint(Infinity); // RangeError\nString.fromCodePoint(-1); // RangeError\nString.fromCodePoint(3.14); // RangeError\nString.fromCodePoint(3e-2); // RangeError\nString.fromCodePoint(NaN); // RangeError\n
\n
\n

Compared to fromCharCode()

\n
\n

String.fromCharCode() cannot return supplementary characters (i.e. code points 0x0100000x10FFFF) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character:

\n

js

\n
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 \"Night with\nString.fromCharCode(55356, 57091); // Stars\" === \"\\uD83C\\uDF03\"\n
\n

String.fromCodePoint(), on the other hand, can return 4-byte supplementary characters, as well as the more common 2-byte BMP characters, by specifying their code point (which is equivalent to the UTF-32 code unit):

\n

js

\n
String.fromCodePoint(0x1f303); // or 127747 in decimal\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.fromcodepoint
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fromCodePoint411229No2894141292894.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint\n

\n
\n", + "global_objects/string/raw": "

String.raw()

The String.raw() static method is a tag function of template literals. This is similar to the r prefix in Python, or the @ prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. ${foo}) are processed, but escape sequences (e.g. \\n) are not.

\n

Try it

\n

Syntax

\n
\n

js

\n
String.raw(strings)\nString.raw(strings, sub1)\nString.raw(strings, sub1, sub2)\nString.raw(strings, sub1, sub2, /* …, */ subN)\n\nString.raw`templateString`\n
\n

Parameters

\n
strings

Well-formed template literal array object, like { raw: ['foo', 'bar', 'baz'] }. Should be an object with a raw property whose value is an array-like object of strings.

\nsub1, …, subN\n

Contains substitution values.

templateString

A template literal, optionally with substitutions (${...}).

Return value

\n

The raw string form of a given template literal.

Exceptions

\n
TypeError

Thrown if the first argument doesn't have a raw property, or the raw property is undefined or null.

Description

\n
\n

In most cases, String.raw() is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other tag functions).

String.raw() is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code.

Warning: You should not use String.raw directly as an \"identity\" tag. See Building an identity tag for how to implement this.

If String.raw() is called with an object whose raw property doesn't have a length property or a non-positive length, it returns an empty string \"\". If substitutions.length < strings.raw.length - 1 (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings.

\n

Examples

\n

Using String.raw()

\n
\n

js

\n
String.raw`Hi\\n${2 + 3}!`;\n// 'Hi\\\\n5!', the character after 'Hi'\n// is not a newline character,\n// '\\' and 'n' are two characters.\n\nString.raw`Hi\\u000A!`;\n// 'Hi\\\\u000A!', same here, this time we will get the\n// \\, u, 0, 0, 0, A, 6 characters.\n// All kinds of escape characters will be ineffective\n// and backslashes will be present in the output string.\n// You can confirm this by checking the .length property\n// of the string.\n\nconst name = \"Bob\";\nString.raw`Hi\\n${name}!`;\n// 'Hi\\\\nBob!', substitutions are processed.\n\nString.raw`Hi \\${name}!`;\n// 'Hi \\\\${name}!', the dollar sign is escaped; there's no interpolation.\n
\n

Building an identity tag

\n
\n

Many tools give special treatment to literals tagged by a particular name.

\n

js

\n
// Some formatters will format this literal's content as HTML\nconst doc = html`<!DOCTYPE html>\n<html lang=\"en-US\">\n  <head>\n    <title>Hello</title>\n  </head>\n  <body>\n    <h1>Hello world!</h1>\n  </body>\n</html>\n`;\n
\n

One might naïvely implement the html tag as:

\n

js

\n
const html = String.raw;\n
\n

This, in fact, works for the case above. However, because String.raw would concatenate the raw string literals instead of the \"cooked\" ones, escape sequences would not be processed.

\n

js

\n
const doc = html`<canvas>\\n</canvas>`;\n// \"<canvas>\\\\n</canvas>\"\n
\n

This may not be what you want for a \"true identity\" tag, where the tag is purely for markup and doesn't change the literal's value. In this case, you can create a custom tag and pass the \"cooked\" (i.e. escape sequences are processed) literal array to String.raw, pretending they are raw strings.

\n

js

\n
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);\n// Some formatters will format this literal's content as HTML\nconst doc = html`<canvas>\\n</canvas>`;\n// \"<canvas>\\n</canvas>\"; the \"\\n\" becomes a line break\n
\n

Notice the first argument is an object with a raw property, whose value is an array-like object (with a length property and integer indexes) representing the separated strings in the template literal. The rest of the arguments are the substitutions. Since the raw value can be any array-like object, it can even be a string! For example, 'test' is treated as ['t', 'e', 's', 't']. The following is equivalent to `t${0}e${1}s${2}t`:

\n

js

\n
String.raw({ raw: \"test\" }, 0, 1, 2); // 't0e1s2t'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.raw
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
raw411234No2894141342894.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw\n

\n
\n", + "global_objects/string/at": "

String.prototype.at()

The at() method of String values takes an integer value and returns a new String consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.

\n

Try it

\n

Syntax

\n
\n

js

\n
at(index)\n
\n

Parameters

\n
index

The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string.

Return value

\n

A String consisting of the single UTF-16 code unit located at the specified position. Returns undefined if the given index can not be found.

Examples

\n

Return the last character of a string

\n
\n

The following example provides a function which returns the last character found in a specified string.

\n

js

\n
// A function which returns the last character of a given string\nfunction returnLast(arr) {\n  return arr.at(-1);\n}\n\nlet invoiceRef = \"myinvoice01\";\n\nconsole.log(returnLast(invoiceRef)); // '1'\n\ninvoiceRef = \"myinvoice02\";\n\nconsole.log(returnLast(invoiceRef)); // '2'\n
\n
\n

Comparing methods

\n
\n

Here we compare different ways to select the penultimate (last but one) character of a String. Whilst all below methods are valid, it highlights the succinctness and readability of the at() method.

\n

js

\n
const myString = \"Every green bus drives fast.\";\n\n// Using length property and charAt() method\nconst lengthWay = myString.charAt(myString.length - 2);\nconsole.log(lengthWay); // 't'\n\n// Using slice() method\nconst sliceWay = myString.slice(-2, -1);\nconsole.log(sliceWay); // 't'\n\n// Using at() method\nconst atWay = myString.at(-2);\nconsole.log(atWay); // 't'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.at
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
at929290No7815.49292906515.416.01.1216.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/at\n

\n
\n", + "global_objects/string/charcodeat": "

String.prototype.charCodeAt()

\n

The charCodeAt() method of String values returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

charCodeAt() always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at the given index, use String.prototype.codePointAt().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
charCodeAt(index)\n
\n

Parameters

\n
index

Zero-based index of the character to be returned. Converted to an integerundefined is converted to 0.

Return value

\n

An integer between 0 and 65535 representing the UTF-16 code unit value of the character at the specified index. If index is out of range of 0str.length - 1, charCodeAt() returns NaN.

Description

\n
\n

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called str is str.length - 1.

Unicode code points range from 0 to 1114111 (0x10FFFF). charCodeAt() always returns a value that is less than 65536, because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to get a full character with value greater than 65535, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i + 1) (as if manipulating a string with two characters), or to use codePointAt(i) instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

\n

Examples

\n

Using charCodeAt()

\n
\n

The following example returns 65, the Unicode value for A.

\n

js

\n
\"ABC\".charCodeAt(0); // returns 65\n
\n

charCodeAt() may return lone surrogates, which are not valid Unicode characters.

\n

js

\n
const str = \"𠮷𠮾\";\nconsole.log(str.charCodeAt(0)); // 55362, or d842, which is not a valid Unicode character\nconsole.log(str.charCodeAt(1)); // 57271, or dfb7, which is not a valid Unicode character\n
\n

To get the full Unicode code point at the given index, use String.prototype.codePointAt().

\n

js

\n
const str = \"𠮷𠮾\";\nconsole.log(str.codePointAt(0)); // 134071\n
\n

Note: Avoid re-implementing codePointAt() using charCodeAt(). The translation from UTF-16 surrogates to Unicode code points is complex, and codePointAt() may be more performant as it directly uses the internal representation of the string. Install a polyfill for codePointAt() if necessary.

Below is a possible algorithm to convert a pair of UTF-16 code units into a Unicode code point, adapted from the Unicode FAQ:

\n

js

\n
// constants\nconst LEAD_OFFSET = 0xd800 - (0x10000 >> 10);\nconst SURROGATE_OFFSET = 0x10000 - (0xd800 << 10) - 0xdc00;\n\nfunction utf16ToUnicode(lead, trail) {\n  return (lead << 10) + trail + SURROGATE_OFFSET;\n}\nfunction unicodeToUTF16(codePoint) {\n  const lead = LEAD_OFFSET + (codePoint >> 10);\n  const trail = 0xdc00 + (codePoint & 0x3ff);\n  return [lead, trail];\n}\n\nconst str = \"𠮷\";\nconsole.log(utf16ToUnicode(str.charCodeAt(0), str.charCodeAt(1))); // 134071\nconsole.log(str.codePointAt(0)); // 134071\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.charcodeat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
charCodeAt11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt\n

\n
\n", + "global_objects/string/codepointat": "

String.prototype.codePointAt()

The codePointAt() method of String values returns a non-negative integer that is the Unicode code point value of the character starting at the given index. Note that the index is still based on UTF-16 code units, not Unicode code points.

\n

Try it

\n

Syntax

\n
\n

js

\n
codePointAt(index)\n
\n

Parameters

\n
index

Zero-based index of the character to be returned. Converted to an integerundefined is converted to 0.

Return value

\n
\n

A non-negative integer representing the code point value of the character at the given index.

\n

Description

\n
\n

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called str is str.length - 1.

Unicode code points range from 0 to 1114111 (0x10FFFF). In UTF-16, each string index is a code unit with value 065535. Higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, codePointAt() returns a code point that may span two string indices. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

\n

Examples

\n

Using codePointAt()

\n
\n

js

\n
\"ABC\".codePointAt(0); // 65\n\"ABC\".codePointAt(0).toString(16); // 41\n\n\"😍\".codePointAt(0); // 128525\n\"\\ud83d\\ude0d\".codePointAt(0); // 128525\n\"\\ud83d\\ude0d\".codePointAt(0).toString(16); // 1f60d\n\n\"😍\".codePointAt(1); // 56845\n\"\\ud83d\\ude0d\".codePointAt(1); // 56845\n\"\\ud83d\\ude0d\".codePointAt(1).toString(16); // de0d\n\n\"ABC\".codePointAt(42); // undefined\n
\n

Looping with codePointAt()

\n
\n

Because using string indices for looping causes the same code point to be visited twice (once for the leading surrogate, once for the trailing surrogate), and the second time codePointAt() returns only the trailing surrogate, it's better to avoid looping by index.

\n

js

\n
const str = \"\\ud83d\\udc0e\\ud83d\\udc71\\u2764\";\n\nfor (let i = 0; i < str.length; i++) {\n  console.log(str.codePointAt(i).toString(16));\n}\n// '1f40e', 'dc0e', '1f471', 'dc71', '2764'\n
\n

Instead, use a for...of statement or spread the string, both of which invoke the string's @@iterator, which iterates by code points. Then, use codePointAt(0) to get the code point of each element.

\n

js

\n
for (const codePoint of str) {\n  console.log(codePoint.codePointAt(0).toString(16));\n}\n// '1f40e', '1f471', '2764'\n\n[...str].map((cp) => cp.codePointAt(0).toString(16));\n// ['1f40e', '1f471', '2764']\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.codepointat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
codePointAt411229No2894141292894.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt\n

\n
\n", + "global_objects/string/concat": "

String.prototype.concat()

The concat() method of String values concatenates the string arguments to this string and returns a new string.

\n

Try it

\n

Syntax

\n
\n

js

\n
concat()\nconcat(str1)\nconcat(str1, str2)\nconcat(str1, str2, /* …, */ strN)\n
\n

Parameters

\n
\nstr1, …, strN\n

One or more strings to concatenate to str.

Return value

\n

A new string containing the combined text of the strings provided.

Description

\n
\n

The concat() function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other.

If the arguments are not of the type string, they are converted to string values before concatenating.

The concat() method is very similar to the addition/string concatenation operators (+, +=), except that concat() coerces its arguments directly to strings, while addition coerces its operands to primitives first. For more information, see the reference page for the + operator.

\n

Examples

\n

Using concat()

\n
\n

The following example combines strings into a new string.

\n

js

\n
const hello = \"Hello, \";\nconsole.log(hello.concat(\"Kevin\", \". Have a nice day.\"));\n// Hello, Kevin. Have a nice day.\n\nconst greetList = [\"Hello\", \" \", \"Venkat\", \"!\"];\n\"\".concat(...greetList); // \"Hello Venkat!\"\n\n\"\".concat({}); // \"[object Object]\"\n\"\".concat([]); // \"\"\n\"\".concat(null); // \"null\"\n\"\".concat(true); // \"true\"\n\"\".concat(4, 5); // \"45\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.concat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
concat11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat\n

\n
\n", + "global_objects/string/endswith": "

String.prototype.endsWith()

The endsWith() method of String values determines whether a string ends with the characters of this string, returning true or false as appropriate.

\n

Try it

\n

Syntax

\n
\n

js

\n
endsWith(searchString)\nendsWith(searchString, endPosition)\n
\n

Parameters

\n
searchString

The characters to be searched for at the end of str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes endsWith() to search for the string \"undefined\", which is rarely what you want.

\nendPosition Optional\n

The end position at which searchString is expected to be found (the index of searchString's last character plus 1). Defaults to str.length.

Return value

\n

true if the given characters are found at the end of the string, including when searchString is an empty string; otherwise, false.

Exceptions

\n
TypeError

Thrown if searchString is a regex.

Description

\n

This method lets you determine whether or not a string ends with another string. This method is case-sensitive.

Examples

\n

Using endsWith()

\n
\n

js

\n
const str = \"To be, or not to be, that is the question.\";\n\nconsole.log(str.endsWith(\"question.\")); // true\nconsole.log(str.endsWith(\"to be\")); // false\nconsole.log(str.endsWith(\"to be\", 19)); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.endswith
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
endsWith411217No2893736172493.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n

\n
\n", + "global_objects/string/includes": "

String.prototype.includes()

The includes() method of String values performs a case-sensitive search to determine whether a given string may be found within this string, returning true or false as appropriate.

\n

Try it

\n

Syntax

\n
\n

js

\n
includes(searchString)\nincludes(searchString, position)\n
\n

Parameters

\n
searchString

A string to be searched for within str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes includes() to search for the string \"undefined\", which is rarely what you want.

\nposition Optional\n

The position within the string at which to begin searching for searchString. (Defaults to 0.)

Return value

\n

true if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false.

Exceptions

\n
TypeError

Thrown if searchString is a regex.

Description

\n

This method lets you determine whether or not a string includes another string.

Case-sensitivity

\n
\n

The includes() method is case sensitive. For example, the following expression returns false:

\n

js

\n
\"Blue Whale\".includes(\"blue\"); // returns false\n
\n

You can work around this constraint by transforming both the original string and the search string to all lowercase:

\n

js

\n
\"Blue Whale\".toLowerCase().includes(\"blue\"); // returns true\n
\n
\n

Examples

\n

Using includes()

\n
\n

js

\n
const str = \"To be, or not to be, that is the question.\";\n\nconsole.log(str.includes(\"To be\")); // true\nconsole.log(str.includes(\"question\")); // true\nconsole.log(str.includes(\"nonexistent\")); // false\nconsole.log(str.includes(\"To be\", 1)); // false\nconsole.log(str.includes(\"TO BE\")); // false\nconsole.log(str.includes(\"\")); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.includes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
includes41124018–48No28941414018–482894.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n

\n
\n", + "global_objects/string/lastindexof": "

String.prototype.lastIndexOf()

The lastIndexOf() method of String values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

\n

Try it

\n

Syntax

\n
\n

js

\n
lastIndexOf(searchString)\nlastIndexOf(searchString, position)\n
\n

Parameters

\n
searchString

Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes lastIndexOf() to search for the string \"undefined\", which is rarely what you want.

\nposition Optional\n

The method returns the index of the last occurrence of the specified substring at a position less than or equal to position, which defaults to +Infinity. If position is greater than the length of the calling string, the method searches the entire string. If position is less than 0, the behavior is the same as for 0 — that is, the method looks for the specified substring only at index 0.

  • \n'hello world hello'.lastIndexOf('world', 4) returns -1 — because, while the substring world does occurs at index 6, that position is not less than or equal to 4.
  • \n'hello world hello'.lastIndexOf('hello', 99) returns 12 — because the last occurrence of hello at a position less than or equal to 99 is at position 12.
  • \n'hello world hello'.lastIndexOf('hello', 0) and 'hello world hello'.lastIndexOf('hello', -5) both return 0 — because both cause the method to only look for hello at index 0.

Return value

\n

The index of the last occurrence of searchString found, or -1 if not found.

Description

\n
\n

Strings are zero-indexed: The index of a string's first character is 0, and the index of a string's last character is the length of the string minus 1.

\n

js

\n
\"canal\".lastIndexOf(\"a\"); // returns 3\n\"canal\".lastIndexOf(\"a\", 2); // returns 1\n\"canal\".lastIndexOf(\"a\", 0); // returns -1\n\"canal\".lastIndexOf(\"x\"); // returns -1\n\"canal\".lastIndexOf(\"c\", -5); // returns 0\n\"canal\".lastIndexOf(\"c\", 0); // returns 0\n\"canal\".lastIndexOf(\"\"); // returns 5\n\"canal\".lastIndexOf(\"\", 2); // returns 2\n
\n
\n

Case-sensitivity

\n
\n

The lastIndexOf() method is case sensitive. For example, the following expression returns -1:

\n

js

\n
\"Blue Whale, Killer Whale\".lastIndexOf(\"blue\"); // returns -1\n
\n
\n

Examples

\n

Using indexOf() and lastIndexOf()

\n
\n

The following example uses indexOf() and lastIndexOf() to locate values in the string \"Brave, Brave New World\".

\n

js

\n
const anyString = \"Brave, Brave New World\";\n\nconsole.log(anyString.indexOf(\"Brave\")); // 0\nconsole.log(anyString.lastIndexOf(\"Brave\")); // 7\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.lastindexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastIndexOf11216314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf\n

\n
\n", + "global_objects/string/padend": "

String.prototype.padEnd()

The padEnd() method of String values pads this string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of this string.

\n

Try it

\n

Syntax

\n
\n

js

\n
padEnd(targetLength)\npadEnd(targetLength, padString)\n
\n

Parameters

\n
targetLength

The length of the resulting string once the current str has been padded. If the value is less than or equal to str.length, the current string will be returned as-is.

\npadString Optional\n

The string to pad the current str with. If padString is too long to stay within targetLength, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is \" \" (U+0020).

Return value

\n

A String of the specified targetLength with the padString applied at the end of the current str.

Examples

\n

Using padEnd

\n
\n

js

\n
\"abc\".padEnd(10); // \"abc       \"\n\"abc\".padEnd(10, \"foo\"); // \"abcfoofoof\"\n\"abc\".padEnd(6, \"123456\"); // \"abc123\"\n\"abc\".padEnd(1); // \"abc\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.padend
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
padEnd571548No441057574843107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd\n

\n
\n", + "global_objects/string/padstart": "

String.prototype.padStart()

The padStart() method of String values pads this string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of this string.

\n

Try it

\n

Syntax

\n
\n

js

\n
padStart(targetLength)\npadStart(targetLength, padString)\n
\n

Parameters

\n
targetLength

The length of the resulting string once the current str has been padded. If the value is less than or equal to str.length, then str is returned as-is.

\npadString Optional\n

The string to pad the current str with. If padString is too long to stay within the targetLength, it will be truncated from the end. The default value is the unicode \"space\" character (U+0020).

Return value

\n

A String of the specified targetLength with padString applied from the start.

Examples

\n

Basic examples

\n
\n

js

\n
\"abc\".padStart(10); // \"       abc\"\n\"abc\".padStart(10, \"foo\"); // \"foofoofabc\"\n\"abc\".padStart(6, \"123465\"); // \"123abc\"\n\"abc\".padStart(8, \"0\"); // \"00000abc\"\n\"abc\".padStart(1); // \"abc\"\n
\n

Fixed width string number conversion

\n
\n

js

\n
// JavaScript version of: (unsigned)\n// printf \"%0*d\" width num\nfunction leftFillNum(num, targetLength) {\n  return num.toString().padStart(targetLength, \"0\");\n}\n\nconst num = 123;\nconsole.log(leftFillNum(num, 5)); // \"00123\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.padstart
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
padStart571548No441057574843107.01.08.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\n

\n
\n", + "global_objects/string/repeat": "

String.prototype.repeat()

The repeat() method of String values constructs and returns a new string which contains the specified number of copies of this string, concatenated together.

\n

Try it

\n

Syntax

\n
\n

js

\n
repeat(count)\n
\n

Parameters

\n
count

An integer between 0 and +Infinity, indicating the number of times to repeat the string.

Return value

\n

A new string containing the specified number of copies of the given string.

Exceptions

\n
RangeError

Thrown if count is negative or if count overflows maximum string length.

Examples

\n

Using repeat()

\n
\n

js

\n
\"abc\".repeat(-1); // RangeError\n\"abc\".repeat(0); // ''\n\"abc\".repeat(1); // 'abc'\n\"abc\".repeat(2); // 'abcabc'\n\"abc\".repeat(3.5); // 'abcabcabc' (count will be converted to integer)\n\"abc\".repeat(1 / 0); // RangeError\n\n({ toString: () => \"abc\", repeat: String.prototype.repeat }).repeat(2);\n// 'abcabc' (repeat() is a generic method)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.repeat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
repeat411224No2894136242893.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n

\n
\n", + "global_objects/string/replaceall": "

String.prototype.replaceAll()

The replaceAll() method of String values returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

\n

Try it

\n

Syntax

\n
\n

js

\n
replaceAll(pattern, replacement)\n
\n

Parameters

\n
pattern

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.

If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown.

replacement

Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace().

Return value

\n

A new string, with all matches of a pattern replaced by a replacement.

Exceptions

\n
TypeError

Thrown if the pattern is a regex that does not have the global (g) flag set (its flags property does not contain \"g\").

Description

\n
\n

This method does not mutate the string value it's called on. It returns a new string.

Unlike replace(), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.

\n

js

\n
function unsafeRedactName(text, name) {\n  return text.replace(new RegExp(name, \"g\"), \"[REDACTED]\");\n}\nfunction safeRedactName(text, name) {\n  return text.replaceAll(name, \"[REDACTED]\");\n}\n\nconst report =\n  \"A hacker called ha.*er used special characters in their name to breach the system.\";\n\nconsole.log(unsafeRedactName(report, \"ha.*er\")); // \"A [REDACTED]s in their name to breach the system.\"\nconsole.log(safeRedactName(report, \"ha.*er\")); // \"A hacker called [REDACTED] used special characters in their name to breach the system.\"\n
\n

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll(). In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).

If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.

\n

js

\n
\"xxx\".replaceAll(\"\", \"_\"); // \"_x_x_x_\"\n
\n

For more information about how regex properties (especially the sticky flag) interact with replaceAll(), see RegExp.prototype[@@replace]().

\n

Examples

\n

Using replaceAll()

\n
\n

js

\n
\"aabbcc\".replaceAll(\"b\", \".\");\n// 'aa..cc'\n
\n

Non-global regex throws

\n
\n

When using a regular expression search value, it must be global. This won't work:

\n

js

\n
\"aabbcc\".replaceAll(/b/, \".\");\n// TypeError: replaceAll must be called with a global RegExp\n
\n

This will work:

\n

js

\n
\"aabbcc\".replaceAll(/b/g, \".\");\n(\"aa..cc\");\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.replaceall
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
replaceAll858577No7113.18585796013.414.01.215.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll\n

\n
\n", + "global_objects/string/slice": "

String.prototype.slice()

The slice() method of String values extracts a section of this string and returns it as a new string, without modifying the original string.

\n

Try it

\n

Syntax

\n
\n

js

\n
slice(indexStart)\nslice(indexStart, indexEnd)\n
\n

Parameters

\n
indexStart

The index of the first character to include in the returned substring.

\nindexEnd Optional\n

The index of the first character to exclude from the returned substring.

Return value

\n

A new string containing the extracted section of the string.

Description

\n
\n

slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice() extracts up to but not including indexEnd. For example, str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

\n

Examples

\n

Using slice() to create a new string

\n
\n

The following example uses slice() to create a new string.

\n

js

\n
const str1 = \"The morning is upon us.\"; // The length of str1 is 23.\nconst str2 = str1.slice(1, 8);\nconst str3 = str1.slice(4, -2);\nconst str4 = str1.slice(12);\nconst str5 = str1.slice(30);\nconsole.log(str2); // he morn\nconsole.log(str3); // morning is upon u\nconsole.log(str4); // is upon us.\nconsole.log(str5); // \"\"\n
\n
\n

Using slice() with negative indexes

\n
\n

The following example uses slice() with negative indexes.

\n

js

\n
const str = \"The morning is upon us.\";\nstr.slice(-3); // 'us.'\nstr.slice(-3, -1); // 'us'\nstr.slice(0, -1); // 'The morning is upon us'\nstr.slice(4, -1); // 'morning is upon us'\n
\n

This example counts backwards from the end of the string by 11 to find the start index and forwards from the start of the string by 16 to find the end index.

\n

js

\n
console.log(str.slice(-11, 16)); // \"is u\"\n
\n

Here it counts forwards from the start by 11 to find the start index and backwards from the end by 7 to find the end index.

\n

js

\n
console.log(str.slice(11, -7)); // \" is u\"\n
\n

These arguments count backwards from the end by 5 to find the start index and backwards from the end by 1 to find the end index.

\n

js

\n
console.log(str.slice(-5, -1)); // \"n us\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.slice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
slice11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\n

\n
\n", + "global_objects/string/startswith": "

String.prototype.startsWith()

The startsWith() method of String values determines whether this string begins with the characters of a specified string, returning true or false as appropriate.

\n

Try it

\n

Syntax

\n
\n

js

\n
startsWith(searchString)\nstartsWith(searchString, position)\n
\n

Parameters

\n
searchString

The characters to be searched for at the start of this string. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes startsWith() to search for the string \"undefined\", which is rarely what you want.

\nposition Optional\n

The start position at which searchString is expected to be found (the index of searchString's first character). Defaults to 0.

Return value

\n

true if the given characters are found at the beginning of the string, including when searchString is an empty string; otherwise, false.

Exceptions

\n
TypeError

Thrown if searchString is a regex.

Description

\n

This method lets you determine whether or not a string begins with another string. This method is case-sensitive.

Examples

\n

Using startsWith()

\n
\n

js

\n
const str = \"To be, or not to be, that is the question.\";\n\nconsole.log(str.startsWith(\"To be\")); // true\nconsole.log(str.startsWith(\"not to be\")); // false\nconsole.log(str.startsWith(\"not to be\", 10)); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.startswith
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
startsWith411217No2893736172493.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n

\n
\n", + "global_objects/string/substr": "

String.prototype.substr()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The substr() method of String values returns a portion of this string, starting at the specified index and extending for a given number of characters afterwards.

Note: substr() is not part of the main ECMAScript specification — it's defined in Annex B: Additional ECMAScript Features for Web Browsers, which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard String.prototype.substring() and String.prototype.slice() methods instead to make their code maximally cross-platform friendly. The String.prototype.substring() page has some comparisons between the three methods.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
substr(start)\nsubstr(start, length)\n
\n

Parameters

\n
start

The index of the first character to include in the returned substring.

\nlength Optional\n

The number of characters to extract.

Return value

\n

A new string containing the specified part of the given string.

Description

\n
\n

A string's substr() method extracts length characters from the string, counting from the start index.

Although you are encouraged to avoid using substr(), there is no trivial way to migrate substr() to either slice() or substring() in legacy code without essentially writing a polyfill for substr(). For example, str.substr(a, l), str.slice(a, a + l), and str.substring(a, a + l) all have different results when str = \"01234\", a = 1, l = -2substr() returns an empty string, slice() returns \"123\", while substring() returns \"0\". The actual refactoring path depends on the knowledge of the range of a and l.

\n

Examples

\n

Using substr()

\n
\n

js

\n
const aString = \"Mozilla\";\n\nconsole.log(aString.substr(0, 1)); // 'M'\nconsole.log(aString.substr(1, 0)); // ''\nconsole.log(aString.substr(-1, 1)); // 'a'\nconsole.log(aString.substr(1, -1)); // ''\nconsole.log(aString.substr(-3)); // 'lla'\nconsole.log(aString.substr(1)); // 'ozilla'\nconsole.log(aString.substr(-20, 2)); // 'Mo'\nconsole.log(aString.substr(20, 2)); // ''\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.substr
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
substr11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr\n

\n
\n", + "global_objects/string/tolocaleuppercase": "

String.prototype.toLocaleUpperCase()

The toLocaleUpperCase() method of String values returns this string converted to upper case, according to any locale-specific case mappings.

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleUpperCase()\ntoLocaleUpperCase(locales)\n
\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

Unlike other methods that use the locales argument, toLocaleUpperCase() does not allow locale matching. Therefore, after checking the validity of the locales argument, toLocaleUpperCase() always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.

Return value

\n

A new string representing the calling string converted to upper case, according to any locale-specific case mappings.

Description

\n
\n

The toLocaleUpperCase() method returns the value of the string converted to upper case according to any locale-specific case mappings. toLocaleUpperCase() does not affect the value of the string itself. In most cases, this will produce the same result as toUpperCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.

Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return false: x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()

\n

Examples

\n

Using toLocaleUpperCase()

\n
\n

js

\n
\"alphabet\".toLocaleUpperCase(); // 'ALPHABET'\n\n\"Gesäß\".toLocaleUpperCase(); // 'GESÄSS'\n\n\"i\\u0307\".toLocaleUpperCase(\"lt-LT\"); // 'I'\n\nconst locales = [\"lt\", \"LT\", \"lt-LT\", \"lt-u-co-phonebk\", \"lt-x-lietuva\"];\n\"i\\u0307\".toLocaleUpperCase(locales); // 'I'\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.tolocaleuppercase
ECMAScript Internationalization API Specification
# sup-string.prototype.tolocaleuppercase
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleUpperCase11215.541.34.418410.111.01.00.10.0
locale5812556451058585542107.01.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase\n

\n
\n", + "global_objects/string/tostring": "

String.prototype.toString()

The toString() method of String values returns this string value.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the specified string value.

Description

\n
\n

The String object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For String values, the toString method returns the string itself (if it's a primitive) or the string that the String object wraps. It has the exact same implementation as String.prototype.valueOf().

The toString() method requires its this value to be a String primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to string values.

Because String doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a String object is used in a context expecting a string, such as in a template literal. However, String primitive values do not consult the toString() method to be coerced to strings — since they are already strings, no conversion is performed.

\n

js

\n
String.prototype.toString = () => \"Overridden\";\nconsole.log(`${\"foo\"}`); // \"foo\"\nconsole.log(`${new String(\"foo\")}`); // \"Overridden\"\n
\n
\n

Examples

\n

Using toString()

\n
\n

The following example displays the string value of a String object:

\n

js

\n
const x = new String(\"Hello world\");\n\nconsole.log(x.toString()); // \"Hello world\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString\n

\n
\n", + "global_objects/string/trim": "

String.prototype.trim()

\n

The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.

To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
trim()\n
\n

Parameters

\n

None.

Return value

\n
\n

A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.

If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str).

\n

Examples

\n

Using trim()

\n
\n

The following example trims whitespace from both ends of str.

\n

js

\n
const str = \"   foo  \";\nconsole.log(str.trim()); // 'foo'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.trim
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
trim4123.51010.55≤371841151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim\n

\n
\n", + "global_objects/string/trimend": "

String.prototype.trimEnd()

The trimEnd() method of String values removes whitespace from the end of this string and returns a new string, without modifying the original string. trimRight() is an alias of this method.

\n

Try it

\n

Syntax

\n
\n

js

\n
trimEnd()\n\ntrimRight()\n
\n

Parameters

\n

None.

Return value

\n
\n

A new string representing str stripped of whitespace from its end (right side). Whitespace is defined as white space characters plus line terminators.

If the end of str has no whitespace, a new string is still returned (essentially a copy of str).

\n

Aliasing

\n
\n

After trim() was standardized, engines also implemented the non-standard method trimRight. However, for consistency with padEnd(), when the method got standardized, its name was chosen as trimEnd. For web compatibility reasons, trimRight remains as an alias to trimEnd, and they refer to the exact same function object. In some engines this means:

\n

js

\n
String.prototype.trimRight.name === \"trimEnd\";\n
\n
\n

Examples

\n

Using trimEnd()

\n
\n

The following example trims whitespace from the end of str, but not from its start.

\n

js

\n
let str = \"   foo  \";\n\nconsole.log(str.length); // 8\n\nstr = str.trimEnd();\nconsole.log(str.length); // 6\nconsole.log(str); // '   foo'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.trimend
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
trimEnd6647912613.5No53151266≤3766186144714129.01.01.01.010.0.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd\n

\n
\n", + "global_objects/string/trimstart": "

String.prototype.trimStart()

The trimStart() method of String values removes whitespace from the beginning of this string and returns a new string, without modifying the original string. trimLeft() is an alias of this method.

\n

Try it

\n

Syntax

\n
\n

js

\n
trimStart()\n\ntrimLeft()\n
\n

Parameters

\n

None.

Return value

\n
\n

A new string representing str stripped of whitespace from its beginning (left side). Whitespace is defined as white space characters plus line terminators.

If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str).

\n

Aliasing

\n
\n

After trim() was standardized, engines also implemented the non-standard method trimLeft. However, for consistency with padStart(), when the method got standardized, its name was chosen as trimStart. For web compatibility reasons, trimLeft remains as an alias to trimStart, and they refer to the exact same function object. In some engines this means:

\n

js

\n
String.prototype.trimLeft.name === \"trimStart\";\n
\n
\n

Examples

\n

Using trimStart()

\n
\n

The following example trims whitespace from the start of str, but not from its end.

\n

js

\n
let str = \"   foo  \";\n\nconsole.log(str.length); // 8\n\nstr = str.trimStart();\nconsole.log(str.length); // 5\nconsole.log(str); // 'foo  '\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.trimstart
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
trimStart6647912613.5No53151266≤3766186144714129.01.01.01.010.0.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart\n

\n
\n", + "global_objects/string/anchor": "

String.prototype.anchor()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The anchor() method of String values creates a string that embeds this string in an <a> element with a name (<a name=\"...\">str</a>).

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

The HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup.

\n
\n

Syntax

\n
\n

js

\n
anchor(name)\n
\n

Parameters

\n
name

A string representing a name value to put into the generated <a name=\"...\"> start tag.

Return value

\n

A string beginning with an <a name=\"name\"> start tag (double quotes in name are replaced with &quot;), then the text str, and then an </a> end tag.

Examples

\n

Using anchor()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.anchor(\"hello\");\n
\n

This will create the following HTML:

\n

html

\n
<a name=\"hello\">Hello, world</a>\n
\n

Warning: This markup is invalid, because name is no longer a valid attribute of the <a> element.

Instead of using anchor() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"a\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.anchor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
anchor112
1Starting with version 17, the quotation mark (\") is replaced by its HTML reference character (\") in strings supplied for the name parameter.
No314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/anchor\n

\n
\n", + "global_objects/string/big": "

String.prototype.big()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The big() method of String values creates a string that embeds this string in a <big> element (<big>str</big>), which causes this string to be displayed in a big font.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of big(), the <big> element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

\n
\n

Syntax

\n
\n

js

\n
big()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <big> start tag, then the text str, and then a </big> end tag.

Examples

\n

Using big()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.big();\n
\n

This will create the following HTML:

\n

html

\n
<big>Hello, world</big>\n
\n

Warning: This markup is invalid, because big is no longer a valid element.

Instead of using big() and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate font-size through the element.style attribute:

\n

js

\n
document.getElementById(\"yourElemId\").style.fontSize = \"2em\";\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.big
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
big11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/big\n

\n
\n", + "global_objects/string/blink": "

String.prototype.blink()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The blink() method of String values creates a string that embeds this string in a <blink> element (<blink>str</blink>), which used to cause a string to blink in old browsers.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of blink(), the <blink> element itself is removed from modern browsers, and blinking text is frowned upon by several accessibility standards. Avoid using the element in any way.

\n
\n

Syntax

\n
\n

js

\n
blink()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <blink> start tag, then the text str, and then a </blink> end tag.

Examples

\n

Using blink()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.blink();\n
\n

This will create the following HTML:

\n

html

\n
<blink>Hello, world</blink>\n
\n

Warning: This markup is invalid, because blink is no longer a valid element.

You should avoid blinking elements altogether.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.blink
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
blink11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/blink\n

\n
\n", + "global_objects/string/bold": "

String.prototype.bold()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The bold() method of String values creates a string that embeds this string in a <b> element (<b>str</b>), which causes this string to be displayed as bold.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
bold()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <b> start tag, then the text str, and then a </b> end tag.

Examples

\n

Using bold()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.bold();\n
\n

This will create the following HTML:

\n

html

\n
<b>Hello, world</b>\n
\n

Instead of using bold() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"b\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.bold
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
bold11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold\n

\n
\n", + "global_objects/string/fixed": "

String.prototype.fixed()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The fixed() method of String values creates a string that embeds this string in a <tt> element (<tt>str</tt>), which causes this string to be displayed in a fixed-width font.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of fixed(), the <tt> element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

\n
\n

Syntax

\n
\n

js

\n
fixed()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <tt> start tag, then the text str, and then a </tt> end tag.

Examples

\n

Using fixed()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.fixed();\n
\n

This will create the following HTML:

\n

html

\n
<tt>Hello, world</tt>\n
\n

Warning: This markup is invalid, because tt is no longer a valid element.

Instead of using fixed() and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate font-family through the element.style attribute:

\n

js

\n
document.getElementById(\"yourElemId\").style.fontFamily = \"monospace\";\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.fixed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fixed11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fixed\n

\n
\n", + "global_objects/string/fontcolor": "

String.prototype.fontcolor()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The fontcolor() method of String values creates a string that embeds this string in a <font> element (<font color=\"...\">str</font>), which causes this string to be displayed in the specified font color.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of fontcolor(), the <font> element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

\n
\n

Syntax

\n
\n

js

\n
fontcolor(color)\n
\n

Parameters

\n
color

A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the CSS color reference.

Return value

\n

A string beginning with a <font color=\"color\"> start tag (double quotes in color are replaced with &quot;), then the text str, and then a </font> end tag.

Description

\n

The fontcolor() method itself simply joins the string parts together without any validation or normalization. However, to create valid <font> elements, if you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is \"FA8072\".

Examples

\n

Using fontcolor()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.fontcolor(\"red\");\n
\n

This will create the following HTML:

\n

html

\n
<font color=\"red\">Hello, world</font>\n
\n

Warning: This markup is invalid, because font is no longer a valid element.

Instead of using fontcolor() and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate color through the element.style attribute:

\n

js

\n
document.getElementById(\"yourElemId\").style.color = \"red\";\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.fontcolor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fontcolor11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fontcolor\n

\n
\n", + "global_objects/string/fontsize": "

String.prototype.fontsize()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The fontsize() method of String values creates a string that embeds this string in a <font> element (<font size=\"...\">str</font>), which causes this string to be displayed in the specified font size.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of fontsize(), the <font> element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

\n
\n

Syntax

\n
\n

js

\n
fontsize(size)\n
\n

Parameters

\n
size

An integer between 1 and 7, or a string representing a signed integer between 1 and 7.

Return value

\n

A string beginning with a <font size=\"size\"> start tag (double quotes in size are replaced with &quot;), then the text str, and then a </font> end tag.

Description

\n

The fontsize() method itself simply joins the string parts together without any validation or normalization. However, to create valid <font> elements, When you specify size as an integer, you set the font size of str to one of the 7 defined sizes. You can specify size as a string such as \"-2\" or \"+3\" to adjust the font size of str relative to 3, the default value.

Examples

\n

Using fontsize()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.fontsize(7);\n
\n

This will create the following HTML:

\n

html

\n
<font size=\"7\">Hello, world</font>\n
\n

Warning: This markup is invalid, because font is no longer a valid element.

Instead of using fontsize() and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate font-size through the element.style attribute:

\n

js

\n
document.getElementById(\"yourElemId\").style.fontSize = \"7pt\";\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.fontsize
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fontsize11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fontsize\n

\n
\n", + "global_objects/string/italics": "

String.prototype.italics()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The italics() method of String values creates a string that embeds this string in an <i> element (<i>str</i>), which causes this string to be displayed as italic.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
italics()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with an <i> start tag, then the text str, and then an </i> end tag.

Examples

\n

Using italics()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.italics();\n
\n

This will create the following HTML:

\n

html

\n
<i>Hello, world</i>\n
\n

Instead of using italics() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"i\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.italics
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
italics11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/italics\n

\n
\n", + "global_objects/string/link": "

String.prototype.link()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The link() method of String values creates a string that embeds this string in an <a> element (<a href=\"...\">str</a>), to be used as a hypertext link to another URL.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
link(url)\n
\n

Parameters

\n
url

Any string that specifies the href attribute of the <a> element; it should be a valid URL (relative or absolute), with any & characters escaped as &amp;.

Return value

\n

A string beginning with an <a href=\"url\"> start tag (double quotes in url are replaced with &quot;), then the text str, and then an </a> end tag.

Examples

\n

Using link()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"MDN Web Docs\";\n\ndocument.body.innerHTML = contentString.link(\"https://developer.mozilla.org/\");\n
\n

This will create the following HTML:

\n

html

\n
<a href=\"https://developer.mozilla.org/\">MDN Web Docs</a>\n
\n

Instead of using link() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"MDN Web Docs\";\nconst elem = document.createElement(\"a\");\nelem.href = \"https://developer.mozilla.org/\";\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.link
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
link11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/link\n

\n
\n", + "global_objects/string/small": "

String.prototype.small()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The small() method of String values creates a string that embeds this string in a <small> element (<small>str</small>), which causes this string to be displayed in a small font.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
small()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <small> start tag, then the text str, and then a </small> end tag.

Examples

\n

Using small()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.small();\n
\n

This will create the following HTML:

\n

html

\n
<small>Hello, world</small>\n
\n

Instead of using small() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"small\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.small
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
small11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/small\n

\n
\n", + "global_objects/string/strike": "

String.prototype.strike()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The strike() method of String values creates a string that embeds this string in a <strike> element (<strike>str</strike>), which causes this string to be displayed as struck-out text.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of strike(), the <strike> element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use the <del> for deleted content or the <s> for content that is no longer accurate or no longer relevant instead.

\n
\n

Syntax

\n
\n

js

\n
strike()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <strike> start tag, then the text str, and then a </strike> end tag.

Examples

\n

Using strike()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.strike();\n
\n

This will create the following HTML:

\n

html

\n
<strike>Hello, world</strike>\n
\n

Warning: This markup is invalid, because strike is no longer a valid element.

Instead of using strike() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"s\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.strike
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
strike11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/strike\n

\n
\n", + "global_objects/string/sub": "

String.prototype.sub()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The sub() method of String values creates a string that embeds this string in a <sub> element (<sub>str</sub>), which causes this string to be displayed as subscript.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
sub()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <sub> start tag, then the text str, and then a </sub> end tag.

Examples

\n

Using sub()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.sub();\n
\n

This will create the following HTML:

\n

html

\n
<sub>Hello, world</sub>\n
\n

Instead of using sub() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"sub\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.sub
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sub11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/sub\n

\n
\n", + "global_objects/string/sup": "

String.prototype.sup()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The sup() method of String values creates a string that embeds this string in a <sup> element (<sup>str</sup>), which causes this string to be displayed as superscript.

Note: All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as document.createElement() instead.

\n
\n

Syntax

\n
\n

js

\n
sup()\n
\n

Parameters

\n

None.

Return value

\n

A string beginning with a <sup> start tag, then the text str, and then a </sup> end tag.

Examples

\n

Using sup()

\n
\n

The code below creates an HTML string and then replaces the document's body with it:

\n

js

\n
const contentString = \"Hello, world\";\n\ndocument.body.innerHTML = contentString.sup();\n
\n

This will create the following HTML:

\n

html

\n
<sup>Hello, world</sup>\n
\n

Instead of using sup() and creating HTML text directly, you should use DOM APIs such as document.createElement(). For example:

\n

js

\n
const contentString = \"Hello, world\";\nconst elem = document.createElement(\"sup\");\nelem.innerText = contentString;\ndocument.body.appendChild(elem);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-string.prototype.sup
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sup11213314.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/sup\n

\n
\n", + "regular_expressions": "

Regular expressions

\n

A regular expression (regex for short) allow developers to match strings against a pattern, extract submatch information, or simply test if the string conforms to that pattern. Regular expressions are used in many programming languages, and JavaScript's syntax is inspired by Perl.

You are encouraged to read the regular expressions guide to get an overview of the available regex syntaxes and how they work.

\n
\n

Description

\n
\n

Regular expressions are a important concept in formal language theory. They are a way to describe a possibly infinite set of character strings (called a language). A regular expression, at its core, needs the following features:

Assuming a finite alphabet (such as the 26 letters of the English alphabet, or the entire Unicode character set), all regular languages can be generated by the features above. Of course, many patterns are very tedious to express this way (such as \"10 digits\" or \"a character that's not a space\"), so JavaScript regular expressions include many shorthands, introduced below.

Note: JavaScript regular expressions are in fact not regular, due to the existence of backreferences (regular expressions must have finite states). However, they are still a very useful feature.

\n

Creating regular expressions

\n
\n

A regular expression is typically created as a literal by enclosing a pattern in forward slashes (/):

\n

js

\n
const regex1 = /ab+c/g;\n
\n

Regular expressions can also be created with the RegExp() constructor:

\n

js

\n
const regex2 = new RegExp(\"ab+c\", \"g\");\n
\n

They have no runtime differences, although they may have implications on performance, static analyzability, and authoring ergonomic issues with escaping characters. For more information, see the RegExp reference.

\n

Regex flags

\n
\n

Flags are special parameters that can change the way a regular expression is interpreted or the way it interacts with the input text. Each flag corresponds to one accessor property on the RegExp object.

Flag Description Corresponding property
d Generate indices for substring matches. hasIndices
g Global search. global
i Case-insensitive search. ignoreCase
m Allows ^ and $ to match newline characters. multiline
s Allows . to match newline characters. dotAll
u \"Unicode\"; treat a pattern as a sequence of Unicode code points. unicode
v An upgrade to the u mode with more Unicode features. unicodeSets
y Perform a \"sticky\" search that matches starting at the current position in the target string. sticky

The sections below list all available regex syntaxes, grouped by their syntactic nature.

\n

Assertions

\n
\n

Assertions are constructs that test whether the string meets a certain condition at the specified position, but not consume characters. Assertions cannot be quantified.

Input boundary assertion: ^, $

Asserts that the current position is the start or end of input, or start or end of a line if the m flag is set.

Lookahead assertion: (?=...), (?!...)

Asserts that the current position is followed or not followed by a certain pattern.

Lookbehind assertion: (?<=...), (?<!...)

Asserts that the current position is preceded or not preceded by a certain pattern.

Word boundary assertion: \\b, \\B

Asserts that the current position is a word boundary.

\n

Atoms

\n
\n

Atoms are the most basic units of a regular expression. Each atom consumes one or more characters in the string, and either fails the match or allows the pattern to continue matching with the next atom.

Backreference: \\1, \\2

Matches a previously matched subpattern captured with a capturing group.

Capturing group: (...)

Matches a subpattern and remembers information about the match.

Character class: [...], [^...]

Matches any character in or not in a set of characters. When the v flag is enabled, it can also be used to match finite-length strings.

Character class escape: \\d, \\D, \\w, \\W, \\s, \\S

Matches any character in or not in a predefined set of characters.

Character escape: \\n, \\u{...}

Matches a character that may not be able to be conveniently represented in its literal form.

Literal character: a, b

Matches a specific character.

Named backreference: \\k<name>

Matches a previously matched subpattern captured with a named capturing group.

Named capturing group: (?<name>...)

Matches a subpattern and remembers information about the match. The group can later be identified by a custom name instead of by its index in the pattern.

Non-capturing group: (?:...)

Matches a subpattern without remembering information about the match.

Unicode character class escape: \\p{...}, \\P{...}

Matches a set of characters specified by a Unicode property. When the v flag is enabled, it can also be used to match finite-length strings.

Wildcard: .

Matches any character except line terminators, unless the s flag is set.

\n

Other features

\n
\n

These features do not specify any pattern themselves, but are used to compose patterns.

Disjunction: |

Matches any of a set of alternatives separated by the | character.

Quantifier: *, +, ?, {n}, {n,}, {n,m}

Matches an atom a certain number of times.

\n

Escape sequences

\n
\n

Escape sequences in regexes refer to any kind of syntax formed by \\ followed by one or more characters. They may serve very different purposes depending on what follow \\. Below is a list of all valid \"escape sequences\":

Escape sequence Followed by Meaning
\\B None Non-word-boundary assertion
\\D None \nCharacter class escape representing non-digit characters
\\P \n{, a Unicode property and/or value, then }\n \nUnicode character class escape representing characters without the specified Unicode property
\\S None \nCharacter class escape representing non-white-space characters
\\W None \nCharacter class escape representing non-word characters
\\b None \nWord boundary assertion; inside character classes, represents U+0008 (BACKSPACE)
\\c A letter from A to Z or a to z\n A character escape representing the control character with value equal to the letter's character value modulo 32
\\d None \nCharacter class escape representing digit characters (0 to 9)
\\f None \nCharacter escape representing U+000C (FORM FEED)
\\k \n<, an identifier, then >\n A named backreference\n
\\n None \nCharacter escape representing U+000A (LINE FEED)
\\p \n{, a Unicode property and/or value, then }\n \nUnicode character class escape representing characters with the specified Unicode property
\\q \n{, a string, then a }\n Only valid inside v-mode character classes; represents the string to be matched literally
\\r None \nCharacter escape representing U+000D (CARRIAGE RETURN)
\\s None \nCharacter class escape representing whitespace characters
\\t None \nCharacter escape representing U+0009 (CHARACTER TABULATION)
\\u 4 hexadecimal digits; or {, 1 to 6 hexadecimal digits, then }\n \nCharacter escape representing the character with the given code point
\\v None \nCharacter escape representing U+000B (LINE TABULATION)
\\w None \nCharacter class escape representing word characters (A to Z, a to z, 0 to 9, _)
\\x 2 hexadecimal digits \nCharacter escape representing the character with the given value
\\0 None \nCharacter escape representing U+0000 (NULL)

\\ followed by any other digit character becomes a legacy octal escape sequence, which is forbidden in Unicode-aware mode.

In addition, \\ can be followed by some non-letter-or-digit characters, in which case the escape sequence is always a character escape representing the escaped character itself:

The other ASCII characters, namely space character, \", ', _, and any letter character not mentioned above, are not valid escape sequences. In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \\a represents the character a. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.

\n

Specifications

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# prod-DecimalEscape
ECMAScript Language Specification
# prod-Atom
ECMAScript Language Specification
# prod-CharacterClass
ECMAScript Language Specification
# prod-CharacterClassEscape
ECMAScript Language Specification
# prod-CharacterEscape
ECMAScript Language Specification
# prod-Disjunction
ECMAScript Language Specification
# prod-Assertion
ECMAScript Language Specification
# prod-PatternCharacter
ECMAScript Language Specification
# prod-AtomEscape
ECMAScript Language Specification
# prod-Quantifier
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
backreference11214514.418410.111.01.00.10.0
capturing_group11214514.418410.111.01.00.10.0
character_class11214514.418410.111.01.00.10.0
character_class_escape11214514.418410.111.01.00.10.0
character_escape11214514.418410.111.01.00.10.0
disjunction11214514.418410.111.01.00.10.0
input_boundary_assertion11214514.418410.111.01.00.10.0
literal_character11214514.418410.111.01.00.10.0
lookahead_assertion11214514.418410.111.01.00.10.0
lookbehind_assertion627978No4916.46262794616.48.01.08.10.0
named_backreference647978No5111.16464794711.39.01.010.0.0
named_capturing_group647978No5111.16464794711.39.01.010.0.0
non_capturing_group11214514.418410.111.01.00.10.0
quantifier11214514.418410.111.01.00.10.0
unicode_character_class_escape647978No5111.16464794711.39.01.010.0.0
wildcard11214514.418410.111.01.00.10.0
word_boundary_assertion11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions\n

\n
\n", + "global_objects/regexp/@@replace": "

RegExp.prototype[@@replace]()

The [@@replace]() method of RegExp instances specifies how String.prototype.replace() and String.prototype.replaceAll() should behave when the regular expression is passed in as the pattern.

\n

Try it

\n

Syntax

\n
\n

js

\n
regexp[Symbol.replace](str, replacement)\n
\n

Parameters

\n
str

A String that is a target of the replacement.

replacement

Can be a string or a function.

  • If it's a string, it will replace the substring matched by the current regexp. A number of special replacement patterns are supported; see the Specifying a string as the replacement section of String.prototype.replace.
  • If it's a function, it will be invoked for every match and the return value is used as the replacement text. The arguments supplied to this function are described in the Specifying a function as the replacement section of String.prototype.replace.

Return value

\n

A new string, with one, some, or all matches of the pattern replaced by the specified replacement.

Description

\n
\n

This method is called internally in String.prototype.replace() and String.prototype.replaceAll() if the pattern argument is a RegExp object. For example, the following two examples return the same result.

\n

js

\n
\"abc\".replace(/a/, \"A\");\n\n/a/[Symbol.replace](\"abc\", \"A\");\n
\n

If the regex is global (with the g flag), the regex's exec() method will be repeatedly called until exec() returns null. Otherwise, exec() would only be called once. For each exec() result, the substitution will be prepared based on the description in String.prototype.replace().

Because @@replace would keep calling exec() until it returns null, and exec() would automatically reset the regex's lastIndex to 0 when the last match fails, @@replace would typically not have side effects when it exits. However, when the regex is sticky but not global, lastIndex would not be reset. In this case, each call to replace() may return a different result.

\n

js

\n
const re = /a/y;\n\nfor (let i = 0; i < 5; i++) {\n  console.log(\"aaa\".replace(re, \"b\"), re.lastIndex);\n}\n\n// baa 1\n// aba 2\n// aab 3\n// aaa 0\n// baa 1\n
\n

When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the lastIndex.

\n

js

\n
console.log(\"aa-a\".replace(/a/gy, \"b\")); // \"bb-a\"\n
\n

If the current match is an empty string, the lastIndex would still be advanced — if the regex is Unicode-aware, it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.

\n

js

\n
console.log(\"😄\".replace(/(?:)/g, \" \")); // \" \\ud83d \\ude04 \"\nconsole.log(\"😄\".replace(/(?:)/gu, \" \")); // \" 😄 \"\n
\n

This method exists for customizing replace behavior in RegExp subclasses.

\n

Examples

\n

Direct call

\n
\n

This method can be used in almost the same way as String.prototype.replace(), except the different this and the different arguments order.

\n

js

\n
const re = /-/g;\nconst str = \"2016-01-01\";\nconst newstr = re[Symbol.replace](str, \".\");\nconsole.log(newstr); // 2016.01.01\n
\n
\n

Using @@replace in subclasses

\n
\n

Subclasses of RegExp can override the [@@replace]() method to modify the default behavior.

\n

js

\n
class MyRegExp extends RegExp {\n  constructor(pattern, flags, count) {\n    super(pattern, flags);\n    this.count = count;\n  }\n  [Symbol.replace](str, replacement) {\n    // Perform @@replace |count| times.\n    let result = str;\n    for (let i = 0; i < this.count; i++) {\n      result = RegExp.prototype[Symbol.replace].call(this, result, replacement);\n    }\n    return result;\n  }\n}\n\nconst re = new MyRegExp(\"\\\\d\", \"\", 3);\nconst str = \"01234567\";\nconst newstr = str.replace(re, \"#\"); // String.prototype.replace calls re[@@replace].\nconsole.log(newstr); // ###34567\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype-@@replace
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@replace507949No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace\n

\n
\n", + "global_objects/regexp/global": "

RegExp.prototype.global

The global accessor property of RegExp instances returns whether or not the g flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.global has the value true if the g flag was used; otherwise, false. The g flag indicates that the regular expression should be tested against all possible matches in a string. Each call to exec() will update its lastIndex property, so that the next call to exec() will start at the next character.

Some methods, such as String.prototype.matchAll() and String.prototype.replaceAll(), will validate that, if the parameter is a regex, it is global. The regex's @@match and @@replace methods (called by String.prototype.match() and String.prototype.replace()) would also have different behaviors when the regex is global.

The set accessor of global is undefined. You cannot change this property directly.

\n

Examples

\n

Using global

\n
\n

js

\n
const regex = /foo/g;\nconsole.log(regex.global); // true\n\nconst str = \"fooexamplefoo\";\nconst str1 = str.replace(regex, \"\");\nconsole.log(str1); // example\n\nconst regex1 = /foo/;\nconst str2 = str.replace(regex1, \"\");\nconsole.log(str2); // examplefoo\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.global
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
global11215.5514.418410.111.01.00.10.0
prototype_accessor4812385.5351.34848383515.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global\n

\n
\n", + "global_objects/regexp/regexp": "

RegExp() constructor

\n

The RegExp() constructor creates RegExp objects.

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new RegExp(pattern)\nnew RegExp(pattern, flags)\nRegExp(pattern)\nRegExp(pattern, flags)\n
\n

Note: RegExp() can be called with or without new, but sometimes with different effects. See Return value.

\n

Parameters

\n
pattern

The text of the regular expression. This can also be another RegExp object.

\nflags Optional\n

If specified, flags is a string that contains the flags to add. Alternatively, if a RegExp object is supplied for the pattern, the flags string will replace any of that object's flags (and lastIndex will be reset to 0).

flags may contain any combination of the following characters:

d (indices)

Generate indices for substring matches.

g (global)

Find all matches rather than stopping after the first match.

i (ignore case)

When matching, casing differences are ignored.

m (multiline)

Treat beginning and end assertions (^ and $) as working over multiple lines. In other words, match the beginning or end of each line (delimited by \\n or \\r), not only the very beginning or end of the whole input string.

s (dotAll)

Allows . to match newlines.

u (unicode)

Treat pattern as a sequence of Unicode code points.

v (unicodeSets)

An upgrade to the u flag that enables set notation in character classes as well as properties of strings.

y (sticky)

Matches only from the index indicated by the lastIndex property of this regular expression in the target string. Does not attempt to match from any later indexes.

Return value

\n
\n

RegExp(pattern) returns pattern directly if all of the following are true:

In all other cases, calling RegExp() with or without new both create a new RegExp object. If pattern is a regex, the new object's source is pattern.source; otherwise, its source is pattern coerced to a string. If the flags parameter is not undefined, the new object's flags is the parameter's value; otherwise, its flags is pattern.flags (if pattern is a regex).

\n

Exceptions

\n
SyntaxError

Thrown in one of the following cases:

  • \npattern cannot be parsed as a valid regular expression.
  • \nflags contains repeated characters or any character outside of those allowed.

Examples

\n

Literal notation and constructor

\n
\n

There are two ways to create a RegExp object: a literal notation and a constructor.

The following three expressions create the same regular expression:

\n

js

\n
/ab+c/i;\nnew RegExp(/ab+c/, \"i\"); // literal notation\nnew RegExp(\"ab+c\", \"i\"); // constructor\n
\n

Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. There are two ways to compile and get a RegExp object.

The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the RegExp object, new RegExp('ab+c'), results in runtime compilation of the regular expression.

Use a string as the first argument to the RegExp() constructor when you want to build the regular expression from dynamic input.

\n

Building a regular expression from dynamic inputs

\n
\n

js

\n
const breakfasts = [\"bacon\", \"eggs\", \"oatmeal\", \"toast\", \"cereal\"];\nconst order = \"Let me get some bacon and eggs, please\";\n\norder.match(new RegExp(`\\\\b(${breakfasts.join(\"|\")})\\\\b`, \"g\"));\n// Returns ['bacon', 'eggs']\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
RegExp11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp\n

\n
\n", + "global_objects/regexp/tostring": "

RegExp.prototype.toString()

The toString() method of RegExp instances returns a string representing this regular expression.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the given object.

Description

\n
\n

The RegExp object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For RegExp objects, the toString() method returns a string representation of the regular expression.

In practice, it reads the regex's source and flags properties and returns a string in the form /source/flags. The toString() return value is guaranteed to be a parsable regex literal, although it may not be the exact same text as what was originally specified for the regex (for example, the flags may be reordered).

\n

Examples

\n

Using toString()

\n
\n

The following example displays the string value of a RegExp object:

\n

js

\n
const myExp = new RegExp(\"a+b+c\");\nconsole.log(myExp.toString()); // '/a+b+c/'\n\nconst foo = new RegExp(\"bar\", \"g\");\nconsole.log(foo.toString()); // '/bar/g'\n
\n
\n

Empty regular expressions and escaping

\n
\n

Since toString() accesses the source property, an empty regular expression returns the string \"/(?:)/\", and line terminators such as \\n are escaped. This makes the returned value always a valid regex literal.

\n

js

\n
new RegExp().toString(); // \"/(?:)/\"\n\nnew RegExp(\"\\n\").toString() === \"/\\\\n/\"; // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString11214514.418410.111.01.00.10.0
escaping731238960673733852611.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/toString\n

\n
\n", + "global_objects/regexp/n": "

RegExp.$1, …, RegExp.$9

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.$1, …, RegExp.$9 static accessor properties return parenthesized substring matches.

\n
\n

Description

\n
\n

Because $1$9 are static properties of RegExp, you always use them as RegExp.$1, RegExp.$2, etc., rather than as properties of a RegExp object you created.

The values of $1, …, $9 update whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, or if the last match does not have the corresponding capturing group, the respective property is an empty string. The set accessor of each property is undefined, so you cannot change the properties directly.

The number of possible parenthesized substrings is unlimited, but the RegExp object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.

$1, …, $9 can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp.$n legacy properties.

\n

Examples

\n

Using $n with RegExp.prototype.test()

\n
\n

The following script uses the RegExp.prototype.test() method to grab a number in a generic string.

\n

js

\n
const str = \"Test 24\";\nconst number = /(\\d+)/.test(str) ? RegExp.$1 : \"0\";\nnumber; // \"24\"\n
\n

Please note that any operation involving the usage of other regular expressions between a re.test(str) call and the RegExp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.

\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
n11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n\n

\n
\n", + "global_objects/regexp/input": "

RegExp.input ($_)

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.input static accessor property returns the string against which a regular expression is matched. RegExp.$_ is an alias for this property.

\n
\n

Description

\n
\n

Because input is a static property of RegExp, you always use it as RegExp.input or RegExp.$_, rather than as a property of a RegExp object you created.

The value of input updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, input is an empty string. You can set the value of input, but this does not affect other behaviors of the regex, and the value will be overwritten again when the next successful match is made.

\n

Examples

\n

Using input and $_

\n
\n

js

\n
const re = /hi/g;\nre.test(\"hi there!\");\nRegExp.input; // \"hi there!\"\nre.test(\"foo\"); // new test, non-matching\nRegExp.$_; // \"hi there!\"\nre.test(\"hi world!\"); // new test, matching\nRegExp.$_; // \"hi world!\"\n
\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
input11215.51534.41841411.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/input\n

\n
\n", + "global_objects/regexp/lastmatch": "

RegExp.lastMatch ($&)

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.lastMatch static accessor property returns the last matched substring. RegExp[\"$&\"] is an alias for this property.

\n
\n

Description

\n
\n

Because lastMatch is a static property of RegExp, you always use it as RegExp.lastMatch or RegExp[\"$&\"], rather than as a property of a RegExp object you created.

The value of lastMatch updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, lastMatch is an empty string. The set accessor of lastMatch is undefined, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (RegExp.$&), because & is not a valid identifier part, so this causes a SyntaxError. Use the bracket notation instead.

$& can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp[\"$&\"] legacy property.

\n

Examples

\n

Using lastMatch and $&

\n
\n

js

\n
const re = /hi/g;\nre.test(\"hi there!\");\nRegExp.lastMatch; // \"hi\"\nRegExp[\"$&\"]; // \"hi\"\n
\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastMatch11215.510.534.41841111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastMatch\n

\n
\n", + "global_objects/regexp/lastparen": "

RegExp.lastParen ($+)

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.lastParen static accessor property returns the last parenthesized substring match, if any. RegExp[\"$+\"] is an alias for this property.

\n
\n

Description

\n
\n

Because lastParen is a static property of RegExp, you always use it as RegExp.lastParen or RegExp[\"$+\"], rather than as a property of a RegExp object you created.

The value of lastParen updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, or if the most recent regex execution contains no capturing groups, lastParen is an empty string. The set accessor of lastParen is undefined, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (RegExp.$+), because + is not a valid identifier part, so this causes a SyntaxError. Use the bracket notation instead.

\n

Examples

\n

Using lastParen and $+

\n
\n

js

\n
const re = /(hi)/g;\nre.test(\"hi there!\");\nRegExp.lastParen; // \"hi\"\nRegExp[\"$+\"]; // \"hi\"\n
\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastParen11215.510.534.41841111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastParen\n

\n
\n", + "global_objects/regexp/leftcontext": "

RegExp.leftContext ($`)

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.leftContext static accessor property returns the substring preceding the most recent match. RegExp[\"$`\"] is an alias for this property.

\n
\n

Description

\n
\n

Because leftContext is a static property of RegExp, you always use it as RegExp.leftContext or RegExp[\"$`\"], rather than as a property of a RegExp object you created.

The value of leftContext updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, leftContext is an empty string. The set accessor of leftContext is undefined, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (RegExp.$` ), because ` is not a valid identifier part, so this causes a SyntaxError. Use the bracket notation instead.

$` can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp[\"$`\"] legacy property.

\n

Examples

\n

Using leftContext and $`

\n
\n

js

\n
const re = /world/g;\nre.test(\"hello world!\");\nRegExp.leftContext; // \"hello \"\nRegExp[\"$`\"]; // \"hello \"\n
\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
leftContext11215.5834.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/leftContext\n

\n
\n", + "global_objects/regexp/rightcontext": "

RegExp.rightContext ($')

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: All RegExp static properties that expose the last match state globally are deprecated. See deprecated RegExp features for more information.

The RegExp.rightContext static accessor property returns the substring following the most recent match. RegExp[\"$'\"] is an alias for this property.

\n
\n

Description

\n
\n

Because rightContext is a static property of RegExp, you always use it as RegExp.rightContext or RegExp[\"$'\"], rather than as a property of a RegExp object you created.

The value of rightContext updates whenever a RegExp (but not a RegExp subclass) instance makes a successful match. If no matches have been made, rightContext is an empty string. The set accessor of rightContext is undefined, so you cannot change this property directly.

You cannot use the shorthand alias with the dot property accessor (RegExp.$'), because ' is not a valid identifier part, so this causes a SyntaxError. Use the bracket notation instead.

$' can also be used in the replacement string of String.prototype.replace(), but that's unrelated to the RegExp[\"$'\"] legacy property.

\n

Examples

\n

Using rightContext and $'

\n
\n

js

\n
const re = /hello/g;\nre.test(\"hello world!\");\nRegExp.rightContext; // \" world!\"\nRegExp[\"$'\"]; // \" world!\"\n
\n

Specifications

\n
\n\n\n
Specification
Legacy RegExp features
# additional-properties-of-the-regexp-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
rightContext11215.5834.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/rightContext\n

\n
\n", + "global_objects/regexp/@@species": "

RegExp[@@species]

\n

The RegExp[@@species] static accessor property returns the constructor used to construct copied regular expressions in certain RegExp methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
RegExp[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct copied RegExp instances.

Description

\n
\n

The @@species accessor property returns the default constructor for RegExp objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass RegExp {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubRegExp extends SubRegExp {}\nSubRegExp[Symbol.species] === SubRegExp; // true\n
\n

Some RegExp methods create a copy of the current regex instance before running exec(), so that side effects such as changes to lastIndex are not retained. The @@species property is used to determine the constructor of the new instance. The methods that copy the current regex instance are:

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the RegExp constructor for RegExp objects:

\n

js

\n
RegExp[Symbol.species]; // function RegExp()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom RegExp subclass, such as MyRegExp, the MyRegExp species is the MyRegExp constructor. However, you might want to overwrite this, in order to return parent RegExp objects in your derived class methods:

\n

js

\n
class MyRegExp extends RegExp {\n  // Overwrite MyRegExp species to the parent RegExp constructor\n  static get [Symbol.species]() {\n    return RegExp;\n  }\n}\n
\n

Or you can use this to observe the copying process:

\n

js

\n
class MyRegExp extends RegExp {\n  constructor(...args) {\n    console.log(\"Creating a new MyRegExp instance with args:\", args);\n    super(...args);\n  }\n  static get [Symbol.species]() {\n    console.log(\"Copying MyRegExp\");\n    return this;\n  }\n  exec(value) {\n    console.log(\"Executing with lastIndex:\", this.lastIndex);\n    return super.exec(value);\n  }\n}\n\nArray.from(\"aabbccdd\".matchAll(new MyRegExp(\"[ac]\", \"g\")));\n// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]\n// Copying MyRegExp\n// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]\n// Executing with lastIndex: 0\n// Executing with lastIndex: 1\n// Executing with lastIndex: 2\n// Executing with lastIndex: 5\n// Executing with lastIndex: 6\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species501349No371050504937105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@species\n

\n
\n", + "global_objects/regexp/dotall": "

RegExp.prototype.dotAll

The dotAll accessor property of RegExp instances returns whether or not the s flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.dotAll has the value true if the s flag was used; otherwise, false. The s flag indicates that the dot special character (.) should additionally match the following line terminator (\"newline\") characters in a string, which it would not match otherwise:

This effectively means the dot will match any character on the Unicode Basic Multilingual Plane (BMP). To allow it to match astral characters, the u (unicode) flag should be used. Using both flags in conjunction allows the dot to match any Unicode character, without exceptions.

The set accessor of dotAll is undefined. You cannot change this property directly.

\n

Examples

\n

Using dotAll

\n
\n

js

\n
const str1 = \"bar\\nexample foo example\";\n\nconst regex1 = /bar.example/s;\n\nconsole.log(regex1.dotAll); // true\n\nconsole.log(str1.replace(regex1, \"\")); // foo example\n\nconst str2 = \"bar\\nexample foo example\";\n\nconst regex2 = /bar.example/;\n\nconsole.log(regex2.dotAll); // false\n\nconsole.log(str2.replace(regex2, \"\"));\n// bar\n// example foo example\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.dotAll
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
dotAll627978No4911.16262794611.38.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll\n

\n
\n", + "global_objects/regexp/flags": "

RegExp.prototype.flags

The flags accessor property of RegExp instances returns the flags of this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.flags has a string as its value. Flags in the flags property are sorted alphabetically (from left to right, e.g. \"dgimsuvy\"). It actually invokes the other flag accessors (hasIndices, global, etc.) one-by-one and concatenates the results.

All built-in functions read the flags property instead of reading individual flag accessors.

The set accessor of flags is undefined. You cannot change this property directly.

\n

Examples

\n

Using flags

\n
\n

js

\n
/foo/ig.flags; // \"gi\"\n/bar/myu.flags; // \"muy\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.flags
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
flags497937No3994949374195.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags\n

\n
\n", + "global_objects/regexp/hasindices": "

RegExp.prototype.hasIndices

The hasIndices accessor property of RegExp instances returns whether or not the d flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.hasIndices has the value true if the d flag was used; otherwise, false. The d flag indicates that the result of a regular expression match should contain the start and end indices of the substrings of each capture group. It does not change the regex's interpretation or matching behavior in any way, but only provides additional information in the matching result.

This flag primarily affects the return value of exec(). If the d flag is present, the array returned by exec() has an additional indices property as described in the exec() method's return value. Because all other regex-related methods (such as String.prototype.match()) call exec() internally, they will also return the indices if the regex has the d flag.

The set accessor of hasIndices is undefined. You cannot change this property directly.

\n

Examples

\n

There's a more detailed usage example at Groups and backreferences > Using groups and match indices.

Using hasIndices

\n
\n

js

\n
const str1 = \"foo bar foo\";\n\nconst regex1 = /foo/dg;\n\nconsole.log(regex1.hasIndices); // true\n\nconsole.log(regex1.exec(str1).indices[0]); // [0, 3]\nconsole.log(regex1.exec(str1).indices[0]); // [8, 11]\n\nconst str2 = \"foo bar foo\";\n\nconst regex2 = /foo/;\n\nconsole.log(regex2.hasIndices); // false\n\nconsole.log(regex2.exec(str2).indices); // undefined\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.hasIndices
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hasIndices909088No7615909088641515.01.816.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices\n

\n
\n", + "global_objects/regexp/ignorecase": "

RegExp.prototype.ignoreCase

The ignoreCase accessor property of RegExp instances returns whether or not the i flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.ignoreCase has the value true if the i flag was used; otherwise, false. The i flag indicates that case should be ignored while attempting a match in a string. Case-insensitive matching is done by mapping both the expected character set and the matched string to the same casing.

If the regex is Unicode-aware, the case mapping happens through simple case folding specified in CaseFolding.txt. The mapping always maps to a single code point, so it does not map, for example, ß (U+00DF LATIN SMALL LETTER SHARP S) to ss (which is full case folding, not simple case folding). It may however map code points outside the Basic Latin block to code points within it — for example, ſ (U+017F LATIN SMALL LETTER LONG S) case-folds to s (U+0073 LATIN SMALL LETTER S) and (U+212A KELVIN SIGN) case-folds to k (U+006B LATIN SMALL LETTER K). Therefore, ſ and can be matched by /[a-z]/ui.

If the regex is Unicode-unaware, case mapping uses the Unicode Default Case Conversion — the same algorithm used in String.prototype.toUpperCase(). For example, (U+2126 OHM SIGN) and Ω (U+03A9 GREEK CAPITAL LETTER OMEGA) are both mapped by Default Case Conversion to themselves but by simple case folding to ω (U+03C9 GREEK SMALL LETTER OMEGA), so \"ω\" is matched by /[\\u2126]/ui and /[\\u03a9]/ui but not by /[\\u2126]/i or /[\\u03a9]/i. This algorithm prevents code points outside the Basic Latin block to be mapped to code points within it, so ſ and mentioned previously are not matched by /[a-z]/i.

The set accessor of ignoreCase is undefined. You cannot change this property directly.

\n

Examples

\n

Using ignoreCase

\n
\n

js

\n
const regex = /foo/i;\n\nconsole.log(regex.ignoreCase); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.ignorecase
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ignoreCase11215.5514.418410.111.01.00.10.0
prototype_accessor4812385.5351.34848383515.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase\n

\n
\n", + "global_objects/regexp/multiline": "

RegExp.prototype.multiline

The multiline accessor property of RegExp instances returns whether or not the m flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.multiline has the value true if the m flag was used; otherwise, false. The m flag indicates that a multiline input string should be treated as multiple lines. For example, if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.

The set accessor of multiline is undefined. You cannot change this property directly.

\n

Examples

\n

Using multiline

\n
\n

js

\n
const regex = /foo/m;\n\nconsole.log(regex.multiline); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.multiline
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
multiline11215.5514.418410.111.01.00.10.0
prototype_accessor4812385.5351.34848383515.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline\n

\n
\n", + "global_objects/regexp/source": "

RegExp.prototype.source

The source accessor property of RegExp instances returns a string containing the source text of this regular expression, without the two forward slashes on both sides or any flags.

\n

Try it

\n

Description

\n

Conceptually, the source property is the text between the two forward slashes in the regular expression literal. The language requires the returned string to be properly escaped, so that when the source is concatenated with a forward slash on both ends, it would form a parsable regex literal. For example, for new RegExp(\"/\"), the source is \\\\/, because if it generates /, the resulting literal becomes ///, which is a line comment. Similarly, all line terminators will be escaped because line terminator characters would break up the regex literal. There's no requirement for other characters, as long as the result is parsable. For empty regular expressions, the string (?:) is returned.

Examples

\n

Using source

\n
\n

js

\n
const regex = /fooBar/gi;\n\nconsole.log(regex.source); // \"fooBar\", doesn't contain /.../ and \"gi\".\n
\n

Empty regular expressions and escaping

\n
\n

js

\n
new RegExp().source; // \"(?:)\"\n\nnew RegExp(\"\\n\").source === \"\\\\n\"; // true, starting with ES5\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.source
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
source11214514.418410.111.01.00.10.0
empty_regex_string61238No155≤371838144.21.01.00.10.0
escaping7312381060673733852611.01.012.0.0
prototype_accessor4812414351.34848413515.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source\n

\n
\n", + "global_objects/regexp/sticky": "

RegExp.prototype.sticky

The sticky accessor property of RegExp instances returns whether or not the y flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.sticky has the value true if the y flag was used; otherwise, false. The y flag indicates that the regex attempts to match the target string only from the index indicated by the lastIndex property (and unlike a global regex, does not attempt to match from any later indexes).

The set accessor of sticky is undefined. You cannot change this property directly.

For both sticky regexes and global regexes:

However, for the exec() method, the behavior when matching fails is different:

For the exec() method, a regex that's both sticky and global behaves the same as a sticky and non-global regex. Because test() is a simple wrapper around exec(), test() would ignore the global flag and perform sticky matches as well. However, due to many other methods special-casing the behavior of global regexes, the global flag is, in general, orthogonal to the sticky flag.

\n

Examples

\n

Using a regular expression with the sticky flag

\n
\n

js

\n
const str = \"#foo#\";\nconst regex = /foo/y;\n\nregex.lastIndex = 1;\nregex.test(str); // true\nregex.lastIndex = 5;\nregex.test(str); // false (lastIndex is taken into account with sticky flag)\nregex.lastIndex; // 0 (reset after match failure)\n
\n

Anchored sticky flag

\n
\n

For several versions, Firefox's SpiderMonkey engine had a bug with regard to the ^ assertion and the sticky flag which allowed expressions starting with the ^ assertion and using the sticky flag to match when they shouldn't. The bug was introduced some time after Firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. Perhaps because of the bug, the specification specifically calls out the fact that:

Even when the y flag is used with a pattern, ^ always matches only at the beginning of Input, or (if rer.[[Multiline]] is true) at the beginning of a line.

Examples of correct behavior:

\n

js

\n
const regex = /^foo/y;\nregex.lastIndex = 2;\nregex.test(\"..foo\"); // false - index 2 is not the beginning of the string\n\nconst regex2 = /^foo/my;\nregex2.lastIndex = 2;\nregex2.test(\"..foo\"); // false - index 2 is not the beginning of the string or line\nregex2.lastIndex = 2;\nregex2.test(\".\\nfoo\"); // true - index 2 is the beginning of a line\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.sticky
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sticky49133No36104949436105.01.06.0.0
anchored_sticky_flag491344No361049494436105.01.06.0.0
prototype_accessor491338No361049493836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky\n

\n
\n", + "global_objects/regexp/unicode": "

RegExp.prototype.unicode

The unicode accessor property of RegExp instances returns whether or not the u flag is used with this regular expression.

\n

Try it

\n

Description

\n
\n

RegExp.prototype.unicode has the value true if the u flag was used; otherwise, false. The u flag enables various Unicode-related features. With the \"u\" flag:

There are other changes to the parsing behavior that prevent possible syntax mistakes (which are analogous to strict mode for regex syntax). These syntaxes are all deprecated and only kept for web compatibility, and you should not rely on them.

The set accessor of unicode is undefined. You cannot change this property directly.

\n

Unicode-aware mode

\n
\n

When we refer to Unicode-aware mode, we mean the regex has either the u or the v flag, in which case the regex enables Unicode-related features (such as Unicode character class escape) and has much stricter syntax rules. Because u and v interpret the same regex in incompatible ways, using both flags results in a SyntaxError.

Similarly, a regex is Unicode-unaware if it has neither the u nor the v flag. In this case, the regex is interpreted as a sequence of UTF-16 code units, and there are many legacy syntaxes that do not become syntax errors.

\n

Examples

\n

Using the unicode property

\n
\n

js

\n
const regex = /\\u{61}/u;\n\nconsole.log(regex.unicode); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.unicode
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unicode50
12Case folding is implemented in version 13
46No371050504637105.01.0
6.0.0Case folding is implemented in version 8.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode\n

\n
\n", + "global_objects/regexp/unicodesets": "

RegExp.prototype.unicodeSets

The unicodeSets accessor property of RegExp instances returns whether or not the v flag is used with this regular expression.

\n

Description

\n
\n

RegExp.prototype.unicodeSets has the value true if the v flag was used; otherwise, false. The v flag is an \"upgrade\" to the u flag that enables more Unicode-related features. (\"v\" is the next letter after \"u\" in the alphabet.) Because u and v interpret the same regex in incompatible ways, using both flags results in a SyntaxError. With the v flag, you get all features mentioned in the u flag description, plus:

Some valid u-mode regexes become invalid in v-mode. Specifically, the character class syntax is different and some characters can no longer appear literally. For more information, see v-mode character class.

Note: The v mode does not interpret grapheme clusters as single characters; they are still multiple code points. For example, /[🇺🇳]/v is still able to match \"🇺\".

The set accessor of unicodeSets is undefined. You cannot change this property directly.

\n

Examples

\n

Using the unicodeSets property

\n
\n

js

\n
const regex = /[\\p{Script_Extensions=Greek}&&\\p{Letter}]/v;\n\nconsole.log(regex.unicodeSets); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-regexp.prototype.unicodesets
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unicodeSets112112116No9817112112116No17No1.3220.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets\n

\n
\n", + "global_objects/regexp/lastindex": "

RegExp: lastIndex

The lastIndex data property of a RegExp instance specifies the index at which to start the next match.

\n

Try it

\n

Value

\n
\n

A non-negative integer.

\n
Property attributes of RegExp: lastIndex\n
Writable yes
Enumerable no
Configurable no
\n

Description

\n
\n

This property is set only if the regular expression instance used the g flag to indicate a global search, or the y flag to indicate a sticky search. The following rules apply when exec() is called on a given input:

Other regex-related methods, such as RegExp.prototype.test(), String.prototype.match(), String.prototype.replace(), etc., call exec() under the hood, so they have different effects on lastIndex. See their respective pages for details.

\n

Examples

\n

Using lastIndex

\n
\n

Consider the following sequence of statements:

\n

js

\n
const re = /(hi)?/g;\n
\n

Matches the empty string.

\n

js

\n
console.log(re.exec(\"hi\"));\nconsole.log(re.lastIndex);\n
\n

Returns [\"hi\", \"hi\"] with lastIndex equal to 2.

\n

js

\n
console.log(re.exec(\"hi\"));\nconsole.log(re.lastIndex);\n
\n

Returns [\"\", undefined], an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex was 2 (and still is 2) and hi has length 2.

\n

Using lastIndex with sticky regexes

\n
\n

The lastIndex property is writable. You can set it to make the regex start its next search at a given index.

The y flag almost always requires setting lastIndex. It always matches strictly at lastIndex and does not attempt any later positions. This is usually useful for writing parsers, when you want to match tokens only at the current position.

\n

js

\n
const stringPattern = /\"[^\"]*\"/y;\nconst input = `const message = \"Hello world\";`;\n\nstringPattern.lastIndex = 6;\nconsole.log(stringPattern.exec(input)); // null\n\nstringPattern.lastIndex = 16;\nconsole.log(stringPattern.exec(input)); // ['\"Hello world\"']\n
\n
\n

Rewinding lastIndex

\n
\n

The g flag also benefits from setting lastIndex. One common use case is when the string is modified in the middle of a global search. In this case, we may miss a particular match if the string is shortened. We can avoid this by rewinding lastIndex.

\n

js

\n
const mdLinkPattern = /\\[[^[\\]]+\\]\\((?<link>[^()\\s]+)\\)/dg;\n\nfunction resolveMDLink(line) {\n  let match;\n  let modifiedLine = line;\n  while ((match = mdLinkPattern.exec(modifiedLine))) {\n    const originalLink = match.groups.link;\n    const resolvedLink = originalLink.replaceAll(/^files|\\/index\\.md$/g, \"\");\n    modifiedLine =\n      modifiedLine.slice(0, match.indices.groups.link[0]) +\n      resolvedLink +\n      modifiedLine.slice(match.indices.groups.link[1]);\n    // Rewind the pattern to the end of the resolved link\n    mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length;\n  }\n  return modifiedLine;\n}\n\nconsole.log(\n  resolveMDLink(\n    \"[`lastIndex`](files/en-us/web/javascript/reference/global_objects/regexp/lastindex/index.md)\",\n  ),\n); // [`lastIndex`](/en-us/web/javascript/reference/global_objects/regexp/lastindex)\nconsole.log(\n  resolveMDLink(\n    \"[`ServiceWorker`](files/en-us/web/api/serviceworker/index.md) and [`SharedWorker`](files/en-us/web/api/sharedworker/index.md)\",\n  ),\n); // [`ServiceWorker`](/en-us/web/api/serviceworker) and [`SharedWorker`](/en-us/web/api/sharedworker)\n
\n

Try deleting the mdLinkPattern.lastIndex += resolvedLink.length - originalLink.length line and running the second example. You will find that the second link is not replaced correctly, because the lastIndex is already past the link's index after the string is shortened.

Warning: This example is for demonstration only. To deal with Markdown, you should probably use a parsing library instead of regex.

\n

Optimizing searching

\n
\n

You can optimize searching by setting lastIndex to a point where previous possible occurrences can be ignored. For example, instead of this:

\n

js

\n
const stringPattern = /\"[^\"]*\"/g;\nconst input = `const message = \"Hello \" + \"world\";`;\n\n// Pretend we've already dealt with the previous parts of the string\nlet offset = 26;\nconst remainingInput = input.slice(offset);\nconst nextString = stringPattern.exec(remainingInput);\nconsole.log(nextString[0]); // \"world\"\noffset += nextString.index + nextString.length;\n
\n

Consider this:

\n

js

\n
stringPattern.lastIndex = offset;\nconst nextString = stringPattern.exec(remainingInput);\nconsole.log(nextString[0]); // \"world\"\noffset = stringPattern.lastIndex;\n
\n

This is potentially more performant because we avoid string slicing.

\n

Avoiding side effects

\n
\n

The side effects caused by exec() can be confusing, especially if the input is different for each exec().

\n

js

\n
const re = /foo/g;\nconsole.log(re.test(\"foo bar\")); // true\nconsole.log(re.test(\"foo baz\")); // false, because lastIndex is non-zero\n
\n

This is even more confusing when you are hand-modifying lastIndex. To contain the side effects, remember to reset lastIndex after each input is completely processed.

\n

js

\n
const re = /foo/g;\nconsole.log(re.test(\"foo bar\")); // true\nre.lastIndex = 0;\nconsole.log(re.test(\"foo baz\")); // true\n
\n

With some abstraction, you can require lastIndex to be set to a particular value before each exec() call.

\n

js

\n
function createMatcher(pattern) {\n  // Create a copy, so that the original regex is never updated\n  const regex = new RegExp(pattern, \"g\");\n  return (input, offset) => {\n    regex.lastIndex = offset;\n    return regex.exec(input);\n  };\n}\n\nconst matchFoo = createMatcher(/foo/);\nconsole.log(matchFoo(\"foo bar\", 0)[0]); // \"foo\"\nconsole.log(matchFoo(\"foo baz\", 0)[0]); // \"foo\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-properties-of-regexp-instances
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastIndex11215.5514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex\n

\n
\n", + "global_objects/regexp/compile": "

RegExp.prototype.compile()

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: The compile() method is only specified for compatibility reasons. Using compile() causes the otherwise immutable regex source and flags to become mutable, which may break user expectations. You can use the RegExp() constructor to construct a new regular expression object instead.

The compile() method of RegExp instances is used to recompile a regular expression with new source and flags after the RegExp object has already been created.

\n
\n

Syntax

\n
\n

js

\n
compile(pattern, flags)\n
\n

Parameters

\n
pattern

The text of the regular expression.

flags

Any combination of flag values.

Return value

\n

None (undefined).

Examples

\n

Using compile()

\n
\n

The following example shows how to recompile a regular expression with a new pattern and a new flag.

\n

js

\n
const regexObj = new RegExp(\"foo\", \"gi\");\nregexObj.compile(\"new foo\", \"g\");\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype.compile
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
compile1121463.14.418410.121.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/compile\n

\n
\n", + "global_objects/regexp/test": "

RegExp.prototype.test()

\n

The test() method of RegExp instances executes a search with this regular expression for a match between a regular expression and a specified string. Returns true if there is a match; false otherwise.

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
test(str)\n
\n

Parameters

\n
str

The string against which to match the regular expression. All values are coerced to strings, so omitting it or passing undefined causes test() to search for the string \"undefined\", which is rarely what you want.

Return value

\n

true if there is a match between the regular expression and the string str. Otherwise, false.

Description

\n
\n

Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method (which returns the index of a match, or -1 if not found).

To get more information (but with slower execution), use the exec() method. (This is similar to the String.prototype.match() method.)

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

\n

Examples

\n

Using test()

\n
\n

Simple example that tests if \"hello\" is contained at the very beginning of a string, returning a boolean result.

\n

js

\n
const str = \"hello world!\";\nconst result = /^hello/.test(str);\n\nconsole.log(result); // true\n
\n

The following example logs a message which depends on the success of the test:

\n

js

\n
function testInput(re, str) {\n  const midstring = re.test(str) ? \"contains\" : \"does not contain\";\n  console.log(`${str}${midstring}${re.source}`);\n}\n
\n
\n

Using test() on a regex with the \"global\" flag

\n
\n

When a regex has the global flag set, test() will advance the lastIndex of the regex. (RegExp.prototype.exec() also advances the lastIndex property.)

Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time test() returns true.

Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!

When test() returns false, the calling regex's lastIndex property will reset to 0.

The following example demonstrates this behavior:

\n

js

\n
const regex = /foo/g; // the \"global\" flag is set\n\n// regex.lastIndex is at 0\nregex.test(\"foo\"); // true\n\n// regex.lastIndex is now at 3\nregex.test(\"foo\"); // false\n\n// regex.lastIndex is at 0\nregex.test(\"barfoo\"); // true\n\n// regex.lastIndex is at 6\nregex.test(\"foobar\"); // false\n\n// regex.lastIndex is at 0\nregex.test(\"foobarfoo\"); // true\n\n// regex.lastIndex is at 3\nregex.test(\"foobarfoo\"); // true\n\n// regex.lastIndex is at 9\nregex.test(\"foobarfoo\"); // false\n\n// regex.lastIndex is at 0\n// (...and so on)\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype.test
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
test11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test\n

\n
\n", + "global_objects/regexp/@@match": "

RegExp.prototype[@@match]()

The [@@match]() method of RegExp instances specifies how String.prototype.match() should behave. In addition, its presence (or absence) can influence whether an object is regarded as a regular expression.

\n

Try it

\n

Syntax

\n
\n

js

\n
regexp[Symbol.match](str)\n
\n

Parameters

\n
str

A String that is a target of the match.

Return value

\n
\n

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

\n

Description

\n
\n

This method is called internally in String.prototype.match().

For example, the following two examples return same result.

\n

js

\n
\"abc\".match(/a/);\n\n/a/[Symbol.match](\"abc\");\n
\n

If the regex is global (with the g flag), the regex's exec() method will be repeatedly called until exec() returns null. Otherwise, exec() would only be called once and its result becomes the return value of @@match.

Because @@match would keep calling exec() until it returns null, and exec() would automatically reset the regex's lastIndex to 0 when the last match fails, @@match would typically not have side effects when it exits. However, when the regex is sticky but not global, lastIndex would not be reset. In this case, each call to match() may return a different result.

\n

js

\n
const re = /[abc]/y;\nfor (let i = 0; i < 5; i++) {\n  console.log(\"abc\".match(re), re.lastIndex);\n}\n// [ 'a' ] 1\n// [ 'b' ] 2\n// [ 'c' ] 3\n// null 0\n// [ 'a' ] 1\n
\n

When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the lastIndex.

\n

js

\n
console.log(\"ab-c\".match(/[abc]/gy)); // [ 'a', 'b' ]\n
\n

If the current match is an empty string, the lastIndex would still be advanced — if the regex is Unicode-aware, it would advance by one Unicode code point; otherwise, it advances by one UTF-16 code unit.

\n

js

\n
console.log(\"😄\".match(/(?:)/g)); // [ '', '', '' ]\nconsole.log(\"😄\".match(/(?:)/gu)); // [ '', '' ]\n
\n

This method exists for customizing match behavior within RegExp subclasses.

In addition, the @@match property is used to check whether an object is a regular expression.

\n

Examples

\n

Direct call

\n
\n

This method can be used in almost the same way as String.prototype.match(), except the different this and the different arguments order.

\n

js

\n
const re = /[0-9]+/g;\nconst str = \"2016-01-02\";\nconst result = re[Symbol.match](str);\nconsole.log(result); // [\"2016\", \"01\", \"02\"]\n
\n
\n

Using @@match in subclasses

\n
\n

Subclasses of RegExp can override the [@@match]() method to modify the default behavior.

\n

js

\n
class MyRegExp extends RegExp {\n  [Symbol.match](str) {\n    const result = RegExp.prototype[Symbol.match].call(this, str);\n    if (!result) return null;\n    return {\n      group(n) {\n        return result[n];\n      },\n    };\n  }\n}\n\nconst re = new MyRegExp(\"([0-9]+)-([0-9]+)-([0-9]+)\");\nconst str = \"2016-01-02\";\nconst result = str.match(re); // String.prototype.match calls re[@@match].\nconsole.log(result.group(1)); // 2016\nconsole.log(result.group(2)); // 01\nconsole.log(result.group(3)); // 02\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype-@@match
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@match501349No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match\n

\n
\n", + "global_objects/regexp/@@matchall": "

RegExp.prototype[@@matchAll]()

The [@@matchAll]() method of RegExp instances specifies how String.prototype.matchAll should behave.

\n

Try it

\n

Syntax

\n
\n

js

\n
regexp[Symbol.matchAll](str)\n
\n

Parameters

\n
str

A String that is a target of the match.

Return value

\n

An iterable iterator object (which is not restartable) of matches. Each match is an array with the same shape as the return value of RegExp.prototype.exec().

Description

\n
\n

This method is called internally in String.prototype.matchAll(). For example, the following two examples return the same result.

\n

js

\n
\"abc\".matchAll(/a/g);\n\n/a/g[Symbol.matchAll](\"abc\");\n
\n

Like @@split, @@matchAll starts by using @@species to construct a new regex, thus avoiding mutating the original regexp in any way. lastIndex starts as the original regex's value.

\n

js

\n
const regexp = /[a-c]/g;\nregexp.lastIndex = 1;\nconst str = \"abc\";\nArray.from(str.matchAll(regexp), (m) => `${regexp.lastIndex}${m[0]}`);\n// [ \"1 b\", \"1 c\" ]\n
\n

The validation that the input is a global regex happens in String.prototype.matchAll(). @@matchAll does not validate the input. If the regex is not global, the returned iterator yields the exec() result once and then returns undefined. If the regexp is global, each time the returned iterator's next() method is called, the regex's exec() is called and the result is yielded.

When the regex is sticky and global, it will still perform sticky matches — i.e. it will not match any occurrences beyond the lastIndex.

\n

js

\n
console.log(Array.from(\"ab-c\".matchAll(/[abc]/gy)));\n// [ [ \"a\" ], [ \"b\" ] ]\n
\n

If the current match is an empty string, the lastIndex will still be advanced. If the regex has the u flag, it advances by one Unicode code point; otherwise, it advances by one UTF-16 code point.

\n

js

\n
console.log(Array.from(\"😄\".matchAll(/(?:)/g)));\n// [ [ \"\" ], [ \"\" ], [ \"\" ] ]\n\nconsole.log(Array.from(\"😄\".matchAll(/(?:)/gu)));\n// [ [ \"\" ], [ \"\" ] ]\n
\n

This method exists for customizing the behavior of matchAll() in RegExp subclasses.

\n

Examples

\n

Direct call

\n
\n

This method can be used in almost the same way as String.prototype.matchAll(), except for the different value of this and the different order of arguments.

\n

js

\n
const re = /[0-9]+/g;\nconst str = \"2016-01-02\";\nconst result = re[Symbol.matchAll](str);\n\nconsole.log(Array.from(result, (x) => x[0]));\n// [ \"2016\", \"01\", \"02\" ]\n
\n
\n

Using @@matchAll in subclasses

\n
\n

Subclasses of RegExp can override the [@@matchAll]() method to modify the default behavior.

For example, to return an Array instead of an iterator:

\n

js

\n
class MyRegExp extends RegExp {\n  [Symbol.matchAll](str) {\n    const result = RegExp.prototype[Symbol.matchAll].call(this, str);\n    return result ? Array.from(result) : null;\n  }\n}\n\nconst re = new MyRegExp(\"([0-9]+)-([0-9]+)-([0-9]+)\", \"g\");\nconst str = \"2016-01-02|2019-03-07\";\nconst result = str.matchAll(re);\n\nconsole.log(result[0]);\n// [ \"2016-01-02\", \"2016\", \"01\", \"02\" ]\n\nconsole.log(result[1]);\n// [ \"2019-03-07\", \"2019\", \"03\", \"07\" ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp-prototype-matchall
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@matchAll737967No601373736752135.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll\n

\n
\n", + "global_objects/regexp/@@search": "

RegExp.prototype[@@search]()

The [@@search]() method of RegExp instances specifies how String.prototype.search should behave.

\n

Try it

\n

Syntax

\n
\n

js

\n
regexp[Symbol.search](str)\n
\n

Parameters

\n
str

A String that is a target of the search.

Return value

\n

The index of the first match between the regular expression and the given string, or -1 if no match was found.

Description

\n
\n

This method is called internally in String.prototype.search(). For example, the following two examples return the same result.

\n

js

\n
\"abc\".search(/a/);\n\n/a/[Symbol.search](\"abc\");\n
\n

This method does not copy the regular expression, unlike @@split or @@matchAll. However, unlike @@match or @@replace, it will set lastIndex to 0 when execution starts and restore it to the previous value when it exits, therefore generally avoiding side effects. This means that the g flag has no effect with this method, and it always returns the first match in the string even when lastIndex is non-zero. This also means sticky regexps will always search strictly at the beginning of the string.

\n

js

\n
const re = /[abc]/g;\nre.lastIndex = 2;\nconsole.log(\"abc\".search(re)); // 0\n\nconst re2 = /[bc]/y;\nre2.lastIndex = 1;\nconsole.log(\"abc\".search(re2)); // -1\nconsole.log(\"abc\".match(re2)); // [ 'b' ]\n
\n

@@search always calls the regex's exec() method exactly once, and returns the index property of the result, or -1 if the result is null.

This method exists for customizing the search behavior in RegExp subclasses.

\n

Examples

\n

Direct call

\n
\n

This method can be used in almost the same way as String.prototype.search(), except for the different value of this and the different arguments order.

\n

js

\n
const re = /-/g;\nconst str = \"2016-01-02\";\nconst result = re[Symbol.search](str);\nconsole.log(result); // 4\n
\n
\n

Using @@search in subclasses

\n
\n

Subclasses of RegExp can override [@@search]() method to modify the behavior.

\n

js

\n
class MyRegExp extends RegExp {\n  constructor(str) {\n    super(str);\n    this.pattern = str;\n  }\n  [Symbol.search](str) {\n    return str.indexOf(this.pattern);\n  }\n}\n\nconst re = new MyRegExp(\"a+b\");\nconst str = \"ab a+b\";\nconst result = str.search(re); // String.prototype.search calls re[@@search].\nconsole.log(result); // 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype-@@search
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@search501349No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search\n

\n
\n", + "global_objects/regexp/@@split": "

RegExp.prototype[@@split]()

The [@@split]() method of RegExp instances specifies how String.prototype.split should behave when the regular expression is passed in as the separator.

\n

Try it

\n

Syntax

\n
\n

js

\n
regexp[Symbol.split](str)\nregexp[Symbol.split](str, limit)\n
\n

Parameters

\n
str

The target of the split operation.

\nlimit Optional\n

Integer specifying a limit on the number of splits to be found. The [@@split]() method still splits on every match of this RegExp pattern (or, in the Syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern.

Return value

\n

An Array containing substrings as its elements. Capturing groups are included.

Description

\n
\n

This method is called internally in String.prototype.split() when a RegExp is passed as the separator. For example, the following two examples return the same result.

\n

js

\n
\"a-b-c\".split(/-/);\n\n/-/[Symbol.split](\"a-b-c\");\n
\n

This method exists for customizing the behavior of split() in RegExp subclasses.

The RegExp.prototype[@@split]() base method exhibits the following behaviors:

\n

Examples

\n

Direct call

\n
\n

This method can be used in almost the same way as String.prototype.split(), except the different this and the different order of arguments.

\n

js

\n
const re = /-/g;\nconst str = \"2016-01-02\";\nconst result = re[Symbol.split](str);\nconsole.log(result); // [\"2016\", \"01\", \"02\"]\n
\n
\n

Using @@split in subclasses

\n
\n

Subclasses of RegExp can override the [@@split]() method to modify the default behavior.

\n

js

\n
class MyRegExp extends RegExp {\n  [Symbol.split](str, limit) {\n    const result = RegExp.prototype[Symbol.split].call(this, str, limit);\n    return result.map((x) => `(${x})`);\n  }\n}\n\nconst re = new MyRegExp(\"-\");\nconst str = \"2016-01-02\";\nconst result = str.split(re); // String.prototype.split calls re[@@split].\nconsole.log(result); // [\"(2016)\", \"(01)\", \"(02)\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-regexp.prototype-@@split
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@split507949No371050504937105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split\n

\n
\n", + "regular_expressions/unicode_character_class_escape": "

Unicode character class escape: \\p{...}, \\P{...}

A unicode character class escape is a kind of character class escape that matches a set of characters specified by a Unicode property. It's only supported in Unicode-aware mode. When the v flag is enabled, it can also be used to match finite-length strings.

\n

Try it

\n

Syntax

\n
\n

regex

\n
\\p{loneProperty}\n\\P{loneProperty}\n\n\\p{property=value}\n\\P{property=value}\n
\n

Parameters

\n
loneProperty

A lone Unicode property name or value, following the same syntax as value. It specifies the value for the General_Category property, or a binary property name. In v mode, it can also be a binary Unicode property of strings.

Note: ICU syntax allows omitting the Script property name as well, but JavaScript does not support this, because most of the time Script_Extensions is more useful than Script.

property

A Unicode property name. Must be made of ASCII letters (A–Z, a–z) and underscores (_), and must be one of the non-binary property names.

value

A Unicode property value. Must be made of ASCII letters (A–Z, a–z), underscores (_), and digits (0–9), and must be one of the supported values listed in PropertyValueAliases.txt.

Description

\n
\n

\\p and \\P are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the p or P character.

Every Unicode character has a set of properties that describe it. For example, the character a has the General_Category property with value Lowercase_Letter, and the Script property with value Latn. The \\p and \\P escape sequences allow you to match a character based on its properties. For example, a can be matched by \\p{Lowercase_Letter} (the General_Category property name is optional) as well as \\p{Script=Latn}. \\P creates a complement class that consists of code points without the specified property.

To compose multiple properties, use the character set intersection syntax enabled with the v flag, or see pattern subtraction and intersection.

In v mode, \\p may match a sequence of code points, defined in Unicode as \"properties of strings\". This is most useful for emojis, which are often composed of multiple code points. However, \\P can only complement character properties.

Note: There are plans to port the properties of strings feature to u mode as well.

\n

Examples

\n

General categories

\n
\n

General categories are used to classify Unicode characters and subcategories are available to define a more precise categorization. It is possible to use both short or long forms in Unicode property escapes.

They can be used to match letters, numbers, symbols, punctuations, spaces, etc. For a more exhaustive list of general categories, please refer to the Unicode specification.

\n

js

\n
// finding all the letters of a text\nconst story = \"It's the Cheshire Cat: now I shall have somebody to talk to.\";\n\n// Most explicit form\nstory.match(/\\p{General_Category=Letter}/gu);\n\n// It is not mandatory to use the property name for General categories\nstory.match(/\\p{Letter}/gu);\n\n// This is equivalent (short alias):\nstory.match(/\\p{L}/gu);\n\n// This is also equivalent (conjunction of all the subcategories using short aliases)\nstory.match(/\\p{Lu}|\\p{Ll}|\\p{Lt}|\\p{Lm}|\\p{Lo}/gu);\n
\n
\n

Scripts and script extensions

\n
\n

Some languages use different scripts for their writing system. For instance, English and Spanish are written using the Latin script while Arabic and Russian are written with other scripts (respectively Arabic and Cyrillic). The Script and Script_Extensions Unicode properties allow regular expression to match characters according to the script they are mainly used with (Script) or according to the set of scripts they belong to (Script_Extensions).

For example, A belongs to the Latin script and ε to the Greek script.

\n

js

\n
const mixedCharacters = \"aεЛ\";\n\n// Using the canonical \"long\" name of the script\nmixedCharacters.match(/\\p{Script=Latin}/u); // a\n\n// Using a short alias (ISO 15924 code) for the script\nmixedCharacters.match(/\\p{Script=Grek}/u); // ε\n\n// Using the short name sc for the Script property\nmixedCharacters.match(/\\p{sc=Cyrillic}/u); // Л\n
\n

For more details, refer to the Unicode specification, the Scripts table in the ECMAScript specification, and the ISO 15924 list of script codes.

If a character is used in a limited set of scripts, the Script property will only match for the \"predominant\" used script. If we want to match characters based on a \"non-predominant\" script, we could use the Script_Extensions property (Scx for short).

\n

js

\n
// ٢ is the digit 2 in Arabic-Indic notation\n// while it is predominantly written within the Arabic script\n// it can also be written in the Thaana script\n\n\"٢\".match(/\\p{Script=Thaana}/u);\n// null as Thaana is not the predominant script\n\n\"٢\".match(/\\p{Script_Extensions=Thaana}/u);\n// [\"٢\", index: 0, input: \"٢\", groups: undefined]\n
\n
\n

Unicode property escapes vs. character classes

\n
\n

With JavaScript regular expressions, it is also possible to use character classes and especially \\w or \\d to match letters or digits. However, such forms only match characters from the Latin script (in other words, a to z and A to Z for \\w and 0 to 9 for \\d). As shown in this example, it might be a bit clumsy to work with non Latin texts.

Unicode property escapes categories encompass much more characters and \\p{Letter} or \\p{Number} will work for any script.

\n

js

\n
// Trying to use ranges to avoid \\w limitations:\n\nconst nonEnglishText = \"Приключения Алисы в Стране чудес\";\nconst regexpBMPWord = /([\\u0000-\\u0019\\u0021-\\uFFFF])+/gu;\n// BMP goes through U+0000 to U+FFFF but space is U+0020\n\nconsole.table(nonEnglishText.match(regexpBMPWord));\n\n// Using Unicode property escapes instead\nconst regexpUPE = /\\p{L}+/gu;\nconsole.table(nonEnglishText.match(regexpUPE));\n
\n
\n

Matching prices

\n
\n

The following example matches prices in a string:

\n

js

\n
function getPrices(str) {\n  // Sc stands for \"currency symbol\"\n  return [...str.matchAll(/\\p{Sc}\\s*[\\d.,]+/gu)].map((match) => match[0]);\n}\n\nconst str = `California rolls $6.99\nCrunchy rolls $8.49\nShrimp tempura $10.99`;\nconsole.log(getPrices(str)); // [\"$6.99\", \"$8.49\", \"$10.99\"]\n\nconst str2 = `US store $19.99\nEurope store €18.99\nJapan store ¥2000`;\nconsole.log(getPrices(str2)); // [\"$19.99\", \"€18.99\", \"¥2000\"]\n
\n
\n

Matching strings

\n
\n

With the v flag, \\p{…} can match strings that are potentially longer than one character by using a property of strings:

\n

js

\n
const flag = \"🇺🇳\";\nconsole.log(flag.length); // 2\nconsole.log(/\\p{RGI_Emoji_Flag_Sequence}/v.exec(flag)); // [ '🇺🇳' ]\n
\n

However, you can't use \\P to match \"a string that does not have a property\", because it's unclear how many characters should be consumed.

\n

js

\n
/\\P{RGI_Emoji_Flag_Sequence}/v; // SyntaxError: Invalid regular expression: Invalid property name\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-CharacterClassEscape
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Unicode_character_class_escape647978No5111.16464794711.39.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape\n

\n
\n", + "global_objects/int8array/int8array": "

Int8Array() constructor

The Int8Array() constructor creates Int8Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Int8Array()\nnew Int8Array(length)\nnew Int8Array(typedArray)\nnew Int8Array(object)\n\nnew Int8Array(buffer)\nnew Int8Array(buffer, byteOffset)\nnew Int8Array(buffer, byteOffset, length)\n
\n

Note: Int8Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create an Int8Array

\n
\n

js

\n
// From a length\nconst int8 = new Int8Array(2);\nint8[0] = 42;\nconsole.log(int8[0]); // 42\nconsole.log(int8.length); // 2\nconsole.log(int8.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Int8Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int8Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Int8Array(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int8FromIterable = new Int8Array(iterable);\nconsole.log(int8FromIterable);\n// Int8Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int8Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array\n

\n
\n", + "global_objects/typedarray/bytes_per_element": "

TypedArray.BYTES_PER_ELEMENT

The TypedArray.BYTES_PER_ELEMENT static data property represents the size in bytes of each element in a typed array.

\n

Try it

\n

Value

\n
\n

A number whose value depends on the type of TypedArray.

\n
Property attributes of TypedArray.BYTES_PER_ELEMENT\n
Writable no
Enumerable no
Configurable no
\n

Description

\n
\n

TypedArray objects differ from each other in the number of bytes per element and in the way the bytes are interpreted. The BYTES_PER_ELEMENT constant contains the number of bytes each element in the given TypedArray has.

The BYTES_PER_ELEMENT property is both an instance property and a static property. It's available on both TypedArray subclass constructors and on instances of those constructors.

As an instance property, BYTES_PER_ELEMENT is defined on the constructor's prototype.

\n

js

\n
console.log(Object.hasOwn(Int8Array.prototype, \"BYTES_PER_ELEMENT\")); // true\n
\n
\n

Examples

\n

Using BYTES_PER_ELEMENT

\n
\n

As a static property:

\n

js

\n
Int8Array.BYTES_PER_ELEMENT; // 1\nUint8Array.BYTES_PER_ELEMENT; // 1\nUint8ClampedArray.BYTES_PER_ELEMENT; // 1\nInt16Array.BYTES_PER_ELEMENT; // 2\nUint16Array.BYTES_PER_ELEMENT; // 2\nInt32Array.BYTES_PER_ELEMENT; // 4\nUint32Array.BYTES_PER_ELEMENT; // 4\nFloat32Array.BYTES_PER_ELEMENT; // 4\nFloat64Array.BYTES_PER_ELEMENT; // 8\nBigInt64Array.BYTES_PER_ELEMENT; // 8\nBigUint64Array.BYTES_PER_ELEMENT; // 8\n
\n

As an instance property:

\n

js

\n
new Int8Array([]).BYTES_PER_ELEMENT; // 1\nnew Uint8Array([]).BYTES_PER_ELEMENT; // 1\nnew Uint8ClampedArray([]).BYTES_PER_ELEMENT; // 1\nnew Int16Array([]).BYTES_PER_ELEMENT; // 2\nnew Uint16Array([]).BYTES_PER_ELEMENT; // 2\nnew Int32Array([]).BYTES_PER_ELEMENT; // 4\nnew Uint32Array([]).BYTES_PER_ELEMENT; // 4\nnew Float32Array([]).BYTES_PER_ELEMENT; // 4\nnew Float64Array([]).BYTES_PER_ELEMENT; // 8\nnew BigInt64Array([]).BYTES_PER_ELEMENT; // 8\nnew BigUint64Array([]).BYTES_PER_ELEMENT; // 8\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray.bytes_per_element
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BYTES_PER_ELEMENT71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT\n

\n
\n", + "global_objects/uint8array/uint8array": "

Uint8Array() constructor

The Uint8Array() constructor creates Uint8Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Uint8Array()\nnew Uint8Array(length)\nnew Uint8Array(typedArray)\nnew Uint8Array(object)\n\nnew Uint8Array(buffer)\nnew Uint8Array(buffer, byteOffset)\nnew Uint8Array(buffer, byteOffset, length)\n
\n

Note: Uint8Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Uint8Array

\n
\n

js

\n
// From a length\nconst uint8 = new Uint8Array(2);\nuint8[0] = 42;\nconsole.log(uint8[0]); // 42\nconsole.log(uint8.length); // 2\nconsole.log(uint8.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Uint8Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint8Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Uint8Array(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint8FromIterable = new Uint8Array(iterable);\nconsole.log(uint8FromIterable);\n// Uint8Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint8Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array\n

\n
\n", + "global_objects/uint8clampedarray/uint8clampedarray": "

Uint8ClampedArray() constructor

The Uint8ClampedArray() constructor creates Uint8ClampedArray objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Uint8ClampedArray()\nnew Uint8ClampedArray(length)\nnew Uint8ClampedArray(typedArray)\nnew Uint8ClampedArray(object)\n\nnew Uint8ClampedArray(buffer)\nnew Uint8ClampedArray(buffer, byteOffset)\nnew Uint8ClampedArray(buffer, byteOffset, length)\n
\n

Note: Uint8ClampedArray() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Uint8ClampedArray

\n
\n

js

\n
// From a length\nconst uint8c = new Uint8ClampedArray(2);\nuint8c[0] = 42;\nuint8c[1] = 1337;\nconsole.log(uint8c[0]); // 42\nconsole.log(uint8c[1]); // 255 (clamped)\nconsole.log(uint8c.length); // 2\nconsole.log(uint8c.BYTES_PER_ELEMENT); // 1\n\n// From an array\nconst x = new Uint8ClampedArray([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint8ClampedArray(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(8);\nconst z = new Uint8ClampedArray(buffer, 1, 4);\nconsole.log(z.byteOffset); // 1\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint8cFromIterable = new Uint8ClampedArray(iterable);\nconsole.log(uint8cFromIterable);\n// Uint8ClampedArray [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint8ClampedArray71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray\n

\n
\n", + "global_objects/int16array/int16array": "

Int16Array() constructor

The Int16Array() constructor creates Int16Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Int16Array()\nnew Int16Array(length)\nnew Int16Array(typedArray)\nnew Int16Array(object)\n\nnew Int16Array(buffer)\nnew Int16Array(buffer, byteOffset)\nnew Int16Array(buffer, byteOffset, length)\n
\n

Note: Int16Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create an Int16Array

\n
\n

js

\n
// From a length\nconst int16 = new Int16Array(2);\nint16[0] = 42;\nconsole.log(int16[0]); // 42\nconsole.log(int16.length); // 2\nconsole.log(int16.BYTES_PER_ELEMENT); // 2\n\n// From an array\nconst x = new Int16Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int16Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(16);\nconst z = new Int16Array(buffer, 2, 4);\nconsole.log(z.byteOffset); // 2\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int16FromIterable = new Int16Array(iterable);\nconsole.log(int16FromIterable);\n// Int16Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int16Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array\n

\n
\n", + "global_objects/uint16array/uint16array": "

Uint16Array() constructor

The Uint16Array() constructor creates Uint16Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Uint16Array()\nnew Uint16Array(length)\nnew Uint16Array(typedArray)\nnew Uint16Array(object)\n\nnew Uint16Array(buffer)\nnew Uint16Array(buffer, byteOffset)\nnew Uint16Array(buffer, byteOffset, length)\n
\n

Note: Uint16Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Uint16Array

\n
\n

js

\n
// From a length\nconst uint16 = new Uint16Array(2);\nuint16[0] = 42;\nconsole.log(uint16[0]); // 42\nconsole.log(uint16.length); // 2\nconsole.log(uint16.BYTES_PER_ELEMENT); // 2\n\n// From an array\nconst x = new Uint16Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint16Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(16);\nconst z = new Uint16Array(buffer, 2, 4);\nconsole.log(z.byteOffset); // 2\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint16FromIterable = new Uint16Array(iterable);\nconsole.log(uint16FromIterable);\n// Uint16Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint16Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array\n

\n
\n", + "global_objects/int32array/int32array": "

Int32Array() constructor

The Int32Array() constructor creates Int32Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Int32Array()\nnew Int32Array(length)\nnew Int32Array(typedArray)\nnew Int32Array(object)\n\nnew Int32Array(buffer)\nnew Int32Array(buffer, byteOffset)\nnew Int32Array(buffer, byteOffset, length)\n
\n

Note: Int32Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create an Int32Array

\n
\n

js

\n
// From a length\nconst int32 = new Int32Array(2);\nint32[0] = 42;\nconsole.log(int32[0]); // 42\nconsole.log(int32.length); // 2\nconsole.log(int32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Int32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Int32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Int32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst int32FromIterable = new Int32Array(iterable);\nconsole.log(int32FromIterable);\n// Int32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Int32Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array\n

\n
\n", + "global_objects/array/length": "

Array: length

The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

\n

Try it

\n

Value

\n
\n

A nonnegative integer less than 232.

\n
Property attributes of Array: length\n
Writable yes
Enumerable no
Configurable no
\n

Description

\n
\n

The value of the length property is a nonnegative integer with a value less than 232.

\n

js

\n
const listA = [1, 2, 3];\nconst listB = new Array(6);\n\nconsole.log(listA.length);\n// 3\n\nconsole.log(listB.length);\n// 6\n\nlistB.length = 2 ** 32; // 4294967296\n// RangeError: Invalid array length\n\nconst listC = new Array(-100); // Negative numbers are not allowed\n// RangeError: Invalid array length\n
\n

The array object observes the length property, and automatically syncs the length value with the array's content. This means:

When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.

\n

js

\n
const arr = [1, 2];\nconsole.log(arr);\n// [ 1, 2 ]\n\narr.length = 5; // set array length to 5 while currently 2.\nconsole.log(arr);\n// [ 1, 2, <3 empty items> ]\n\narr.forEach((element) => console.log(element));\n// 1\n// 2\n
\n

See also Relationship between length and numerical properties.

\n

Examples

\n

Iterating over an array

\n
\n

In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.

\n

js

\n
const numbers = [1, 2, 3, 4, 5];\nconst length = numbers.length;\nfor (let i = 0; i < length; i++) {\n  numbers[i] *= 2;\n}\n// numbers is now [2, 4, 6, 8, 10]\n
\n
\n

Shortening an array

\n
\n

The following example shortens the array numbers to a length of 3 if the current length is greater than 3.

\n

js

\n
const numbers = [1, 2, 3, 4, 5];\n\nif (numbers.length > 3) {\n  numbers.length = 3;\n}\n\nconsole.log(numbers); // [1, 2, 3]\nconsole.log(numbers.length); // 3\nconsole.log(numbers[3]); // undefined; the extra elements are deleted\n
\n
\n

Create empty array of fixed length

\n
\n

Setting length to a value greater than the current length creates a sparse array.

\n

js

\n
const numbers = [];\nnumbers.length = 3;\nconsole.log(numbers); // [empty x 3]\n
\n
\n

Array with non-writable length

\n
\n

The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.

\n

js

\n
\"use strict\";\n\nconst numbers = [1, 2, 3, 4, 5];\nObject.defineProperty(numbers, \"length\", { writable: false });\nnumbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]'\nnumbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-properties-of-array-instances-length
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
length1121441≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n

\n
\n", + "global_objects/array/join": "

Array.prototype.join()

The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

\n

Try it

\n

Syntax

\n
\n

js

\n
join()\njoin(separator)\n
\n

Parameters

\n
\nseparator Optional\n

A string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (\",\").

Return value

\n

A string with all array elements joined. If array.length is 0, the empty string is returned.

Description

\n
\n

The string conversions of all array elements are joined into one string. If an element is undefined, null, it is converted to an empty string instead of the string \"null\" or \"undefined\".

The join method is accessed internally by Array.prototype.toString() with no arguments. Overriding join of an array instance will override its toString behavior as well.

Array.prototype.join recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString (which is the same as calling join()) does not have delimiters, nested arrays look like they are flattened. You can only control the separator of the first level, while deeper levels always use the default comma.

\n

js

\n
const matrix = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9],\n];\n\nconsole.log(matrix.join()); // 1,2,3,4,5,6,7,8,9\nconsole.log(matrix.join(\";\")); // 1,2,3;4,5,6;7,8,9\n
\n

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

\n

js

\n
const arr = [];\narr.push(1, [3, arr, 4], 2);\nconsole.log(arr.join(\";\")); // 1;3,,4;2\n
\n

When used on sparse arrays, the join() method iterates empty slots as if they have the value undefined.

The join() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Joining an array four different ways

\n
\n

The following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.

\n

js

\n
const a = [\"Wind\", \"Water\", \"Fire\"];\na.join(); // 'Wind,Water,Fire'\na.join(\", \"); // 'Wind, Water, Fire'\na.join(\" + \"); // 'Wind + Water + Fire'\na.join(\"\"); // 'WindWaterFire'\n
\n
\n

Using join() on sparse arrays

\n
\n

join() treats empty slots the same as undefined and produces an extra separator:

\n

js

\n
console.log([1, , 3].join()); // '1,,3'\nconsole.log([1, undefined, 3].join()); // '1,,3'\n
\n
\n

Calling join() on non-array objects

\n
\n

The join() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 5, // ignored by join() since length is 3\n};\nconsole.log(Array.prototype.join.call(arrayLike));\n// 2,3,4\nconsole.log(Array.prototype.join.call(arrayLike, \".\"));\n// 2.3.4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.join
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
join11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\n

\n
\n", + "global_objects/array/slice": "

Array.prototype.slice()

The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

\n

Try it

\n

Syntax

\n
\n

js

\n
slice()\nslice(start)\nslice(start, end)\n
\n

Parameters

\n
\nstart Optional\n

Zero-based index at which to start extraction, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length or start is omitted, 0 is used.
  • If start >= array.length, nothing is extracted.
\nend Optional\n

Zero-based index at which to end extraction, converted to an integer. slice() extracts up to but not including end.

  • Negative index counts back from the end of the array — if end < 0, end + array.length is used.
  • If end < -array.length, 0 is used.
  • If end >= array.length or end is omitted, array.length is used, causing all elements until the end to be extracted.
  • If end is positioned before or at start after normalization, nothing is extracted.

Return value

\n

A new array containing the extracted elements.

Description

\n
\n

The slice() method is a copying method. It does not alter this but instead returns a shallow copy that contains some of the same elements as the ones from the original array.

The slice() method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well.

The slice() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Return a portion of an existing array

\n
\n

js

\n
const fruits = [\"Banana\", \"Orange\", \"Lemon\", \"Apple\", \"Mango\"];\nconst citrus = fruits.slice(1, 3);\n\n// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']\n// citrus contains ['Orange','Lemon']\n
\n

Using slice

\n
\n

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

\n

js

\n
// Using slice, create newCar from myCar.\nconst myHonda = {\n  color: \"red\",\n  wheels: 4,\n  engine: { cylinders: 4, size: 2.2 },\n};\nconst myCar = [myHonda, 2, \"cherry condition\", \"purchased 1997\"];\nconst newCar = myCar.slice(0, 2);\n\nconsole.log(\"myCar =\", myCar);\nconsole.log(\"newCar =\", newCar);\nconsole.log(\"myCar[0].color =\", myCar[0].color);\nconsole.log(\"newCar[0].color =\", newCar[0].color);\n\n// Change the color of myHonda.\nmyHonda.color = \"purple\";\nconsole.log(\"The new color of my Honda is\", myHonda.color);\n\nconsole.log(\"myCar[0].color =\", myCar[0].color);\nconsole.log(\"newCar[0].color =\", newCar[0].color);\n
\n

This script writes:

myCar = [\n  { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } },\n  2,\n  'cherry condition',\n  'purchased 1997'\n]\nnewCar = [ { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }, 2 ]\nmyCar[0].color = red\nnewCar[0].color = red\nThe new color of my Honda is purple\nmyCar[0].color = purple\nnewCar[0].color = purple\n
\n

Calling slice() on non-array objects

\n
\n

The slice() method reads the length property of this. It then reads the integer-keyed properties from start to end and defines them on a newly created array.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 33, // ignored by slice() since length is 3\n};\nconsole.log(Array.prototype.slice.call(arrayLike, 1, 3));\n// [ 3, 4 ]\n
\n
\n

Using slice() to convert array-like objects to arrays

\n
\n

The slice() method is often used with bind() and call() to create a utility method that converts an array-like object into an array.

\n

js

\n
// slice() is called with `this` passed as the first argument\nconst slice = Function.prototype.call.bind(Array.prototype.slice);\n\nfunction list() {\n  return slice(arguments);\n}\n\nconst list1 = list(1, 2, 3); // [1, 2, 3]\n
\n
\n

Using slice() on sparse arrays

\n
\n

The array returned from slice() may be sparse if the source is sparse.

\n

js

\n
console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.slice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
slice11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\n

\n
\n", + "global_objects/array/push": "

Array.prototype.push()

The push() method of Array instances adds the specified elements to the end of an array and returns the new length of the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
push()\npush(element1)\npush(element1, element2)\npush(element1, element2, /* …, */ elementN)\n
\n

Parameters

\n
\nelement1, …, elementN\n

The element(s) to add to the end of the array.

Return value

\n

The new length property of the object upon which the method was called.

Description

\n
\n

The push() method appends values to an array.

Array.prototype.unshift() has similar behavior to push(), but applied to the start of an array.

The push() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* ... ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat().

The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Adding elements to an array

\n
\n

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

\n

js

\n
const sports = [\"soccer\", \"baseball\"];\nconst total = sports.push(\"football\", \"swimming\");\n\nconsole.log(sports); // ['soccer', 'baseball', 'football', 'swimming']\nconsole.log(total); // 4\n
\n
\n

Merging two arrays

\n
\n

This example uses spread syntax to push all elements from a second array into the first one.

\n

js

\n
const vegetables = [\"parsnip\", \"potato\"];\nconst moreVegs = [\"celery\", \"beetroot\"];\n\n// Merge the second array into the first one\nvegetables.push(...moreVegs);\n\nconsole.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']\n
\n

Merging two arrays can also be done with the concat() method.

\n

Calling push() on non-array objects

\n
\n

The push() method reads the length property of this. It then sets each index of this starting at length with the arguments passed to push(). Finally, it sets the length to the previous length plus the number of pushed elements.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n};\nArray.prototype.push.call(arrayLike, 1, 2);\nconsole.log(arrayLike);\n// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }\n\nconst plainObj = {};\n// There's no length property, so the length is 0\nArray.prototype.push.call(plainObj, 1, 2);\nconsole.log(plainObj);\n// { '0': 1, '1': 2, length: 2 }\n
\n
\n

Using an object in an array-like fashion

\n
\n

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

\n

js

\n
const obj = {\n  length: 0,\n\n  addElem(elem) {\n    // obj.length is automatically incremented\n    // every time an element is added.\n    [].push.call(this, elem);\n  },\n};\n\n// Let's add some empty objects just to illustrate.\nobj.addElem({});\nobj.addElem({});\nconsole.log(obj.length); // 2\n
\n

Note that although obj is not an array, the method push successfully incremented obj's length property just like if we were dealing with an actual array.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.push
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
push11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\n

\n
\n", + "global_objects/array/splice": "

Array.prototype.splice()

\n

The splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced(). To access part of an array without modifying it, see slice().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
splice(start)\nsplice(start, deleteCount)\nsplice(start, deleteCount, item1)\nsplice(start, deleteCount, item1, item2)\nsplice(start, deleteCount, item1, item2, /* …, */ itemN)\n
\n

Parameters

\n
start

Zero-based index at which to start changing the array, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length, 0 is used.
  • If start >= array.length, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided.
  • If start is omitted (and splice() is called with no arguments), nothing is deleted. This is different from passing undefined, which is converted to 0.
\ndeleteCount Optional\n

An integer indicating the number of elements in the array to remove from start.

If deleteCount is omitted, or if its value is greater than or equal to the number of elements after the position specified by start, then all the elements from start to the end of the array will be deleted. However, if you wish to pass any itemN parameter, you should pass Infinity as deleteCount to delete all elements after start, because an explicit undefined gets converted to 0.

If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

\nitem1, …, itemN Optional\n

The elements to add to the array, beginning from start.

If you do not specify any elements, splice() will only remove elements from the array.

Return value

\n
\n

An array containing the deleted elements.

If only one element is removed, an array of one element is returned.

If no elements are removed, an empty array is returned.

\n

Description

\n
\n

The splice() method is a mutating method. It may change the content of this. If the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed as well. At the same time, it uses @@species to create a new array instance to be returned.

If the deleted portion is sparse, the array returned by splice() is sparse as well, with those corresponding indices being empty slots.

The splice() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Remove 0 (zero) elements before index 2, and insert \"drum\"

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"sturgeon\"];\nconst removed = myFish.splice(2, 0, \"drum\");\n\n// myFish is [\"angel\", \"clown\", \"drum\", \"mandarin\", \"sturgeon\"]\n// removed is [], no elements removed\n
\n

Remove 0 (zero) elements before index 2, and insert \"drum\" and \"guitar\"

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"sturgeon\"];\nconst removed = myFish.splice(2, 0, \"drum\", \"guitar\");\n\n// myFish is [\"angel\", \"clown\", \"drum\", \"guitar\", \"mandarin\", \"sturgeon\"]\n// removed is [], no elements removed\n
\n

Remove 1 element at index 3

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"drum\", \"mandarin\", \"sturgeon\"];\nconst removed = myFish.splice(3, 1);\n\n// myFish is [\"angel\", \"clown\", \"drum\", \"sturgeon\"]\n// removed is [\"mandarin\"]\n
\n

Remove 1 element at index 2, and insert \"trumpet\"

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"drum\", \"sturgeon\"];\nconst removed = myFish.splice(2, 1, \"trumpet\");\n\n// myFish is [\"angel\", \"clown\", \"trumpet\", \"sturgeon\"]\n// removed is [\"drum\"]\n
\n

Remove 2 elements from index 0, and insert \"parrot\", \"anemone\" and \"blue\"

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"trumpet\", \"sturgeon\"];\nconst removed = myFish.splice(0, 2, \"parrot\", \"anemone\", \"blue\");\n\n// myFish is [\"parrot\", \"anemone\", \"blue\", \"trumpet\", \"sturgeon\"]\n// removed is [\"angel\", \"clown\"]\n
\n

Remove 2 elements, starting from index 2

\n
\n

js

\n
const myFish = [\"parrot\", \"anemone\", \"blue\", \"trumpet\", \"sturgeon\"];\nconst removed = myFish.splice(2, 2);\n\n// myFish is [\"parrot\", \"anemone\", \"sturgeon\"]\n// removed is [\"blue\", \"trumpet\"]\n
\n

Remove 1 element from index -2

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"sturgeon\"];\nconst removed = myFish.splice(-2, 1);\n\n// myFish is [\"angel\", \"clown\", \"sturgeon\"]\n// removed is [\"mandarin\"]\n
\n

Remove all elements, starting from index 2

\n
\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"sturgeon\"];\nconst removed = myFish.splice(2);\n\n// myFish is [\"angel\", \"clown\"]\n// removed is [\"mandarin\", \"sturgeon\"]\n
\n

Using splice() on sparse arrays

\n
\n

The splice() method preserves the array's sparseness.

\n

js

\n
const arr = [1, , 3, 4, , 6];\nconsole.log(arr.splice(1, 2)); // [empty, 3]\nconsole.log(arr); // [1, 4, empty, 6]\n
\n
\n

Calling splice() on non-array objects

\n
\n

The splice() method reads the length property of this. It then updates the integer-keyed properties and the length property as needed.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  0: 5,\n  2: 4,\n};\nconsole.log(Array.prototype.splice.call(arrayLike, 0, 1, 2, 3));\n// [ 5 ]\nconsole.log(arrayLike);\n// { '0': 2, '1': 3, '3': 4, length: 4, unrelated: 'foo' }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.splice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
splice1121
5.5From Internet Explorer 5.5 through 8, all elements of the array will not be deleted if deleteCount is omitted. This behavior was fixed in Internet Explorer 9.
414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\n

\n
\n", + "global_objects/array/copywithin": "

Array.prototype.copyWithin()

The copyWithin() method of Array instances shallow copies part of this array to another location in the same array and returns this array without modifying its length.

\n

Try it

\n

Syntax

\n
\n

js

\n
copyWithin(target, start)\ncopyWithin(target, start, end)\n
\n

Parameters

\n
target

Zero-based index at which to copy the sequence to, converted to an integer. This corresponds to where the element at start will be copied to, and all elements between start and end are copied to succeeding indices.

  • Negative index counts back from the end of the array — if target < 0, target + array.length is used.
  • If target < -array.length, 0 is used.
  • If target >= array.length, nothing is copied.
  • If target is positioned after start after normalization, copying only happens until the end of array.length (in other words, copyWithin() never extends the array).
start

Zero-based index at which to start copying elements from, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length, 0 is used.
  • If start >= array.length, nothing is copied.
\nend Optional\n

Zero-based index at which to end copying elements from, converted to an integer. copyWithin() copies up to but not including end.

  • Negative index counts back from the end of the array — if end < 0, end + array.length is used.
  • If end < -array.length, 0 is used.
  • If end >= array.length or end is omitted, array.length is used, causing all elements until the end to be copied.
  • If end is positioned before or at start after normalization, nothing is copied.

Return value

\n

The modified array.

Description

\n
\n

The copyWithin() method works like C and C++'s memmove, and is a high-performance method to shift the data of an Array. This especially applies to the TypedArray method of the same name. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap.

Because undefined becomes 0 when converted to an integer, omitting the start parameter has the same effect as passing 0, which copies the entire array to the target position, equivalent to a right shift where the right boundary is clipped off and the left boundary is duplicated. This behavior may confuse readers of your code, so you should explicitly pass 0 as start instead.

\n

js

\n
console.log([1, 2, 3, 4, 5].copyWithin(2));\n// [1, 2, 1, 2, 3]; move all elements to the right by 2 positions\n
\n

The copyWithin() method is a mutating method. It does not alter the length of this, but it will change the content of this and create new properties or delete existing properties, if necessary.

The copyWithin() method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.

The copyWithin() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Using copyWithin()

\n
\n

js

\n
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));\n// [4, 5, 3, 4, 5]\n\nconsole.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));\n// [4, 2, 3, 4, 5]\n\nconsole.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));\n// [1, 2, 3, 3, 4]\n
\n

Using copyWithin() on sparse arrays

\n
\n

copyWithin() will propagate empty slots.

\n

js

\n
console.log([1, , 3].copyWithin(2, 1, 2)); // [1, empty, empty]\n
\n
\n

Calling copyWithin() on non-array objects

\n
\n

The copyWithin() method reads the length property of this and then manipulates the integer indices involved.

\n

js

\n
const arrayLike = {\n  length: 5,\n  3: 1,\n};\nconsole.log(Array.prototype.copyWithin.call(arrayLike, 0, 3));\n// { '0': 1, '3': 1, length: 5 }\nconsole.log(Array.prototype.copyWithin.call(arrayLike, 3, 1));\n// { '0': 1, length: 5 }\n// The '3' property is deleted because the copied source is an empty slot\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.copywithin
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
copyWithin451232No3294545323295.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin\n

\n
\n", + "global_objects/array/every": "

Array.prototype.every()

The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

\n

Try it

\n

Syntax

\n
\n

js

\n
every(callbackFn)\nevery(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array every() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

true unless callbackFn returns a falsy value for an array element, in which case false is immediately returned.

Description

\n
\n

The every() method is an iterative method. It calls a provided callbackFn function once for each element in an array, until the callbackFn returns a falsy value. If such an element is found, every() immediately returns false and stops iterating through the array. Otherwise, if callbackFn returns a truthy value for all elements, every() returns true.

every acts like the \"for all\" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

every() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The every() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Testing size of all array elements

\n
\n

The following example tests whether all elements in the array are bigger than 9.

\n

js

\n
function isBigEnough(element, index, array) {\n  return element >= 10;\n}\n[12, 5, 8, 130, 44].every(isBigEnough); // false\n[12, 54, 18, 130, 44].every(isBigEnough); // true\n
\n
\n

Check if one array is a subset of another array

\n
\n

The following example tests if all the elements of an array are present in another array.

\n

js

\n
const isSubset = (array1, array2) =>\n  array2.every((element) => array1.includes(element));\n\nconsole.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true\nconsole.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false\n
\n
\n

Using every() on sparse arrays

\n
\n

every() will not run its predicate on empty slots.

\n

js

\n
console.log([1, , 3].every((x) => x !== undefined)); // true\nconsole.log([2, , 2].every((x) => x === 2)); // true\n
\n
\n

Affecting Initial Array (modifying, appending, and deleting)

\n
\n

The following examples tests the behavior of the every method when the array is modified.

\n

js

\n
// ---------------\n// Modifying items\n// ---------------\nlet arr = [1, 2, 3, 4];\narr.every((elem, index, arr) => {\n  arr[index + 1]--;\n  console.log(`[${arr}][${index}] -> ${elem}`);\n  return elem < 2;\n});\n\n// Loop runs for 3 iterations, but would\n// have run 2 iterations without any modification\n//\n// 1st iteration: [1,1,3,4][0] -> 1\n// 2nd iteration: [1,1,2,4][1] -> 1\n// 3rd iteration: [1,1,2,3][2] -> 2\n\n// ---------------\n// Appending items\n// ---------------\narr = [1, 2, 3];\narr.every((elem, index, arr) => {\n  arr.push(\"new\");\n  console.log(`[${arr}][${index}] -> ${elem}`);\n  return elem < 4;\n});\n\n// Loop runs for 3 iterations, even after appending new items\n//\n// 1st iteration: [1, 2, 3, new][0] -> 1\n// 2nd iteration: [1, 2, 3, new, new][1] -> 2\n// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3\n\n// ---------------\n// Deleting items\n// ---------------\narr = [1, 2, 3, 4];\narr.every((elem, index, arr) => {\n  arr.pop();\n  console.log(`[${arr}][${index}] -> ${elem}`);\n  return elem < 4;\n});\n\n// Loop runs for 2 iterations only, as the remaining\n// items are `pop()`ed off\n//\n// 1st iteration: [1,2,3][0] -> 1\n// 2nd iteration: [1,2][1] -> 2\n
\n
\n

Calling every() on non-array objects

\n
\n

The every() method reads the length property of this and then accesses each property with a nonnegative integer key less than length until they all have been accessed or callbackFn returns false.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\",\n  3: 345, // ignored by every() since length is 3\n};\nconsole.log(\n  Array.prototype.every.call(arrayLike, (x) => typeof x === \"string\"),\n); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.every
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
every1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\n

\n
\n", + "global_objects/array/filter": "

Array.prototype.filter()

The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

\n

Try it

\n

Syntax

\n
\n

js

\n
filter(callbackFn)\nfilter(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array filter() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

A shallow copy of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned.

Description

\n
\n

The filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value. Array elements which do not pass the callbackFn test are not included in the new array.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The filter() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The filter() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Filtering out all small values

\n
\n

The following example uses filter() to create a filtered array that has all elements with values less than 10 removed.

\n

js

\n
function isBigEnough(value) {\n  return value >= 10;\n}\n\nconst filtered = [12, 5, 8, 130, 44].filter(isBigEnough);\n// filtered is [12, 130, 44]\n
\n
\n

Find all prime numbers in an array

\n
\n

The following example returns all prime numbers in the array:

\n

js

\n
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];\n\nfunction isPrime(num) {\n  for (let i = 2; num > i; i++) {\n    if (num % i === 0) {\n      return false;\n    }\n  }\n  return num > 1;\n}\n\nconsole.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]\n
\n
\n

Filtering invalid entries from JSON

\n
\n

The following example uses filter() to create a filtered JSON of all elements with non-zero, numeric id.

\n

js

\n
const arr = [\n  { id: 15 },\n  { id: -1 },\n  { id: 0 },\n  { id: 3 },\n  { id: 12.2 },\n  {},\n  { id: null },\n  { id: NaN },\n  { id: \"undefined\" },\n];\n\nlet invalidEntries = 0;\n\nfunction filterByID(item) {\n  if (Number.isFinite(item.id) && item.id !== 0) {\n    return true;\n  }\n  invalidEntries++;\n  return false;\n}\n\nconst arrByID = arr.filter(filterByID);\n\nconsole.log(\"Filtered Array\\n\", arrByID);\n// Filtered Array\n// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]\n\nconsole.log(\"Number of Invalid Entries =\", invalidEntries);\n// Number of Invalid Entries = 5\n
\n
\n

Searching in array

\n
\n

Following example uses filter() to filter array content based on search criteria.

\n

js

\n
const fruits = [\"apple\", \"banana\", \"grapes\", \"mango\", \"orange\"];\n\n/**\n * Filter array items based on search criteria (query)\n */\nfunction filterItems(arr, query) {\n  return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));\n}\n\nconsole.log(filterItems(fruits, \"ap\")); // ['apple', 'grapes']\nconsole.log(filterItems(fruits, \"an\")); // ['banana', 'mango', 'orange']\n
\n
\n

Using filter() on sparse arrays

\n
\n

filter() will skip empty slots.

\n

js

\n
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]\nconsole.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]\n
\n
\n

Calling filter() on non-array objects

\n
\n

The filter() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\",\n  3: \"a\", // ignored by filter() since length is 3\n};\nconsole.log(Array.prototype.filter.call(arrayLike, (x) => x <= \"b\"));\n// [ 'a', 'b' ]\n
\n
\n

Affecting Initial Array (modifying, appending and deleting)

\n
\n

The following example tests the behavior of the filter method when the array is modified.

\n

js

\n
// Modifying each word\nlet words = [\"spray\", \"limit\", \"exuberant\", \"destruction\", \"elite\", \"present\"];\n\nconst modifiedWords = words.filter((word, index, arr) => {\n  arr[index + 1] += \" extra\";\n  return word.length < 6;\n});\n\nconsole.log(modifiedWords);\n// Notice there are three words below length 6, but since they've been modified one is returned\n// [\"spray\"]\n\n// Appending new words\nwords = [\"spray\", \"limit\", \"exuberant\", \"destruction\", \"elite\", \"present\"];\nconst appendedWords = words.filter((word, index, arr) => {\n  arr.push(\"new\");\n  return word.length < 6;\n});\n\nconsole.log(appendedWords);\n// Only three fits the condition even though the `words` itself now has a lot more words with character length less than 6\n// [\"spray\" ,\"limit\" ,\"elite\"]\n\n// Deleting words\nwords = [\"spray\", \"limit\", \"exuberant\", \"destruction\", \"elite\", \"present\"];\nconst deleteWords = words.filter((word, index, arr) => {\n  arr.pop();\n  return word.length < 6;\n});\n\nconsole.log(deleteWords);\n// Notice 'elite' is not even obtained as it's been popped off 'words' before filter can even get there\n// [\"spray\" ,\"limit\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.filter
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
filter1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\n

\n
\n", + "global_objects/array/flat": "

Array.prototype.flat()

The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

\n

Try it

\n

Syntax

\n
\n

js

\n
flat()\nflat(depth)\n
\n

Parameters

\n
\ndepth Optional\n

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Return value

\n

A new array with the sub-array elements concatenated into it.

Description

\n
\n

The flat() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array.

The flat() method ignores empty slots if the array being flattened is sparse. For example, if depth is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves.

The flat() method is generic. It only expects the this value to have a length property and integer-keyed properties. However, its elements must be arrays if they are to be flattened.

\n

Examples

\n

Flattening nested arrays

\n
\n

js

\n
const arr1 = [1, 2, [3, 4]];\narr1.flat();\n// [1, 2, 3, 4]\n\nconst arr2 = [1, 2, [3, 4, [5, 6]]];\narr2.flat();\n// [1, 2, 3, 4, [5, 6]]\n\nconst arr3 = [1, 2, [3, 4, [5, 6]]];\narr3.flat(2);\n// [1, 2, 3, 4, 5, 6]\n\nconst arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];\narr4.flat(Infinity);\n// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n
\n

Using flat() on sparse arrays

\n
\n

The flat() method removes empty slots in arrays:

\n

js

\n
const arr5 = [1, 2, , 4, 5];\nconsole.log(arr5.flat()); // [1, 2, 4, 5]\n\nconst array = [1, , 3, [\"a\", , \"c\"]];\nconsole.log(array.flat()); // [ 1, 3, \"a\", \"c\" ]\n\nconst array2 = [1, , 3, [\"a\", , [\"d\", , \"e\"]]];\nconsole.log(array2.flat()); // [ 1, 3, \"a\", [\"d\", empty, \"e\"] ]\nconsole.log(array2.flat(2)); // [ 1, 3, \"a\", \"d\", \"e\"]\n
\n
\n

Calling flat() on non-array objects

\n
\n

The flat() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length. If the element is not an array, it's directly appended to the result. If the element is an array, it's flattened according to the depth parameter.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: [1, 2],\n  // Array-like objects aren't flattened\n  1: { length: 2, 0: 3, 1: 4 },\n  2: 5,\n  3: 3, // ignored by flat() since length is 3\n};\nconsole.log(Array.prototype.flat.call(arrayLike));\n// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.flat
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
flat697962No5612696962481210.01.011.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\n

\n
\n", + "global_objects/array/flatmap": "

Array.prototype.flatMap()

The flatMap() method of Array instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

\n

Try it

\n

Syntax

\n
\n

js

\n
flatMap(callbackFn)\nflatMap(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array flatMap() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

A new array with each element being the result of the callback function and flattened by a depth of 1.

Description

\n
\n

The flatMap() method is an iterative method. See Array.prototype.map() for a detailed description of the callback function. The flatMap() method is identical to map(callbackFn, thisArg) followed by flat(1) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array.

The flatMap() method is generic. It only expects the this value to have a length property and integer-keyed properties. However, the value returned from callbackFn must be an array if it is to be flattened.

\n

Alternative

\n
\n

Pre-allocate and explicitly iterate

\n

js

\n
const arr = [1, 2, 3, 4];\n\narr.flatMap((x) => [x, x * 2]);\n// is equivalent to\nconst n = arr.length;\nconst acc = new Array(n * 2);\nfor (let i = 0; i < n; i++) {\n  const x = arr[i];\n  acc[i * 2] = x;\n  acc[i * 2 + 1] = x * 2;\n}\n// [1, 2, 2, 4, 3, 6, 4, 8]\n
\n

Note that in this particular case the flatMap approach is slower than the for-loop approach — due to the creation of temporary arrays that must be garbage collected, as well as the return array not needing to be frequently resized. However, flatMap may still be the correct solution in cases where its flexibility and readability are desired.

\n

Examples

\n

map() and flatMap()

\n
\n
\n

js

\n
const arr1 = [1, 2, 3, 4];\n\narr1.map((x) => [x * 2]);\n// [[2], [4], [6], [8]]\n\narr1.flatMap((x) => [x * 2]);\n// [2, 4, 6, 8]\n\n// only one level is flattened\narr1.flatMap((x) => [[x * 2]]);\n// [[2], [4], [6], [8]]\n
\n

While the above could have been achieved by using map itself, here is an example that better showcases the use of flatMap().

Let's generate a list of words from a list of sentences.

\n

js

\n
const arr1 = [\"it's Sunny in\", \"\", \"California\"];\n\narr1.map((x) => x.split(\" \"));\n// [[\"it's\",\"Sunny\",\"in\"],[\"\"],[\"California\"]]\n\narr1.flatMap((x) => x.split(\" \"));\n// [\"it's\",\"Sunny\",\"in\", \"\", \"California\"]\n
\n

Notice, the output list length can be different from the input list length.

\n

For adding and removing items during a map()

\n
\n

flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

\n

js

\n
// Let's say we want to remove all the negative numbers\n// and split the odd numbers into an even number and a 1\nconst a = [5, 4, -3, 20, 17, -33, -4, 18];\n//         |\\  \\  x   |  | \\   x   x   |\n//        [4,1, 4,   20, 16, 1,       18]\n\nconst result = a.flatMap((n) => {\n  if (n < 0) {\n    return [];\n  }\n  return n % 2 === 0 ? [n] : [n - 1, 1];\n});\nconsole.log(result); // [4, 1, 4, 20, 16, 1, 18]\n
\n
\n

Using flatMap() on sparse arrays

\n
\n

The callbackFn won't be called for empty slots in the source array because map() doesn't, while flat() ignores empty slots in the returned arrays.

\n

js

\n
console.log([1, 2, , 4, 5].flatMap((x) => [x, x * 2])); // [1, 2, 2, 4, 4, 8, 5, 10]\nconsole.log([1, 2, 3, 4].flatMap((x) => [, x * 2])); // [2, 4, 6, 8]\n
\n
\n

Calling flatMap() on non-array objects

\n
\n

The flatMap() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length. If the return value of the callback function is not an array, it is always directly appended to the result array.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 1,\n  1: 2,\n  2: 3,\n  3: 4, // ignored by flatMap() since length is 3\n};\nconsole.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x * 2]));\n// [1, 2, 2, 4, 3, 6]\n\n// Array-like objects returned from the callback won't be flattened\nconsole.log(\n  Array.prototype.flatMap.call(arrayLike, (x) => ({\n    length: 1,\n    0: x,\n  })),\n);\n// [ { '0': 1, length: 1 }, { '0': 2, length: 1 }, { '0': 3, length: 1 } ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.flatmap
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
flatMap697962No5612696962481210.01.011.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap\n

\n
\n", + "global_objects/array/foreach": "

Array.prototype.forEach()

The forEach() method of Array instances executes a provided function once for each array element.

\n

Try it

\n

Syntax

\n
\n

js

\n
forEach(callbackFn)\nforEach(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array forEach() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

None (undefined).

Description

\n
\n

The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map(), forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

forEach() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The forEach() method is generic. It only expects the this value to have a length property and integer-keyed properties.

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with looping statements like for, for...of, and for...in. Array methods like every(), some(), find(), and findIndex() also stops iteration immediately when further iteration is not necessary.

forEach() expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callbacks.

\n

js

\n
const ratings = [5, 4, 5];\nlet sum = 0;\n\nconst sumFunction = async (a, b) => a + b;\n\nratings.forEach(async (rating) => {\n  sum = await sumFunction(sum, rating);\n});\n\nconsole.log(sum);\n// Naively expected output: 14\n// Actual output: 0\n
\n

To run a series of asynchronous operations sequentially or concurrently, see promise composition.

\n

Examples

\n

Using forEach() on sparse arrays

\n
\n
\n

js

\n
const arraySparse = [1, 3, /* empty */, 7];\nlet numCallbackRuns = 0;\n\narraySparse.forEach((element) => {\n  console.log({ element });\n  numCallbackRuns++;\n});\n\nconsole.log({ numCallbackRuns });\n\n// { element: 1 }\n// { element: 3 }\n// { element: 7 }\n// { numCallbackRuns: 3 }\n
\n

The callback function is not invoked for the missing value at index 2.

\n

Converting a for loop to forEach

\n
\n

js

\n
const items = [\"item1\", \"item2\", \"item3\"];\nconst copyItems = [];\n\n// before\nfor (let i = 0; i < items.length; i++) {\n  copyItems.push(items[i]);\n}\n\n// after\nitems.forEach((item) => {\n  copyItems.push(item);\n});\n
\n

Printing the contents of an array

\n
\n

Note: In order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the array.

The following example illustrates an alternative approach, using forEach().

The following code logs a line for each element in an array:

\n

js

\n
const logArrayElements = (element, index /*, array */) => {\n  console.log(`a[${index}] = ${element}`);\n};\n\n// Notice that index 2 is skipped, since there is no item at\n// that position in the array.\n[2, 5, , 9].forEach(logArrayElements);\n// Logs:\n// a[0] = 2\n// a[1] = 5\n// a[3] = 9\n
\n
\n

Using thisArg

\n
\n

The following (contrived) example updates an object's properties from each entry in the array:

\n

js

\n
class Counter {\n  constructor() {\n    this.sum = 0;\n    this.count = 0;\n  }\n  add(array) {\n    // Only function expressions will have its own this binding\n    array.forEach(function countEntry(entry) {\n      this.sum += entry;\n      ++this.count;\n    }, this);\n  }\n}\n\nconst obj = new Counter();\nobj.add([2, 5, 9]);\nconsole.log(obj.count); // 3\nconsole.log(obj.sum); // 16\n
\n

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked. The callback uses it as its this value.

Note: If passing the callback function used an arrow function expression, the thisArg parameter could be omitted, since all arrow functions lexically bind the this value.

\n

An object copy function

\n
\n

The following code creates a copy of a given object.

There are different ways to create a copy of an object. The following is just one way and is presented to explain how Array.prototype.forEach() works by using Object.* utility functions.

\n

js

\n
const copy = (obj) => {\n  const copy = Object.create(Object.getPrototypeOf(obj));\n  const propNames = Object.getOwnPropertyNames(obj);\n  propNames.forEach((name) => {\n    const desc = Object.getOwnPropertyDescriptor(obj, name);\n    Object.defineProperty(copy, name, desc);\n  });\n  return copy;\n};\n\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = copy(obj1); // obj2 looks like obj1 now\n
\n
\n

Modifying the array during iteration

\n
\n

The following example logs one, two, four.

When the entry containing the value two is reached, the first entry of the whole array is shifted off—resulting in all remaining entries moving up one position. Because element four is now at an earlier position in the array, three will be skipped.

forEach() does not make a copy of the array before iterating.

\n

js

\n
const words = [\"one\", \"two\", \"three\", \"four\"];\nwords.forEach((word) => {\n  console.log(word);\n  if (word === \"two\") {\n    words.shift(); //'one' will delete from array\n  }\n}); // one // two // four\n\nconsole.log(words); // ['two', 'three', 'four']\n
\n
\n

Flatten an array

\n
\n

The following example is only here for learning purpose. If you want to flatten an array using built-in methods, you can use Array.prototype.flat().

\n

js

\n
const flatten = (arr) => {\n  const result = [];\n  arr.forEach((item) => {\n    if (Array.isArray(item)) {\n      result.push(...flatten(item));\n    } else {\n      result.push(item);\n    }\n  });\n  return result;\n};\n\n// Usage\nconst nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];\nconsole.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]\n
\n
\n

Calling forEach() on non-array objects

\n
\n

The forEach() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 5, // ignored by forEach() since length is 3\n};\nArray.prototype.forEach.call(arrayLike, (x) => console.log(x));\n// 2\n// 3\n// 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.foreach
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
forEach1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\n

\n
\n", + "global_objects/array/map": "

Array.prototype.map()

The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.

\n

Try it

\n

Syntax

\n
\n

js

\n
map(callbackFn)\nmap(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array map() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

A new array with each element being the result of the callback function.

Description

\n
\n

The map() method is an iterative method. It calls a provided callbackFn function once for each element in an array and constructs a new array from the results.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The map() method is a copying method. It does not alter this. However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The map() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Since map builds a new array, calling it without using the returned array is an anti-pattern; use forEach or for...of instead.

\n

Examples

\n

Mapping an array of numbers to an array of square roots

\n
\n

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

\n

js

\n
const numbers = [1, 4, 9];\nconst roots = numbers.map((num) => Math.sqrt(num));\n\n// roots is now     [1, 2, 3]\n// numbers is still [1, 4, 9]\n
\n
\n

Using map to reformat objects in an array

\n
\n

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

\n

js

\n
const kvArray = [\n  { key: 1, value: 10 },\n  { key: 2, value: 20 },\n  { key: 3, value: 30 },\n];\n\nconst reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));\n\nconsole.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]\nconsole.log(kvArray);\n// [\n//   { key: 1, value: 10 },\n//   { key: 2, value: 20 },\n//   { key: 3, value: 30 }\n// ]\n
\n
\n

Mapping an array of numbers using a function containing an argument

\n
\n

The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

\n

js

\n
const numbers = [1, 4, 9];\nconst doubles = numbers.map((num) => num * 2);\n\nconsole.log(doubles); // [2, 8, 18]\nconsole.log(numbers); // [1, 4, 9]\n
\n
\n

Side-effectful mapping

\n
\n

The callback can have side effects.

\n

js

\n
const cart = [5, 15, 25];\nlet total = 0;\nconst withTax = cart.map((cost) => {\n  total += cost;\n  return cost * 1.2;\n});\nconsole.log(withTax); // [6, 18, 30]\nconsole.log(total); // 45\n
\n

This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.

\n

js

\n
const cart = [5, 15, 25];\nconst total = cart.reduce((acc, cost) => acc + cost, 0);\nconst withTax = cart.map((cost) => cost * 1.2);\n
\n

Sometimes this pattern goes to its extreme and the only useful thing that map() does is causing side effects.

\n

js

\n
const products = [\n  { name: \"sports car\" },\n  { name: \"laptop\" },\n  { name: \"phone\" },\n];\n\nproducts.map((product) => {\n  product.price = 100;\n});\n
\n

As mentioned previously, this is an anti-pattern. If you don't use the return value of map(), use forEach() or a for...of loop instead.

\n

js

\n
products.forEach((product) => {\n  product.price = 100;\n});\n
\n

Or, if you want to create a new array instead:

\n

js

\n
const productsWithPrice = products.map((product) => {\n  return { ...product, price: 100 };\n});\n
\n
\n

Calling map() on non-array objects

\n
\n

The map() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 5, // ignored by map() since length is 3\n};\nconsole.log(Array.prototype.map.call(arrayLike, (x) => x ** 2));\n// [ 4, 9, 16 ]\n
\n
\n

Using map() generically on a NodeList

\n
\n

This example shows how to iterate through a collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList (which is a collection of objects).

In this case, we return all the selected options' values on the screen:

\n

js

\n
const elems = document.querySelectorAll(\"select option:checked\");\nconst values = Array.prototype.map.call(elems, ({ value }) => value);\n
\n

An easier way would be the Array.from() method.

\n

Using map() on sparse arrays

\n
\n

A sparse array remains sparse after map(). The indices of empty slots are still empty in the returned array, and the callback function won't be called on them.

\n

js

\n
console.log(\n  [1, , 3].map((x, index) => {\n    console.log(`Visit ${index}`);\n    return x * 2;\n  }),\n);\n// Visit 0\n// Visit 2\n// [2, empty, 6]\n
\n
\n

Using parseInt() with map()

\n
\n

(inspired by this blog post)

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.

Consider:

\n

js

\n
[\"1\", \"2\", \"3\"].map(parseInt);\n
\n

While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

The third argument is ignored by parseInt—but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:

\n

js

\n
// parseInt(string, radix) -> map(parseInt(value, index))\n/* first iteration  (index is 0): */ parseInt(\"1\", 0); // 1\n/* second iteration (index is 1): */ parseInt(\"2\", 1); // NaN\n/* third iteration  (index is 2): */ parseInt(\"3\", 2); // NaN\n
\n

Then let's talk about solutions.

\n

js

\n
const returnInt = (element) => parseInt(element, 10);\n\n[\"1\", \"2\", \"3\"].map(returnInt); // [1, 2, 3]\n// Actual result is an array of numbers (as expected)\n\n// Same as above, but using the concise arrow function syntax\n[\"1\", \"2\", \"3\"].map((str) => parseInt(str)); // [1, 2, 3]\n\n// A simpler way to achieve the above, while avoiding the \"gotcha\":\n[\"1\", \"2\", \"3\"].map(Number); // [1, 2, 3]\n\n// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:\n[\"1.1\", \"2.2e2\", \"3e300\"].map(Number); // [1.1, 220, 3e+300]\n\n// For comparison, if we use parseInt() on the array above:\n[\"1.1\", \"2.2e2\", \"3e300\"].map((str) => parseInt(str)); // [1, 2, 3]\n
\n

One alternative output of the map method being called with parseInt as a parameter runs as follows:

\n

js

\n
const strings = [\"10\", \"10\", \"10\"];\nconst numbers = strings.map(parseInt);\n\nconsole.log(numbers);\n// Actual result of [10, NaN, 2] may be unexpected based on the above description.\n
\n
\n

Mapped array contains undefined

\n
\n

When undefined or nothing is returned:

\n

js

\n
const numbers = [1, 2, 3, 4];\nconst filteredNumbers = numbers.map((num, index) => {\n  if (index < 3) {\n    return num;\n  }\n});\n\n// index goes from 0, so the filterNumbers are 1,2,3 and undefined.\n// filteredNumbers is [1, 2, 3, undefined]\n// numbers is still [1, 2, 3, 4]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.map
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
map1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\n

\n
\n", + "global_objects/array/reduce": "

Array.prototype.reduce()

\n

The reduce() method of Array instances executes a user-supplied \"reducer\" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no \"return value of the previous calculation\". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Perhaps the easiest-to-understand case for reduce() is to return the sum of all the elements in an array:

\n
\n

Try it

\n
\n

The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.

\n

Syntax

\n
\n

js

\n
reduce(callbackFn)\nreduce(callbackFn, initialValue)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:

accumulator

The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].

currentValue

The value of the current element. On the first call, its value is array[0] if initialValue is specified; otherwise its value is array[1].

currentIndex

The index position of currentValue in the array. On the first call, its value is 0 if initialValue is specified, otherwise 1.

array

The array reduce() was called upon.

\ninitialValue Optional\n

A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue. If initialValue is not specified, accumulator is initialized to the first value in the array, and callbackFn starts executing with the second value in the array as currentValue. In this case, if the array is empty (so that there's no first value to return as accumulator), an error is thrown.

Return value

\n

The value that results from running the \"reducer\" callback function to completion over the entire array.

Exceptions

\n
TypeError

Thrown if the array contains no elements and initialValue is not provided.

Description

\n
\n

The reduce() method is an iterative method. It runs a \"reducer\" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of callbackFn is passed into callbackFn again on next invocation as accumulator. The final value of accumulator (which is the value returned from callbackFn on the final iteration of the array) becomes the return value of reduce().

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, reduce() does not accept a thisArg argument. callbackFn is always called with undefined as this, which gets substituted with globalThis if callbackFn is non-strict.

reduce() is a central concept in functional programming, where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's reduce(): you should use spreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined.

reduce() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The reduce() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Edge cases

\n
\n

If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callbackFn.

If initialValue is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.

If initialValue is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:

\n

js

\n
const getMax = (a, b) => Math.max(a, b);\n\n// callback is invoked for each element in the array starting at index 0\n[1, 100].reduce(getMax, 50); // 100\n[50].reduce(getMax, 10); // 50\n\n// callback is invoked once for element at index 1\n[1, 100].reduce(getMax); // 100\n\n// callback is not invoked\n[50].reduce(getMax); // 50\n[].reduce(getMax, 1); // 1\n\n[].reduce(getMax); // TypeError\n
\n
\n

Examples

\n

How reduce() works without an initial value

\n
\n

The code below shows what happens if we call reduce() with an array and no initial value.

\n

js

\n
const array = [15, 16, 17, 18, 19];\n\nfunction reducer(accumulator, currentValue, index) {\n  const returns = accumulator + currentValue;\n  console.log(\n    `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,\n  );\n  return returns;\n}\n\narray.reduce(reducer);\n
\n

The callback would be invoked four times, with the arguments and return values in each call being as follows:

accumulator currentValue index Return value
First call 15 16 1 31
Second call 31 17 2 48
Third call 48 18 3 66
Fourth call 66 19 4 85

The array parameter never changes through the process — it's always [15, 16, 17, 18, 19]. The value returned by reduce() would be that of the last callback invocation (85).

\n

How reduce() works with an initial value

\n
\n

Here we reduce the same array using the same algorithm, but with an initialValue of 10 passed as the second argument to reduce():

\n

js

\n
[15, 16, 17, 18, 19].reduce(\n  (accumulator, currentValue) => accumulator + currentValue,\n  10,\n);\n
\n

The callback would be invoked five times, with the arguments and return values in each call being as follows:

accumulator currentValue index Return value
First call 10 15 0 25
Second call 25 16 1 41
Third call 41 17 2 58
Fourth call 58 18 3 76
Fifth call 76 19 4 95

The value returned by reduce() in this case would be 95.

\n

Sum of values in an object array

\n
\n

To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.

\n

js

\n
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];\nconst sum = objects.reduce(\n  (accumulator, currentValue) => accumulator + currentValue.x,\n  0,\n);\n\nconsole.log(sum); // 6\n
\n
\n

Function sequential piping

\n
\n

The pipe function takes a sequence of functions and returns a new function. When the new function is called with an argument, the sequence of functions are called in order, which each one receiving the return value of the previous function.

\n

js

\n
const pipe =\n  (...functions) =>\n  (initialValue) =>\n    functions.reduce((acc, fn) => fn(acc), initialValue);\n\n// Building blocks to use for composition\nconst double = (x) => 2 * x;\nconst triple = (x) => 3 * x;\nconst quadruple = (x) => 4 * x;\n\n// Composed functions for multiplication of specific values\nconst multiply6 = pipe(double, triple);\nconst multiply9 = pipe(triple, triple);\nconst multiply16 = pipe(quadruple, quadruple);\nconst multiply24 = pipe(double, triple, quadruple);\n\n// Usage\nmultiply6(6); // 36\nmultiply9(9); // 81\nmultiply16(16); // 256\nmultiply24(10); // 240\n
\n
\n

Running promises in sequence

\n
\n

Promise sequencing is essentially function piping demonstrated in the previous section, except done asynchronously.

\n

js

\n
// Compare this with pipe: fn(acc) is changed to acc.then(fn),\n// and initialValue is ensured to be a promise\nconst asyncPipe =\n  (...functions) =>\n  (initialValue) =>\n    functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue));\n\n// Building blocks to use for composition\nconst p1 = async (a) => a * 5;\nconst p2 = async (a) => a * 2;\n// The composed functions can also return non-promises, because the values are\n// all eventually wrapped in promises\nconst f3 = (a) => a * 3;\nconst p4 = async (a) => a * 4;\n\nasyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200\n
\n

asyncPipe can also be implemented using async/await, which better demonstrates its similarity with pipe:

\n

js

\n
const asyncPipe =\n  (...functions) =>\n  (initialValue) =>\n    functions.reduce(async (acc, fn) => fn(await acc), initialValue);\n
\n
\n

Using reduce() with sparse arrays

\n
\n

reduce() skips missing elements in sparse arrays, but it does not skip undefined values.

\n

js

\n
console.log([1, 2, , 4].reduce((a, b) => a + b)); // 7\nconsole.log([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN\n
\n
\n

Calling reduce() on non-array objects

\n
\n

The reduce() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 99, // ignored by reduce() since length is 3\n};\nconsole.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));\n// 9\n
\n
\n

When to not use reduce()

\n
\n

Multipurpose higher-order functions like reduce() can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using reduce().

Note that reduce() is always equivalent to a for...of loop, except that instead of mutating a variable in the upper scope, we now return the new value for each iteration:

\n

js

\n
const val = array.reduce((acc, cur) => update(acc, cur), initialValue);\n\n// Is equivalent to:\nlet val = initialValue;\nfor (const cur of array) {\n  val = update(val, cur);\n}\n
\n

As previously stated, the reason why people may want to use reduce() is to mimic functional programming practices of immutable data. Therefore, developers who uphold the immutability of the accumulator often copy the entire accumulator for each iteration, like this:

\n

js

\n
const names = [\"Alice\", \"Bob\", \"Tiff\", \"Bruce\", \"Alice\"];\nconst countedNames = names.reduce((allNames, name) => {\n  const currCount = Object.hasOwn(allNames, name) ? allNames[name] : 0;\n  return {\n    ...allNames,\n    [name]: currCount + 1,\n  };\n}, {});\n
\n

This code is ill-performing, because each iteration has to copy the entire allNames object, which could be big, depending how many unique names there are. This code has worst-case O(N^2) performance, where N is the length of names.

A better alternative is to mutate the allNames object on each iteration. However, if allNames gets mutated anyway, you may want to convert the reduce() to a simple for loop instead, which is much clearer:

\n

js

\n
const names = [\"Alice\", \"Bob\", \"Tiff\", \"Bruce\", \"Alice\"];\nconst countedNames = names.reduce((allNames, name) => {\n  const currCount = allNames[name] ?? 0;\n  allNames[name] = currCount + 1;\n  // return allNames, otherwise the next iteration receives undefined\n  return allNames;\n}, Object.create(null));\n
\n
\n

js

\n
const names = [\"Alice\", \"Bob\", \"Tiff\", \"Bruce\", \"Alice\"];\nconst countedNames = Object.create(null);\nfor (const name of names) {\n  const currCount = countedNames[name] ?? 0;\n  countedNames[name] = currCount + 1;\n}\n
\n

Therefore, if your accumulator is an array or an object and you are copying the array or object on each iteration, you may accidentally introduce quadratic complexity into your code, causing performance to quickly degrade on large data.

Some of the acceptable use cases of reduce() are given above (most notably, summing an array, promise sequencing, and function piping). There are other cases where better alternatives than reduce() exist.

In cases where reduce() is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.reduce
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reduce3123910.54≤37184143.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\n

\n
\n", + "global_objects/array/reduceright": "

Array.prototype.reduceRight()

\n

The reduceRight() method of Array instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

See also Array.prototype.reduce() for left-to-right.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
reduceRight(callbackFn)\nreduceRight(callbackFn, initialValue)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduceRight(). The function is called with the following arguments:

accumulator

The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is the last element of the array.

currentValue

The value of the current element. On the first call, its value is the last element if initialValue is specified; otherwise its value is the second-to-last element.

currentIndex

The index position of currentValue in the array. On the first call, its value is array.length - 1 if initialValue is specified, otherwise array.length - 2.

array

The array reduceRight() was called upon.

\ninitialValue Optional\n

Value to use as accumulator to the first call of the callbackFn. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduceRight() on an empty array without an initial value creates a TypeError.

Return value

\n

The value that results from the reduction.

Description

\n
\n

The reduceRight() method is an iterative method. It runs a \"reducer\" callback function over all elements in the array, in descending-index order, and accumulates them into a single value.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, reduceRight() does not accept a thisArg argument. callbackFn is always called with undefined as this, which gets substituted with globalThis if callbackFn is non-strict.

reduceRight() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The reduceRight() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

How reduceRight() works without an initial value

\n
\n

The call to the reduceRight callbackFn would look something like this:

\n

js

\n
arr.reduceRight((accumulator, currentValue, index, array) => {\n  // …\n});\n
\n

The first time the function is called, the accumulator and currentValue can be one of two values. If an initialValue was provided in the call to reduceRight, then accumulator will be equal to initialValue and currentValue will be equal to the last value in the array. If no initialValue was provided, then accumulator will be equal to the last value in the array and currentValue will be equal to the second-to-last value.

If the array is empty and no initialValue was provided, TypeError would be thrown. If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callbackFn.

Some example run-throughs of the function would look like this:

\n

js

\n
[0, 1, 2, 3, 4].reduceRight(\n  (accumulator, currentValue, index, array) => accumulator + currentValue,\n);\n
\n

The callback would be invoked four times, with the arguments and return values in each call being as follows:

accumulator currentValue index Return value
First call 4 3 3 7
Second call 7 2 2 9
Third call 9 1 1 10
Fourth call 10 0 0 10

The array parameter never changes through the process — it's always [0, 1, 2, 3, 4]. The value returned by reduceRight would be that of the last callback invocation (10).

\n

How reduceRight() works with an initial value

\n
\n

Here we reduce the same array using the same algorithm, but with an initialValue of 10 passed as the second argument to reduceRight():

\n

js

\n
[0, 1, 2, 3, 4].reduceRight(\n  (accumulator, currentValue, index, array) => accumulator + currentValue,\n  10,\n);\n
\n
accumulator currentValue index Return value
First call 10 4 4 14
Second call 14 3 3 17
Third call 17 2 2 19
Fourth call 19 1 1 20
Fifth call 20 0 0 20

The value returned by reduceRight this time would be, of course, 20.

\n

Sum up all values within an array

\n
\n

js

\n
const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b);\n// sum is 6\n
\n

Run a list of asynchronous functions with callbacks in series each passing their results to the next

\n
\n

js

\n
const waterfall =\n  (...functions) =>\n  (callback, ...args) =>\n    functions.reduceRight(\n      (composition, fn) =>\n        (...results) =>\n          fn(composition, ...results),\n      callback,\n    )(...args);\n\nconst randInt = (max) => Math.floor(Math.random() * max);\n\nconst add5 = (callback, x) => {\n  setTimeout(callback, randInt(1000), x + 5);\n};\nconst mult3 = (callback, x) => {\n  setTimeout(callback, randInt(1000), x * 3);\n};\nconst sub2 = (callback, x) => {\n  setTimeout(callback, randInt(1000), x - 2);\n};\nconst split = (callback, x) => {\n  setTimeout(callback, randInt(1000), x, x);\n};\nconst add = (callback, x, y) => {\n  setTimeout(callback, randInt(1000), x + y);\n};\nconst div4 = (callback, x) => {\n  setTimeout(callback, randInt(1000), x / 4);\n};\n\nconst computation = waterfall(add5, mult3, sub2, split, add, div4);\ncomputation(console.log, 5); // Logs 14\n\n// same as:\n\nconst computation2 = (input, callback) => {\n  const f6 = (x) => div4(callback, x);\n  const f5 = (x, y) => add(f6, x, y);\n  const f4 = (x) => split(f5, x);\n  const f3 = (x) => sub2(f4, x);\n  const f2 = (x) => mult3(f3, x);\n  add5(f2, input);\n};\n
\n

Difference between reduce and reduceRight

\n
\n

js

\n
const a = [\"1\", \"2\", \"3\", \"4\", \"5\"];\nconst left = a.reduce((prev, cur) => prev + cur);\nconst right = a.reduceRight((prev, cur) => prev + cur);\n\nconsole.log(left); // \"12345\"\nconsole.log(right); // \"54321\"\n
\n

Defining composable functions

\n
\n

Function composition is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. In this example we use reduceRight() to implement function composition.

See also Function composition on Wikipedia.

\n

js

\n
const compose =\n  (...args) =>\n  (value) =>\n    args.reduceRight((acc, fn) => fn(acc), value);\n\n// Increment passed number\nconst inc = (n) => n + 1;\n\n// Doubles the passed value\nconst double = (n) => n * 2;\n\n// using composition function\nconsole.log(compose(double, inc)(2)); // 6\n\n// using composition function\nconsole.log(compose(inc, double)(2)); // 5\n
\n
\n

Using reduceRight() with sparse arrays

\n
\n

reduceRight() skips missing elements in sparse arrays, but it does not skip undefined values.

\n

js

\n
console.log([1, 2, , 4].reduceRight((a, b) => a + b)); // 7\nconsole.log([1, 2, undefined, 4].reduceRight((a, b) => a + b)); // NaN\n
\n
\n

Calling reduceRight() on non-array objects

\n
\n

The reduceRight() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 3,\n  2: 4,\n  3: 99, // ignored by reduceRight() since length is 3\n};\nconsole.log(Array.prototype.reduceRight.call(arrayLike, (x, y) => x - y));\n// -1, which is 4 - 3 - 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.reduceright
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reduceRight3123910.54≤37184143.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight\n

\n
\n", + "global_objects/array/reverse": "

Array.prototype.reverse()

\n

The reverse() method of Array instances reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

To reverse the elements in an array without mutating the original array, use toReversed().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
reverse()\n
\n

Parameters

\n

None.

Return value

\n

The reference to the original array, now reversed. Note that the array is reversed in place, and no copy is made.

Description

\n
\n

The reverse() method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

The reverse() method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.

The reverse() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Reversing the elements in an array

\n
\n

The following example creates an array items, containing three elements, then reverses the array. The call to reverse() returns a reference to the reversed array items.

\n

js

\n
const items = [1, 2, 3];\nconsole.log(items); // [1, 2, 3]\n\nitems.reverse();\nconsole.log(items); // [3, 2, 1]\n
\n
\n

The reverse() method returns the reference to the same array

\n
\n

The reverse() method returns reference to the original array, so mutating the returned array will mutate the original array as well.

\n

js

\n
const numbers = [3, 2, 4, 1, 5];\nconst reversed = numbers.reverse();\n// numbers and reversed are both in reversed order [5, 1, 4, 2, 3]\nreversed[0] = 5;\nconsole.log(numbers[0]); // 5\n
\n

In case you want reverse() to not mutate the original array, but return a shallow-copied array like other array methods (e.g. map()) do, use the toReversed() method. Alternatively, you can do a shallow copy before calling reverse(), using the spread syntax or Array.from().

\n

js

\n
const numbers = [3, 2, 4, 1, 5];\n// [...numbers] creates a shallow copy, so reverse() does not mutate the original\nconst reverted = [...numbers].reverse();\nreverted[0] = 5;\nconsole.log(numbers[0]); // 3\n
\n
\n

Using reverse() on sparse arrays

\n
\n

Sparse arrays remain sparse after calling reverse(). Empty slots are copied over to their respective new indices as empty slots.

\n

js

\n
console.log([1, , 3].reverse()); // [3, empty, 1]\nconsole.log([1, , 3, 4].reverse()); // [4, 3, empty, 1]\n
\n
\n

Calling reverse() on non-array objects

\n
\n

The reverse() method reads the length property of this. It then visits each property having an integer key between 0 and length / 2, and swaps the two corresponding indices on both ends, deleting any destination property for which the source property did not exist.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n  3: 33, // ignored by reverse() since length is 3\n};\nconsole.log(Array.prototype.reverse.call(arrayLike));\n// { 0: 4, 3: 33, length: 3, unrelated: 'foo' }\n// The index 2 is deleted because there was no index 0 present originally\n// The index 3 is unchanged since the length is 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.reverse
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reverse11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse\n

\n
\n", + "global_objects/array/some": "

Array.prototype.some()

The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
some(callbackFn)\nsome(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array some() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

false unless callbackFn returns a truthy value for an array element, in which case true is immediately returned.

Description

\n
\n

The some() method is an iterative method. It calls a provided callbackFn function once for each element in an array, until the callbackFn returns a truthy value. If such an element is found, some() immediately returns true and stops iterating through the array. Otherwise, if callbackFn returns a falsy value for all elements, some() returns false.

some() acts like the \"there exists\" quantifier in mathematics. In particular, for an empty array, it returns false for any condition.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

some() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The some() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Testing value of array elements

\n
\n

The following example tests whether any element in the array is bigger than 10.

\n

js

\n
function isBiggerThan10(element, index, array) {\n  return element > 10;\n}\n\n[2, 5, 8, 1, 4].some(isBiggerThan10); // false\n[12, 5, 8, 1, 4].some(isBiggerThan10); // true\n
\n
\n

Testing array elements using arrow functions

\n
\n

Arrow functions provide a shorter syntax for the same test.

\n

js

\n
[2, 5, 8, 1, 4].some((x) => x > 10); // false\n[12, 5, 8, 1, 4].some((x) => x > 10); // true\n
\n
\n

Checking whether a value exists in an array

\n
\n

To mimic the function of the includes() method, this custom function returns true if the element exists in the array:

\n

js

\n
const fruits = [\"apple\", \"banana\", \"mango\", \"guava\"];\n\nfunction checkAvailability(arr, val) {\n  return arr.some((arrVal) => val === arrVal);\n}\n\ncheckAvailability(fruits, \"kela\"); // false\ncheckAvailability(fruits, \"banana\"); // true\n
\n
\n

Converting any value to Boolean

\n
\n

js

\n
const TRUTHY_VALUES = [true, \"true\", 1];\n\nfunction getBoolean(value) {\n  if (typeof value === \"string\") {\n    value = value.toLowerCase().trim();\n  }\n\n  return TRUTHY_VALUES.some((t) => t === value);\n}\n\ngetBoolean(false); // false\ngetBoolean(\"false\"); // false\ngetBoolean(1); // true\ngetBoolean(\"true\"); // true\n
\n

Using some() on sparse arrays

\n
\n

some() will not run its predicate on empty slots.

\n

js

\n
console.log([1, , 3].some((x) => x === undefined)); // false\nconsole.log([1, , 1].some((x) => x !== 1)); // false\nconsole.log([1, undefined, 1].some((x) => x !== 1)); // true\n
\n
\n

Calling some() on non-array objects

\n
\n

The some() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length until they all have been accessed or callbackFn returns true.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\",\n  3: 3, // ignored by some() since length is 3\n};\nconsole.log(Array.prototype.some.call(arrayLike, (x) => typeof x === \"number\"));\n// false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.some
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
some1121.599.53≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\n

\n
\n", + "global_objects/array/sort": "

Array.prototype.sort()

\n

The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

To sort the elements in an array without mutating the original array, use toSorted().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
sort()\nsort(compareFn)\n
\n

Parameters

\n
\ncompareFn Optional\n

A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if a is less than b, positive if a is greater than b, and zero if they are equal. NaN is treated as 0. The function is called with the following arguments:

a

The first element for comparison. Will never be undefined.

b

The second element for comparison. Will never be undefined.

If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

Return value

\n

The reference to the original array, now sorted. Note that the array is sorted in place, and no copy is made.

Description

\n
\n

If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, \"banana\" comes before \"cherry\". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, \"80\" comes before \"9\" in the Unicode order. All undefined elements are sorted to the end of the array.

The sort() method preserves empty slots. If the source array is sparse, the empty slots are moved to the end of the array, and always come after all the undefined.

Note: In UTF-16, Unicode characters above \\uFFFF are encoded as two surrogate code units, of the range \\uD800 - \\uDFFF. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \\uD855\\uDE51 will be sorted before the character \\uFF3A.

If compareFn is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFn).

\ncompareFn(a, b) return value sort order
> 0 sort a after b, e.g. [b, a]\n
< 0 sort a before b, e.g. [a, b]\n
=== 0 keep original order of a and b\n

So, the compare function has the following form:

\n

js

\n
function compareFn(a, b) {\n  if (a is less than b by some ordering criterion) {\n    return -1;\n  } else if (a is greater than b by the ordering criterion) {\n    return 1;\n  }\n  // a must be equal to b\n  return 0;\n}\n
\n

More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior:

A comparator conforming to the constraints above will always be able to return all of 1, 0, and -1, or consistently return 0. For example, if a comparator only returns 1 and 0, or only returns 0 and -1, it will not be able to sort reliably because anti-symmetry is broken. A comparator that always returns 0 will cause the array to not be changed at all, but is reliable nonetheless.

The default lexicographic comparator satisfies all constraints above.

To compare numbers instead of strings, the compare function can subtract b from a. The following function will sort the array in ascending order (if it doesn't contain NaN):

\n

js

\n
function compareNumbers(a, b) {\n  return a - b;\n}\n
\n

The sort() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Creating, displaying, and sorting an array

\n
\n

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.

\n

js

\n
const stringArray = [\"Blue\", \"Humpback\", \"Beluga\"];\nconst numberArray = [40, 1, 5, 200];\nconst numericStringArray = [\"80\", \"9\", \"700\"];\nconst mixedNumericArray = [\"80\", \"9\", \"700\", 40, 1, 5, 200];\n\nfunction compareNumbers(a, b) {\n  return a - b;\n}\n\nstringArray.join(); // 'Blue,Humpback,Beluga'\nstringArray.sort(); // ['Beluga', 'Blue', 'Humpback']\n\nnumberArray.join(); // '40,1,5,200'\nnumberArray.sort(); // [1, 200, 40, 5]\nnumberArray.sort(compareNumbers); // [1, 5, 40, 200]\n\nnumericStringArray.join(); // '80,9,700'\nnumericStringArray.sort(); // ['700', '80', '9']\nnumericStringArray.sort(compareNumbers); // ['9', '80', '700']\n\nmixedNumericArray.join(); // '80,9,700,40,1,5,200'\nmixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']\nmixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']\n
\n
\n

Sorting array of objects

\n
\n

Arrays of objects can be sorted by comparing the value of one of their properties.

\n

js

\n
const items = [\n  { name: \"Edward\", value: 21 },\n  { name: \"Sharpe\", value: 37 },\n  { name: \"And\", value: 45 },\n  { name: \"The\", value: -12 },\n  { name: \"Magnetic\", value: 13 },\n  { name: \"Zeros\", value: 37 },\n];\n\n// sort by value\nitems.sort((a, b) => a.value - b.value);\n\n// sort by name\nitems.sort((a, b) => {\n  const nameA = a.name.toUpperCase(); // ignore upper and lowercase\n  const nameB = b.name.toUpperCase(); // ignore upper and lowercase\n  if (nameA < nameB) {\n    return -1;\n  }\n  if (nameA > nameB) {\n    return 1;\n  }\n\n  // names must be equal\n  return 0;\n});\n
\n
\n

Sorting non-ASCII characters

\n
\n

For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English, use String.prototype.localeCompare(). This function can compare those characters so they appear in the right order.

\n

js

\n
const items = [\"réservé\", \"premier\", \"communiqué\", \"café\", \"adieu\", \"éclair\"];\nitems.sort((a, b) => a.localeCompare(b));\n\n// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']\n
\n
\n

Sorting with map

\n
\n

The compareFn can be invoked multiple times per element within the array. Depending on the compareFn's nature, this may yield a high overhead. The more work a compareFn does and the more elements there are to sort, it may be more efficient to use map() for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order.

\n

js

\n
// the array to be sorted\nconst data = [\"delta\", \"alpha\", \"charlie\", \"bravo\"];\n\n// temporary array holds objects with position and sort-value\nconst mapped = data.map((v, i) => {\n  return { i, value: someSlowOperation(v) };\n});\n\n// sorting the mapped array containing the reduced values\nmapped.sort((a, b) => {\n  if (a.value > b.value) {\n    return 1;\n  }\n  if (a.value < b.value) {\n    return -1;\n  }\n  return 0;\n});\n\nconst result = mapped.map((v) => data[v.i]);\n
\n

There is an open source library available called mapsort which applies this approach.

\n

sort() returns the reference to the same array

\n
\n

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

\n

js

\n
const numbers = [3, 1, 4, 1, 5];\nconst sorted = numbers.sort((a, b) => a - b);\n// numbers and sorted are both [1, 1, 3, 4, 5]\nsorted[0] = 10;\nconsole.log(numbers[0]); // 10\n
\n

In case you want sort() to not mutate the original array, but return a shallow-copied array like other array methods (e.g. map()) do, use the toSorted() method. Alternatively, you can do a shallow copy before calling sort(), using the spread syntax or Array.from().

\n

js

\n
const numbers = [3, 1, 4, 1, 5];\n// [...numbers] creates a shallow copy, so sort() does not mutate the original\nconst sorted = [...numbers].sort((a, b) => a - b);\nsorted[0] = 10;\nconsole.log(numbers[0]); // 3\n
\n
\n

Sort stability

\n
\n

Since version 10 (or ECMAScript 2019), the specification dictates that Array.prototype.sort is stable.

For example, say you had a list of students alongside their grades. Note that the list of students is already pre-sorted by name in alphabetical order:

\n

js

\n
const students = [\n  { name: \"Alex\", grade: 15 },\n  { name: \"Devlin\", grade: 15 },\n  { name: \"Eagle\", grade: 13 },\n  { name: \"Sam\", grade: 14 },\n];\n
\n

After sorting this array by grade in ascending order:

\n

js

\n
students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade);\n
\n

The students variable will then have the following value:

\n

js

\n
[\n  { name: \"Eagle\", grade: 13 },\n  { name: \"Sam\", grade: 14 },\n  { name: \"Alex\", grade: 15 }, // original maintained for similar grade (stable sorting)\n  { name: \"Devlin\", grade: 15 }, // original maintained for similar grade (stable sorting)\n];\n
\n

It's important to note that students that have the same grade (for example, Alex and Devlin), will remain in the same order as before calling the sort. This is what a stable sorting algorithm guarantees.

Before version 10 (or ECMAScript 2019), sort stability was not guaranteed, meaning that you could end up with the following:

\n

js

\n
[\n  { name: \"Eagle\", grade: 13 },\n  { name: \"Sam\", grade: 14 },\n  { name: \"Devlin\", grade: 15 }, // original order not maintained\n  { name: \"Alex\", grade: 15 }, // original order not maintained\n];\n
\n
\n

Sorting with non-well-formed comparator

\n
\n

If a comparing function does not satisfy all of purity, stability, reflexivity, anti-symmetry, and transitivity rules, as explained in the description, the program's behavior is not well-defined.

For example, consider this code:

\n

js

\n
const arr = [3, 1, 4, 1, 5, 9];\nconst compareFn = (a, b) => (a > b ? 1 : 0);\narr.sort(compareFn);\n
\n

The compareFn function here is not well-formed, because it does not satisfy anti-symmetry: if a > b, it returns 1; but by swapping a and b, it returns 0 instead of a negative value. Therefore, the resulting array will be different across engines. For example, V8 (used by Chrome, Node.js, etc.) and JavaScriptCore (used by Safari) would not sort the array at all and return [3, 1, 4, 1, 5, 9], while SpiderMonkey (used by Firefox) will return the array sorted ascendingly, as [1, 1, 3, 4, 5, 9].

However, if the compareFn function is changed slightly so that it returns -1 or 0:

\n

js

\n
const arr = [3, 1, 4, 1, 5, 9];\nconst compareFn = (a, b) => (a > b ? -1 : 0);\narr.sort(compareFn);\n
\n

Then V8 and JavaScriptCore sorts it descendingly, as [9, 5, 4, 3, 1, 1], while SpiderMonkey returns it as-is: [3, 1, 4, 1, 5, 9].

Due to this implementation inconsistency, you are always advised to make your comparator well-formed by following the five constraints.

\n

Using sort() on sparse arrays

\n
\n

Empty slots are moved to the end of the array.

\n

js

\n
console.log([\"a\", \"c\", , \"b\"].sort()); // ['a', 'b', 'c', empty]\nconsole.log([, undefined, \"a\", \"b\"].sort()); // [\"a\", \"b\", undefined, empty]\n
\n
\n

Calling sort() on non-array objects

\n
\n

The sort() method reads the length property of this. It then collects all existing integer-keyed properties in the range of 0 to length - 1, sorts them, and writes them back. If there are missing properties in the range, the corresponding trailing properties are deleted, as if the non-existent properties are sorted towards the end.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  0: 5,\n  2: 4,\n};\nconsole.log(Array.prototype.sort.call(arrayLike));\n// { '0': 4, '1': 5, length: 3, unrelated: 'foo' }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.sort
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sort11215.5414.418410.111.01.00.10.0
stable70793No5710.1707044910.310.01.012.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\n

\n
\n", + "global_objects/array/entries": "

Array.prototype.entries()

The entries() method of Array instances returns a new array iterator object that contains the key/value pairs for each index in the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
entries()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n
\n

When used on sparse arrays, the entries() method iterates empty slots as if they have the value undefined.

The entries() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Iterating with index and element

\n
\n

js

\n
const a = [\"a\", \"b\", \"c\"];\n\nfor (const [index, element] of a.entries()) {\n  console.log(index, element);\n}\n\n// 0 'a'\n// 1 'b'\n// 2 'c'\n
\n

Using a for...of loop

\n
\n

js

\n
const array = [\"a\", \"b\", \"c\"];\nconst arrayEntries = array.entries();\n\nfor (const element of arrayEntries) {\n  console.log(element);\n}\n\n// [0, 'a']\n// [1, 'b']\n// [2, 'c']\n
\n

Iterating sparse arrays

\n
\n

entries() will visit empty slots as if they are undefined.

\n

js

\n
for (const element of [, \"a\"].entries()) {\n  console.log(element);\n}\n// [0, undefined]\n// [1, 'a']\n
\n
\n

Calling entries() on non-array objects

\n
\n

The entries() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\",\n  3: \"d\", // ignored by entries() since length is 3\n};\nfor (const entry of Array.prototype.entries.call(arrayLike)) {\n  console.log(entry);\n}\n// [ 0, 'a' ]\n// [ 1, 'b' ]\n// [ 2, 'c' ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.entries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
entries381228No2583838282583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries\n

\n
\n", + "global_objects/array/fill": "

Array.prototype.fill()

The fill() method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.

\n

Try it

\n

Syntax

\n
\n

js

\n
fill(value)\nfill(value, start)\nfill(value, start, end)\n
\n

Parameters

\n
value

Value to fill the array with. Note all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object.

\nstart Optional\n

Zero-based index at which to start filling, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length or start is omitted, 0 is used.
  • If start >= array.length, no index is filled.
\nend Optional\n

Zero-based index at which to end filling, converted to an integer. fill() fills up to but not including end.

  • Negative index counts back from the end of the array — if end < 0, end + array.length is used.
  • If end < -array.length, 0 is used.
  • If end >= array.length or end is omitted, array.length is used, causing all indices until the end to be filled.
  • If end is positioned before or at start after normalization, no index is filled.

Return value

\n

The modified array, filled with value.

Description

\n
\n

The fill() method is a mutating method. It does not alter the length of this, but it will change the content of this.

The fill() method fills empty slots in sparse arrays with value as well.

The fill() method is generic. It only expects the this value to have a length property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Note: Using Array.prototype.fill() on an empty array (length = 0) would not modify it as the array has nothing to be modified. To use Array.prototype.fill() when declaring an array, make sure the array has non-zero length. See example.

\n

Examples

\n

Using fill()

\n
\n

js

\n
console.log([1, 2, 3].fill(4)); // [4, 4, 4]\nconsole.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]\nconsole.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]\nconsole.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]\nconsole.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]\nconsole.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]\nconsole.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]\nconsole.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]\nconsole.log(Array(3).fill(4)); // [4, 4, 4]\n\n// A single object, referenced by each slot of the array:\nconst arr = Array(3).fill({}); // [{}, {}, {}]\narr[0].hi = \"hi\"; // [{ hi: \"hi\" }, { hi: \"hi\" }, { hi: \"hi\" }]\n
\n

Using fill() to create a matrix of all 1

\n
\n

This example shows how to create a matrix of all 1, like the ones() function of Octave or MATLAB.

\n

js

\n
const arr = new Array(3);\nfor (let i = 0; i < arr.length; i++) {\n  arr[i] = new Array(4).fill(1); // Creating an array of size 4 and filled of 1\n}\narr[0][0] = 10;\nconsole.log(arr[0][0]); // 10\nconsole.log(arr[1][0]); // 1\nconsole.log(arr[2][0]); // 1\n
\n
\n

Using fill() to populate an empty array

\n
\n

This example shows how to populate an array, setting all elements to a specific value. The end parameter does not have to be specified.

\n

js

\n
const tempGirls = Array(5).fill(\"girl\", 0);\n
\n

Note that the array was initially a sparse array with no assigned indices. fill() is still able to fill this array.

\n

Calling fill() on non-array objects

\n
\n

The fill() method reads the length property of this and sets the value of each integer-keyed property from start to end.

\n

js

\n
const arrayLike = { length: 2 };\nconsole.log(Array.prototype.fill.call(arrayLike, 1));\n// { '0': 1, '1': 1, length: 2 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.fill
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fill451231No3284545313285.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\n

\n
\n", + "global_objects/array/find": "

Array.prototype.find()

\n

The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
find(callbackFn)\nfind(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array find() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Description

\n
\n

The find() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. find() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, find() returns undefined.

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

find() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The find() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Find an object in an array by one of its properties

\n
\n
\n

js

\n
const inventory = [\n  { name: \"apples\", quantity: 2 },\n  { name: \"bananas\", quantity: 0 },\n  { name: \"cherries\", quantity: 5 },\n];\n\nfunction isCherries(fruit) {\n  return fruit.name === \"cherries\";\n}\n\nconsole.log(inventory.find(isCherries));\n// { name: 'cherries', quantity: 5 }\n
\n

Using arrow function and destructuring

\n

js

\n
const inventory = [\n  { name: \"apples\", quantity: 2 },\n  { name: \"bananas\", quantity: 0 },\n  { name: \"cherries\", quantity: 5 },\n];\n\nconst result = inventory.find(({ name }) => name === \"cherries\");\n\nconsole.log(result); // { name: 'cherries', quantity: 5 }\n
\n
\n

Find a prime number in an array

\n
\n

The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):

\n

js

\n
function isPrime(element, index, array) {\n  let start = 2;\n  while (start <= Math.sqrt(element)) {\n    if (element % start++ < 1) {\n      return false;\n    }\n  }\n  return element > 1;\n}\n\nconsole.log([4, 6, 8, 12].find(isPrime)); // undefined, not found\nconsole.log([4, 5, 8, 12].find(isPrime)); // 5\n
\n
\n

Using find() on sparse arrays

\n
\n

Empty slots in sparse arrays are visited, and are treated the same as undefined.

\n

js

\n
// Declare array with no elements at indexes 2, 3, and 4\nconst array = [0, 1, , , , 5, 6];\n\n// Shows all indexes, not just those with assigned values\narray.find((value, index) => {\n  console.log(\"Visited index\", index, \"with value\", value);\n});\n// Visited index 0 with value 0\n// Visited index 1 with value 1\n// Visited index 2 with value undefined\n// Visited index 3 with value undefined\n// Visited index 4 with value undefined\n// Visited index 5 with value 5\n// Visited index 6 with value 6\n\n// Shows all indexes, including deleted\narray.find((value, index) => {\n  // Delete element 5 on first iteration\n  if (index === 0) {\n    console.log(\"Deleting array[5] with value\", array[5]);\n    delete array[5];\n  }\n  // Element 5 is still visited even though deleted\n  console.log(\"Visited index\", index, \"with value\", value);\n});\n// Deleting array[5] with value 5\n// Visited index 0 with value 0\n// Visited index 1 with value 1\n// Visited index 2 with value undefined\n// Visited index 3 with value undefined\n// Visited index 4 with value undefined\n// Visited index 5 with value undefined\n// Visited index 6 with value 6\n
\n
\n

Calling find() on non-array objects

\n
\n

The find() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  \"-1\": 0.1, // ignored by find() since -1 < 0\n  0: 2,\n  1: 7.3,\n  2: 4,\n};\nconsole.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)));\n// 7.3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.find
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
find451225No328454543285.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\n

\n
\n", + "global_objects/array/findindex": "

Array.prototype.findIndex()

\n

The findIndex() method of Array instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

See also the find() method, which returns the first element that satisfies the testing function (rather than its index).

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
findIndex(callbackFn)\nfindIndex(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array findIndex() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The index of the first element in the array that passes the test. Otherwise, -1.

Description

\n
\n

The findIndex() is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. findIndex() then returns the index of that element and stops iterating through the array. If callbackFn never returns a truthy value, findIndex() returns -1.

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

findIndex() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The findIndex() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Find the index of a prime number in an array

\n
\n

The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.

\n

js

\n
function isPrime(element) {\n  if (element % 2 === 0 || element < 2) {\n    return false;\n  }\n  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {\n    if (element % factor === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\nconsole.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found\nconsole.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)\n
\n
\n

Using findIndex() on sparse arrays

\n
\n

You can search for undefined in a sparse array and get the index of an empty slot.

\n

js

\n
console.log([1, , 3].findIndex((x) => x === undefined)); // 1\n
\n
\n

Calling findIndex() on non-array objects

\n
\n

The findIndex() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  \"-1\": 0.1, // ignored by findIndex() since -1 < 0\n  0: 2,\n  1: 7.3,\n  2: 4,\n};\nconsole.log(\n  Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),\n); // 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.findindex
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findIndex451225No328454543285.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\n

\n
\n", + "global_objects/array/findlast": "

Array.prototype.findLast()

\n

The findLast() method of Array instances iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.

If you need to find:

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
findLast(callbackFn)\nfindLast(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array findLast() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The last (highest-index) element in the array that satisfies the provided testing function; undefined if no matching element is found.

Description

\n
\n

The findLast() method is an iterative method. It calls a provided callbackFn function once for each element in an array in descending-index order, until callbackFn returns a truthy value. findLast() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, findLast() returns undefined.

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

findLast() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The findLast() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Find last object in an array matching on element properties

\n
\n

This example shows how you might create a test based on the properties of array elements.

\n

js

\n
const inventory = [\n  { name: \"apples\", quantity: 2 },\n  { name: \"bananas\", quantity: 0 },\n  { name: \"fish\", quantity: 1 },\n  { name: \"cherries\", quantity: 5 },\n];\n\n// return true inventory stock is low\nfunction isNotEnough(item) {\n  return item.quantity < 2;\n}\n\nconsole.log(inventory.findLast(isNotEnough));\n// { name: \"fish\", quantity: 1 }\n
\n

Using arrow function and destructuring

The previous example might be written using an arrow function and object destructuring:

\n

js

\n
const inventory = [\n  { name: \"apples\", quantity: 2 },\n  { name: \"bananas\", quantity: 0 },\n  { name: \"fish\", quantity: 1 },\n  { name: \"cherries\", quantity: 5 },\n];\n\nconst result = inventory.findLast(({ quantity }) => quantity < 2);\n\nconsole.log(result);\n// { name: \"fish\", quantity: 1 }\n
\n
\n

Find the last prime number in an array

\n
\n

The following example returns the last element in the array that is a prime number, or undefined if there is no prime number.

\n

js

\n
function isPrime(element) {\n  if (element % 2 === 0 || element < 2) {\n    return false;\n  }\n  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {\n    if (element % factor === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\nconsole.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found\nconsole.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11\n
\n
\n

Using findLast() on sparse arrays

\n
\n

Empty slots in sparse arrays are visited, and are treated the same as undefined.

\n

js

\n
// Declare array with no elements at indexes 2, 3, and 4\nconst array = [0, 1, , , , 5, 6];\n\n// Shows all indexes, not just those with assigned values\narray.findLast((value, index) => {\n  console.log(`Visited index ${index} with value ${value}`);\n});\n// Visited index 6 with value 6\n// Visited index 5 with value 5\n// Visited index 4 with value undefined\n// Visited index 3 with value undefined\n// Visited index 2 with value undefined\n// Visited index 1 with value 1\n// Visited index 0 with value 0\n\n// Shows all indexes, including deleted\narray.findLast((value, index) => {\n  // Delete element 5 on first iteration\n  if (index === 6) {\n    console.log(`Deleting array[5] with value ${array[5]}`);\n    delete array[5];\n  }\n  // Element 5 is still visited even though deleted\n  console.log(`Visited index ${index} with value ${value}`);\n});\n// Deleting array[5] with value 5\n// Visited index 6 with value 6\n// Visited index 5 with value undefined\n// Visited index 4 with value undefined\n// Visited index 3 with value undefined\n// Visited index 2 with value undefined\n// Visited index 1 with value 1\n// Visited index 0 with value 0\n
\n
\n

Calling findLast() on non-array objects

\n
\n

The findLast() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 7.3,\n  2: 4,\n  3: 3, // ignored by findLast() since length is 3\n};\nconsole.log(\n  Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)),\n); // 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.findlast
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findLast9797104No8315.497971046815.418.01.1618.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast\n

\n
\n", + "global_objects/array/findlastindex": "

Array.prototype.findLastIndex()

\n

The findLastIndex() method of Array instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

See also the findLast() method, which returns the value of last element that satisfies the testing function (rather than its index).

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
findLastIndex(callbackFn)\nfindLastIndex(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array findLastIndex() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The index of the last (highest-index) element in the array that passes the test. Otherwise -1 if no matching element is found.

Description

\n
\n

The findLastIndex() method is an iterative method. It calls a provided callbackFn function once for each element in an array in descending-index order, until callbackFn returns a truthy value. findLastIndex() then returns the index of that element and stops iterating through the array. If callbackFn never returns a truthy value, findLastIndex() returns -1.

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

findLastIndex() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The findLastIndex() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Find the index of the last prime number in an array

\n
\n

The following example returns the index of the last element in the array that is a prime number, or -1 if there is no prime number.

\n

js

\n
function isPrime(element) {\n  if (element % 2 === 0 || element < 2) {\n    return false;\n  }\n  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {\n    if (element % factor === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\nconsole.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found\nconsole.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5\n
\n
\n

Using findLastIndex() on sparse arrays

\n
\n

You can search for undefined in a sparse array and get the index of an empty slot.

\n

js

\n
console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1\n
\n
\n

Calling findLastIndex() on non-array objects

\n
\n

The findLastIndex() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 2,\n  1: 7.3,\n  2: 4,\n  3: 3, // ignored by findLastIndex() since length is 3\n};\nconsole.log(\n  Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)),\n); // 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.findlastindex
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findLastIndex9797104No8315.497971046815.418.01.1618.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex\n

\n
\n", + "global_objects/array/keys": "

Array.prototype.keys()

The keys() method of Array instances returns a new array iterator object that contains the keys for each index in the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
keys()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n
\n

When used on sparse arrays, the keys() method iterates empty slots as if they have the value undefined.

The keys() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Using keys() on sparse arrays

\n
\n

Unlike Object.keys(), which only includes keys that actually exist in the array, the keys() iterator doesn't ignore holes representing missing properties.

\n

js

\n
const arr = [\"a\", , \"c\"];\nconst sparseKeys = Object.keys(arr);\nconst denseKeys = [...arr.keys()];\nconsole.log(sparseKeys); // ['0', '2']\nconsole.log(denseKeys); // [0, 1, 2]\n
\n
\n

Calling keys() on non-array objects

\n
\n

The keys() method reads the length property of this and then yields all integer indices between 0 and length - 1. No index access actually happens.

\n

js

\n
const arrayLike = {\n  length: 3,\n};\nfor (const entry of Array.prototype.keys.call(arrayLike)) {\n  console.log(entry);\n}\n// 0\n// 1\n// 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.keys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keys381228No2583838282583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys\n

\n
\n", + "global_objects/array/tolocalestring": "

Array.prototype.toLocaleString()

The toLocaleString() method of Array instances returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma \",\").

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n
\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object with configuration properties. For numbers, see Number.prototype.toLocaleString(); for dates, see Date.prototype.toLocaleString().

Return value

\n

A string representing the elements of the array.

Description

\n
\n

The Array.prototype.toLocaleString method traverses its content, calling the toLocaleString method of every element with the locales and options parameters provided, and concatenates them with an implementation-defined separator (such as a comma \",\"). Note that the method itself does not consume the two parameters — it only passes them to the toLocaleString() of each element. The choice of the separator string depends on the host's current locale, not the locales parameter.

If an element is undefined, null, it is converted to an empty string instead of the string \"null\" or \"undefined\".

When used on sparse arrays, the toLocaleString() method iterates empty slots as if they have the value undefined.

The toLocaleString() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Using locales and options

\n
\n

The elements of the array are converted to strings using their toLocaleString methods.

Always display the currency for the strings and numbers in the prices array:

\n

js

\n
const prices = [\"¥7\", 500, 8123, 12];\nprices.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" });\n\n// \"¥7,¥500,¥8,123,¥12\"\n
\n

For more examples, see also the Intl.NumberFormat and Intl.DateTimeFormat pages.

\n

Using toLocaleString() on sparse arrays

\n
\n

toLocaleString() treats empty slots the same as undefined and produces an extra separator:

\n

js

\n
console.log([1, , 3].toLocaleString()); // '1,,3'\n
\n
\n

Calling toLocaleString() on non-array objects

\n
\n

The toLocaleString() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: 1,\n  1: 2,\n  2: 3,\n  3: 4, // ignored by toLocaleString() since length is 3\n};\nconsole.log(Array.prototype.toLocaleString.call(arrayLike));\n// 1,2,3\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.tolocalestring
ECMAScript Internationalization API Specification
# sup-array.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString11215.541≤3718410.111.01.00.10.0
locales_parameter247952No1574.425561472.01.8
1.0–1.8Only the locale data for en-US is available.
\n
13.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options_parameter247952No1574.425561472.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString\n

\n
\n", + "global_objects/array/values": "

Array.prototype.values()

The values() method of Array instances returns a new array iterator object that iterates the value of each item in the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
values()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n
\n

Array.prototype.values() is the default implementation of Array.prototype[@@iterator]().

\n

js

\n
Array.prototype.values === Array.prototype[Symbol.iterator]; // true\n
\n

When used on sparse arrays, the values() method iterates empty slots as if they have the value undefined.

The values() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Iteration using for...of loop

\n
\n

Because values() returns an iterable iterator, you can use a for...of loop to iterate it.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst iterator = arr.values();\n\nfor (const letter of iterator) {\n  console.log(letter);\n} // \"a\" \"b\" \"c\" \"d\" \"e\"\n
\n
\n

Iteration using next()

\n
\n

Because the return value is also an iterator, you can directly call its next() method.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst iterator = arr.values();\niterator.next(); // { value: \"a\", done: false }\niterator.next(); // { value: \"b\", done: false }\niterator.next(); // { value: \"c\", done: false }\niterator.next(); // { value: \"d\", done: false }\niterator.next(); // { value: \"e\", done: false }\niterator.next(); // { value: undefined, done: true }\nconsole.log(iterator.next().value); // undefined\n
\n
\n

Reusing the iterable

\n
\n

Warning: The array iterator object should be a one-time use object. Do not reuse it.

The iterable returned from values() is not reusable. When next().done = true or currentIndex > length, the for...of loop ends, and further iterating it has no effect.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst values = arr.values();\nfor (const letter of values) {\n  console.log(letter);\n}\n// \"a\" \"b\" \"c\" \"d\" \"e\"\nfor (const letter of values) {\n  console.log(letter);\n}\n// undefined\n
\n

If you use a break statement to end the iteration early, the iterator can resume from the current position when continuing to iterate it.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst values = arr.values();\nfor (const letter of values) {\n  console.log(letter);\n  if (letter === \"b\") {\n    break;\n  }\n}\n// \"a\" \"b\"\n\nfor (const letter of values) {\n  console.log(letter);\n}\n// \"c\" \"d\" \"e\"\n
\n
\n

Mutations during iteration

\n
\n

There are no values stored in the array iterator object returned from values(); instead, it stores the address of the array used in its creation, and reads the currently visited index on each iteration. Therefore, its iteration output depends on the value stored in that index at the time of stepping. If the values in the array changed, the array iterator object's values change too.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst iterator = arr.values();\nconsole.log(iterator); // Array Iterator { }\nconsole.log(iterator.next().value); // \"a\"\narr[1] = \"n\";\nconsole.log(iterator.next().value); // \"n\"\n
\n
\n

Iterating sparse arrays

\n
\n

values() will visit empty slots as if they are undefined.

\n

js

\n
for (const element of [, \"a\"].values()) {\n  console.log(element);\n}\n// undefined\n// 'a'\n
\n
\n

Calling values() on non-array objects

\n
\n

The values() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

\n

js

\n
const arrayLike = {\n  length: 3,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\",\n  3: \"d\", // ignored by values() since length is 3\n};\nfor (const entry of Array.prototype.values.call(arrayLike)) {\n  console.log(entry);\n}\n// a\n// b\n// c\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.values
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
values661460No5396666604799.01.010.9.00.12.0–4.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values\n

\n
\n", + "global_objects/array/@@species": "

Array[@@species]

\n

The Array[@@species] static accessor property returns the constructor used to construct return values from array methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible. Modern array methods, such as toReversed(), do not use @@species and always return a new Array base class instance.

\n
\n

Syntax

\n
\n

js

\n
Array[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct return values from array methods that create new arrays.

Description

\n
\n

The @@species accessor property returns the default constructor for Array objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass Array {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubArray extends Array {}\nSubArray[Symbol.species] === SubArray; // true\n
\n

When calling array methods that do not mutate the existing array but return a new array instance (for example, filter() and map()), the array's constructor[@@species] will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays.

\n

js

\n
class NotAnArray {\n  constructor(length) {\n    this.length = length;\n  }\n}\n\nconst arr = [0, 1, 2];\narr.constructor = { [Symbol.species]: NotAnArray };\narr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 }\narr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 }\narr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 }\n
\n
\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the Array constructor for Array.

\n

js

\n
Array[Symbol.species]; // [Function: Array]\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom Array subclass, such as MyArray, the MyArray species is the MyArray constructor. However, you might want to overwrite this, in order to return parent Array objects in your derived class methods:

\n

js

\n
class MyArray extends Array {\n  // Overwrite MyArray species to the parent Array constructor\n  static get [Symbol.species]() {\n    return Array;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-array-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species517948No381051514841105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@species\n

\n
\n", + "global_objects/array/toreversed": "

Array.prototype.toReversed()

The toReversed() method of Array instances is the copying counterpart of the reverse() method. It returns a new array with the elements in reversed order.

\n

Syntax

\n
\n

js

\n
toReversed()\n
\n

Parameters

\n

None.

Return value

\n

A new array containing the elements in reversed order.

Description

\n
\n

The toReversed() method transposes the elements of the calling array object in reverse order and returns a new array.

When used on sparse arrays, the toReversed() method iterates empty slots as if they have the value undefined.

The toReversed() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Reversing the elements in an array

\n
\n

The following example creates an array items, containing three elements, then creates a new array that's the reverse of items. The items array remains unchanged.

\n

js

\n
const items = [1, 2, 3];\nconsole.log(items); // [1, 2, 3]\n\nconst reversedItems = items.toReversed();\nconsole.log(reversedItems); // [3, 2, 1]\nconsole.log(items); // [1, 2, 3]\n
\n
\n

Using toReversed() on sparse arrays

\n
\n

The return value of toReversed() is never sparse. Empty slots become undefined in the returned array.

\n

js

\n
console.log([1, , 3].toReversed()); // [3, undefined, 1]\nconsole.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]\n
\n
\n

Calling toReversed() on non-array objects

\n
\n

The toReversed() method reads the length property of this. It then visits each property having an integer key between length - 1 and 0 in descending order, adding the value of the current property to the end of the array to be returned.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n};\nconsole.log(Array.prototype.toReversed.call(arrayLike));\n// [4, undefined, undefined]\n// The '0' and '1' indices are not present so they become undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.toreversed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toReversed110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed\n

\n
\n", + "global_objects/array/tosorted": "

Array.prototype.toSorted()

The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

\n

Syntax

\n
\n

js

\n
toSorted()\ntoSorted(compareFn)\n
\n

Parameters

\n
\ncompareFn Optional\n

Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

a

The first element for comparison.

b

The second element for comparison.

Return value

\n

A new array with the elements sorted in ascending order.

Description

\n
\n

See sort() for more information on the compareFn parameter.

When used on sparse arrays, the toSorted() method iterates empty slots as if they have the value undefined.

The toSorted() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Sorting an array

\n
\n
\n

js

\n
const months = [\"Mar\", \"Jan\", \"Feb\", \"Dec\"];\nconst sortedMonths = months.toSorted();\nconsole.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']\nconsole.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']\n\nconst values = [1, 10, 21, 2];\nconst sortedValues = values.toSorted((a, b) => a - b);\nconsole.log(sortedValues); // [1, 2, 10, 21]\nconsole.log(values); // [1, 10, 21, 2]\n
\n

For more usage examples, see sort().

\n

Using toSorted() on sparse arrays

\n
\n

Empty slots are sorted as if they have the value undefined. They are always sorted to the end of the array and compareFn is not called for them.

\n

js

\n
console.log([\"a\", \"c\", , \"b\"].toSorted()); // ['a', 'b', 'c', undefined]\nconsole.log([, undefined, \"a\", \"b\"].toSorted()); // [\"a\", \"b\", undefined, undefined]\n
\n
\n

Calling toSorted() on non-array objects

\n
\n

The toSorted() method reads the length property of this. It then collects all existing integer-keyed properties in the range of 0 to length - 1, sorts them, and writes them into a new array.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  0: 5,\n  2: 4,\n  3: 3, // ignored by toSorted() since length is 3\n};\nconsole.log(Array.prototype.toSorted.call(arrayLike));\n// [4, 5, undefined]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.tosorted
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toSorted110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted\n

\n
\n", + "global_objects/array/tospliced": "

Array.prototype.toSpliced()

The toSpliced() method of Array instances is the copying version of the splice() method. It returns a new array with some elements removed and/or replaced at a given index.

\n

Syntax

\n
\n

js

\n
toSpliced(start)\ntoSpliced(start, deleteCount)\ntoSpliced(start, deleteCount, item1)\ntoSpliced(start, deleteCount, item1, item2)\ntoSpliced(start, deleteCount, item1, item2, /* …, */ itemN)\n
\n

Parameters

\n
start

Zero-based index at which to start changing the array, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start < -array.length or start is omitted, 0 is used.
  • If start >= array.length, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided.
\ndeleteCount Optional\n

An integer indicating the number of elements in the array to remove from start.

If deleteCount is omitted, or if its value is greater than or equal to the number of elements after the position specified by start, then all the elements from start to the end of the array will be deleted. However, if you wish to pass any itemN parameter, you should pass Infinity as deleteCount to delete all elements after start, because an explicit undefined gets converted to 0.

If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

\nitem1, …, itemN Optional\n

The elements to add to the array, beginning from start.

If you do not specify any elements, toSpliced() will only remove elements from the array.

Return value

\n

A new array that consists of all elements before start, item1, item2, …, itemN, and all elements after start + deleteCount.

Description

\n
\n

The toSpliced() method, like splice(), does multiple things at once: it removes the given number of elements from the array, starting at a given index, and then inserts the given elements at the same index. However, it returns a new array instead of modifying the original array. The deleted elements therefore are not returned from this method.

The toSpliced() method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined in the new array.

The toSpliced() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Deleting, adding, and replacing elements

\n
\n

You can use toSpliced() to delete, add, and replace elements in an array and create a new array more efficiently than using slice() and concat().

\n

js

\n
const months = [\"Jan\", \"Mar\", \"Apr\", \"May\"];\n\n// Inserting an element at index 1\nconst months2 = months.toSpliced(1, 0, \"Feb\");\nconsole.log(months2); // [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\"]\n\n// Deleting two elements starting from index 2\nconst months3 = months2.toSpliced(2, 2);\nconsole.log(months3); // [\"Jan\", \"Feb\", \"May\"]\n\n// Replacing one element at index 1 with two new elements\nconst months4 = months3.toSpliced(1, 1, \"Feb\", \"Mar\");\nconsole.log(months4); // [\"Jan\", \"Feb\", \"Mar\", \"May\"]\n\n// Original array is not modified\nconsole.log(months); // [\"Jan\", \"Mar\", \"Apr\", \"May\"]\n
\n
\n

Using toSpliced() on sparse arrays

\n
\n

The toSpliced() method always creates a dense array.

\n

js

\n
const arr = [1, , 3, 4, , 6];\nconsole.log(arr.toSpliced(1, 2)); // [1, 4, undefined, 6]\n
\n
\n

Calling toSpliced() on non-array objects

\n
\n

The toSpliced() method reads the length property of this. It then reads the integer-keyed properties needed and writes them into the new array.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  0: 5,\n  2: 4,\n};\nconsole.log(Array.prototype.toSpliced.call(arrayLike, 0, 1, 2, 3));\n// [2, 3, undefined, 4]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.tospliced
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toSpliced110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced\n

\n
\n", + "global_objects/array/with": "

Array.prototype.with()

The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

\n

Syntax

\n
\n

js

\n
arrayInstance.with(index, value)\n
\n

Parameters

\n
index

Zero-based index at which to change the array, converted to an integer.

  • Negative index counts back from the end of the array — if index < 0, index + array.length is used.
  • If the index after normalization is out of bounds, a RangeError is thrown.
value

Any value to be assigned to the given index.

Return value

\n

A new array with the element at index replaced with value.

Exceptions

\n
RangeError

Thrown if index >= array.length or index < -array.length.

Description

\n
\n

The with() method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

By combining with() with at(), you can both write and read (respectively) an array using negative indices.

The with() method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined in the new array.

The with() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Creating a new array with a single element changed

\n
\n

js

\n
const arr = [1, 2, 3, 4, 5];\nconsole.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]\nconsole.log(arr); // [1, 2, 3, 4, 5]\n
\n

Chaining array methods

\n
\n

With the with() method, you can update a single element in an array and then apply other array methods.

\n

js

\n
const arr = [1, 2, 3, 4, 5];\nconsole.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]\n
\n
\n

Using with() on sparse arrays

\n
\n

The with() method always creates a dense array.

\n

js

\n
const arr = [1, , 3, 4, , 6];\nconsole.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]\n
\n
\n

Calling with() on non-array objects

\n
\n

The with() method creates and returns a new array. It reads the length property of this and then accesses each property whose key is a nonnegative integer less than length. As each property of this is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value at index is set to value.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  0: 5,\n  2: 4,\n  3: 3, // ignored by with() since length is 3\n};\nconsole.log(Array.prototype.with.call(arrayLike, 0, 1));\n// [ 1, undefined, 4 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.with
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
with110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with\n

\n
\n", + "global_objects/array/pop": "

Array.prototype.pop()

The pop() method of Array instances removes the last element from an array and returns that element. This method changes the length of the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
pop()\n
\n

Parameters

\n

None.

Return value

\n

The removed element from the array; undefined if the array is empty.

Description

\n
\n

The pop() method removes the last element from an array and returns that value to the caller. If you call pop() on an empty array, it returns undefined.

Array.prototype.shift() has similar behavior to pop(), but applied to the first element in an array.

The pop() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with the last element removed, you can use arr.slice(0, -1) instead.

The pop() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Removing the last element of an array

\n
\n

The following code creates the myFish array containing four elements, then removes its last element.

\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"sturgeon\"];\n\nconst popped = myFish.pop();\n\nconsole.log(myFish); // ['angel', 'clown', 'mandarin' ]\n\nconsole.log(popped); // 'sturgeon'\n
\n
\n

Calling pop() on non-array objects

\n
\n

The pop() method reads the length property of this. If the normalized length is 0, length is set to 0 again (whereas it may be negative or undefined before). Otherwise, the property at length - 1 is returned and deleted.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n};\nconsole.log(Array.prototype.pop.call(arrayLike));\n// 4\nconsole.log(arrayLike);\n// { length: 2, unrelated: 'foo' }\n\nconst plainObj = {};\n// There's no length property, so the length is 0\nArray.prototype.pop.call(plainObj);\nconsole.log(plainObj);\n// { length: 0 }\n
\n
\n

Using an object in an array-like fashion

\n
\n

push and pop are intentionally generic, and we can use that to our advantage — as the following example shows.

Note that in this example, we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push and Array.prototype.pop to trick those methods into thinking we're dealing with an array.

\n

js

\n
const collection = {\n  length: 0,\n  addElements(...elements) {\n    // obj.length will be incremented automatically\n    // every time an element is added.\n\n    // Returning what push returns; that is\n    // the new value of length property.\n    return [].push.call(this, ...elements);\n  },\n  removeElement() {\n    // obj.length will be decremented automatically\n    // every time an element is removed.\n\n    // Returning what pop returns; that is\n    // the removed element.\n    return [].pop.call(this);\n  },\n};\n\ncollection.addElements(10, 20, 30);\nconsole.log(collection.length); // 3\ncollection.removeElement();\nconsole.log(collection.length); // 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.pop
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
pop11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop\n

\n
\n", + "global_objects/array/shift": "

Array.prototype.shift()

The shift() method of Array instances removes the first element from an array and returns that removed element. This method changes the length of the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
shift()\n
\n

Parameters

\n

None.

Return value

\n

The removed element from the array; undefined if the array is empty.

Description

\n
\n

The shift() method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.

The pop() method has similar behavior to shift(), but applied to the last element in an array.

The shift() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with the first element removed, you can use arr.slice(1) instead.

The shift() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Removing an element from an array

\n
\n

The following code displays the myFish array before and after removing its first element. It also displays the removed element:

\n

js

\n
const myFish = [\"angel\", \"clown\", \"mandarin\", \"surgeon\"];\n\nconsole.log(\"myFish before:\", myFish);\n// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']\n\nconst shifted = myFish.shift();\n\nconsole.log(\"myFish after:\", myFish);\n// myFish after: ['clown', 'mandarin', 'surgeon']\n\nconsole.log(\"Removed this element:\", shifted);\n// Removed this element: angel\n
\n
\n

Using shift() method in while loop

\n
\n

The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array, until it is empty:

\n

js

\n
const names = [\"Andrew\", \"Tyrone\", \"Paul\", \"Maria\", \"Gayatri\"];\n\nwhile (typeof (i = names.shift()) !== \"undefined\") {\n  console.log(i);\n}\n// Andrew, Tyrone, Paul, Maria, Gayatri\n
\n
\n

Calling shift() on non-array objects

\n
\n

The shift() method reads the length property of this. If the normalized length is 0, length is set to 0 again (whereas it may be negative or undefined before). Otherwise, the property at 0 is returned, and the rest of the properties are shifted left by one. The length property is decremented by one.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n};\nconsole.log(Array.prototype.shift.call(arrayLike));\n// undefined, because it is an empty slot\nconsole.log(arrayLike);\n// { '1': 4, length: 2, unrelated: 'foo' }\n\nconst plainObj = {};\n// There's no length property, so the length is 0\nArray.prototype.shift.call(plainObj);\nconsole.log(plainObj);\n// { length: 0 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.shift
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
shift11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift\n

\n
\n", + "global_objects/array/unshift": "

Array.prototype.unshift()

The unshift() method of Array instances adds the specified elements to the beginning of an array and returns the new length of the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
unshift()\nunshift(element1)\nunshift(element1, element2)\nunshift(element1, element2, /* …, */ elementN)\n
\n

Parameters

\n
\nelement1, …, elementN\n

The elements to add to the front of the arr.

Return value

\n

The new length property of the object upon which the method was called.

Description

\n
\n

The unshift() method inserts the given values to the beginning of an array-like object.

Array.prototype.push() has similar behavior to unshift(), but applied to the end of an array.

Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling unshift() with n arguments once, or calling it n times with 1 argument (with a loop, for example), don't yield the same results.

See example:

\n

js

\n
let arr = [4, 5, 6];\n\narr.unshift(1, 2, 3);\nconsole.log(arr);\n// [1, 2, 3, 4, 5, 6]\n\narr = [4, 5, 6]; // resetting the array\n\narr.unshift(1);\narr.unshift(2);\narr.unshift(3);\n\nconsole.log(arr);\n// [3, 2, 1, 4, 5, 6]\n
\n

The unshift() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

\n

Examples

\n

Using unshift()

\n
\n

js

\n
const arr = [1, 2];\n\narr.unshift(0); // result of the call is 3, which is the new array length\n// arr is [0, 1, 2]\n\narr.unshift(-2, -1); // the new array length is 5\n// arr is [-2, -1, 0, 1, 2]\n\narr.unshift([-4, -3]); // the new array length is 6\n// arr is [[-4, -3], -2, -1, 0, 1, 2]\n\narr.unshift([-7, -6], [-5]); // the new array length is 8\n// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]\n
\n

Calling unshift() on non-array objects

\n
\n

The unshift() method reads the length property of this. It shifts all indices in the range 0 to length - 1 right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at 0 with the arguments passed to unshift(). Finally, it sets the length to the previous length plus the number of prepended elements.

\n

js

\n
const arrayLike = {\n  length: 3,\n  unrelated: \"foo\",\n  2: 4,\n};\nArray.prototype.unshift.call(arrayLike, 1, 2);\nconsole.log(arrayLike);\n// { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' }\n\nconst plainObj = {};\n// There's no length property, so the length is 0\nArray.prototype.unshift.call(plainObj, 1, 2);\nconsole.log(plainObj);\n// { '0': 1, '1': 2, length: 2 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.unshift
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unshift11215.5414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\n

\n
\n", + "global_objects/array/array": "

Array() constructor

The Array() constructor creates Array objects.

\n

Syntax

\n
\n
\n

js

\n
new Array()\nnew Array(element1)\nnew Array(element1, element2)\nnew Array(element1, element2, /* …, */ elementN)\nnew Array(arrayLength)\n\nArray()\nArray(element1)\nArray(element1, element2)\nArray(element1, element2, /* …, */ elementN)\nArray(arrayLength)\n
\n

Note: Array() can be called with or without new. Both create a new Array instance.

\n

Parameters

\n
\nelement1, …, elementN\n

A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the square bracket syntax.

arrayLength

If the only argument passed to the Array constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values — see sparse arrays).

Exceptions

\n
RangeError

Thrown if there's only one argument (arrayLength) that is a number, but its value is not an integer or not between 0 and 232 - 1 (inclusive).

Examples

\n

Array literal notation

\n
\n

Arrays can be created using the literal notation:

\n

js

\n
const fruits = [\"Apple\", \"Banana\"];\n\nconsole.log(fruits.length); // 2\nconsole.log(fruits[0]); // \"Apple\"\n
\n
\n

Array constructor with a single parameter

\n
\n

Arrays can be created using a constructor with a single number parameter. An array is created with its length property set to that number, and the array elements are empty slots.

\n

js

\n
const arrayEmpty = new Array(2);\n\nconsole.log(arrayEmpty.length); // 2\nconsole.log(arrayEmpty[0]); // undefined; actually, it is an empty slot\nconsole.log(0 in arrayEmpty); // false\nconsole.log(1 in arrayEmpty); // false\n
\n
\n

js

\n
const arrayOfOne = new Array(\"2\"); // Not the number 2 but the string \"2\"\n\nconsole.log(arrayOfOne.length); // 1\nconsole.log(arrayOfOne[0]); // \"2\"\n
\n
\n

Array constructor with multiple parameters

\n
\n

If more than one argument is passed to the constructor, a new Array with the given elements is created.

\n

js

\n
const fruits = new Array(\"Apple\", \"Banana\");\n\nconsole.log(fruits.length); // 2\nconsole.log(fruits[0]); // \"Apple\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Array1121441≤3718410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array\n

\n
\n", + "global_objects/array/from": "

Array.from()

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Array.from(arrayLike)\nArray.from(arrayLike, mapFn)\nArray.from(arrayLike, mapFn, thisArg)\n
\n

Parameters

\n
arrayLike

An iterable or array-like object to convert to an array.

\nmapFn Optional\n

A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn's return value is added to the array instead. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

\nthisArg Optional\n

Value to use as this when executing mapFn.

Return value

\n

A new Array instance.

Description

\n
\n

Array.from() lets you create Arrays from:

To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use Object.keys(), Object.values(), or Object.entries(). To convert an async iterable to an array, use Array.fromAsync().

Array.from() never creates a sparse array. If the arrayLike object is missing some index properties, they become undefined in the new array.

Array.from() has an optional parameter mapFn, which allows you to execute a function on each element of the array being created, similar to map(). More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array, and mapFn only receives two arguments (element, index) without the whole array, because the array is still under construction.

Note: This behavior is more important for typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. Array.from() is implemented to have the same signature as TypedArray.from().

The Array.from() method is a generic factory method. For example, if a subclass of Array inherits the from() method, the inherited from() method will return new instances of the subclass instead of Array instances. In fact, the this value can be any constructor function that accepts a single argument representing the length of the new array. When an iterable is passed as arrayLike, the constructor is called with no arguments; when an array-like object is passed, the constructor is called with the normalized length of the array-like object. The final length will be set again when iteration finishes. If the this value is not a constructor function, the plain Array constructor is used instead.

\n

Examples

\n

Array from a String

\n
\n

js

\n
Array.from(\"foo\");\n// [ \"f\", \"o\", \"o\" ]\n
\n

Array from a Set

\n
\n

js

\n
const set = new Set([\"foo\", \"bar\", \"baz\", \"foo\"]);\nArray.from(set);\n// [ \"foo\", \"bar\", \"baz\" ]\n
\n

Array from a Map

\n
\n

js

\n
const map = new Map([\n  [1, 2],\n  [2, 4],\n  [4, 8],\n]);\nArray.from(map);\n// [[1, 2], [2, 4], [4, 8]]\n\nconst mapper = new Map([\n  [\"1\", \"a\"],\n  [\"2\", \"b\"],\n]);\nArray.from(mapper.values());\n// ['a', 'b'];\n\nArray.from(mapper.keys());\n// ['1', '2'];\n
\n

Array from a NodeList

\n
\n

js

\n
// Create an array based on a property of DOM Elements\nconst images = document.querySelectorAll(\"img\");\nconst sources = Array.from(images, (image) => image.src);\nconst insecureSources = sources.filter((link) => link.startsWith(\"http://\"));\n
\n

Array from an Array-like object (arguments)

\n
\n

js

\n
function f() {\n  return Array.from(arguments);\n}\n\nf(1, 2, 3);\n\n// [ 1, 2, 3 ]\n
\n

Using arrow functions and Array.from()

\n
\n

js

\n
// Using an arrow function as the map function to\n// manipulate the elements\nArray.from([1, 2, 3], (x) => x + x);\n// [2, 4, 6]\n\n// Generate a sequence of numbers\n// Since the array is initialized with `undefined` on each position,\n// the value of `v` below will be `undefined`\nArray.from({ length: 5 }, (v, i) => i);\n// [0, 1, 2, 3, 4]\n
\n

Sequence generator (range)

\n
\n

js

\n
// Sequence generator function (commonly referred to as \"range\", e.g. Clojure, PHP, etc.)\nconst range = (start, stop, step) =>\n  Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);\n\n// Generate numbers range 0..4\nrange(0, 4, 1);\n// [0, 1, 2, 3, 4]\n\n// Generate numbers range 1..10 with step of 2\nrange(1, 10, 2);\n// [1, 3, 5, 7, 9]\n\n// Generate the alphabet using Array.from making use of it being ordered as a sequence\nrange(\"A\".charCodeAt(0), \"Z\".charCodeAt(0), 1).map((x) =>\n  String.fromCharCode(x),\n);\n// [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n
\n

Calling from() on non-array constructors

\n
\n

The from() method can be called on any constructor function that accepts a single argument representing the length of the new array.

\n

js

\n
function NotArray(len) {\n  console.log(\"NotArray called with length\", len);\n}\n\n// Iterable\nconsole.log(Array.from.call(NotArray, new Set([\"foo\", \"bar\", \"baz\"])));\n// NotArray called with length undefined\n// NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 }\n\n// Array-like\nconsole.log(Array.from.call(NotArray, { length: 1, 0: \"foo\" }));\n// NotArray called with length 1\n// NotArray { '0': 'foo', length: 1 }\n
\n

When the this value is not a constructor, a plain Array object is returned.

\n

js

\n
console.log(Array.from.call({}, { length: 1, 0: \"foo\" })); // [ 'foo' ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.from
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
from451232No3294545323295.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\n

\n
\n", + "global_objects/array/fromasync": "

Array.fromAsync()

The Array.fromAsync() static method creates a new, shallow-copied Array instance from an async iterable, iterable, or array-like object.

\n

Syntax

\n
\n

js

\n
Array.fromAsync(arrayLike)\nArray.fromAsync(arrayLike, mapFn)\nArray.fromAsync(arrayLike, mapFn, thisArg)\n
\n

Parameters

\n
arrayLike

An async iterable, iterable, or array-like object to convert to an array.

\nmapFn Optional\n

A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn's return value is added to the array instead (after being awaited). The function is called with the following arguments:

element

The current element being processed in the array. Because all elements are first awaited, this value will never be a thenable.

index

The index of the current element being processed in the array.

\nthisArg Optional\n

Value to use as this when executing mapFn.

Return value

\n

A new Promise whose fulfillment value is a new Array instance.

Description

\n
\n

Array.fromAsync() lets you create arrays from:

Array.fromAsync() iterates the async iterable in a fashion very similar to for await...of. Array.fromAsync() is almost equivalent to Array.from() in terms of behavior, except the following:

Array.fromAsync() and Promise.all() can both turn an iterable of promises into a promise of an array. However, there are two key differences:

\n

Examples

\n

Array from an async iterable

\n
\n

js

\n
const asyncIterable = (async function* () {\n  for (let i = 0; i < 5; i++) {\n    await new Promise((resolve) => setTimeout(resolve, 10 * i));\n    yield i;\n  }\n})();\n\nArray.fromAsync(asyncIterable).then((array) => console.log(array));\n// [0, 1, 2, 3, 4]\n
\n

Array from a sync iterable

\n
\n

js

\n
Array.fromAsync(\n  new Map([\n    [1, 2],\n    [3, 4],\n  ]),\n).then((array) => console.log(array));\n// [[1, 2], [3, 4]]\n
\n

Array from a sync iterable that yields promises

\n
\n

js

\n
Array.fromAsync(\n  new Set([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]),\n).then((array) => console.log(array));\n// [1, 2, 3]\n
\n

Array from an array-like object of promises

\n
\n

js

\n
Array.fromAsync({\n  length: 3,\n  0: Promise.resolve(1),\n  1: Promise.resolve(2),\n  2: Promise.resolve(3),\n}).then((array) => console.log(array));\n// [1, 2, 3]\n
\n

Using mapFn

\n
\n

Both the input and output of mapFn are awaited internally by Array.fromAsync().

\n

js

\n
function delayedValue(v) {\n  return new Promise((resolve) => setTimeout(() => resolve(v), 100));\n}\n\nArray.fromAsync(\n  [delayedValue(1), delayedValue(2), delayedValue(3)],\n  (element) => delayedValue(element * 2),\n).then((array) => console.log(array));\n// [2, 4, 6]\n
\n
\n

Comparison with Promise.all()

\n
\n

Array.fromAsync() awaits each value yielded from the object sequentially. Promise.all() awaits all values concurrently.

\n

js

\n
function* makeAsyncIterable() {\n  for (let i = 0; i < 5; i++) {\n    yield new Promise((resolve) => setTimeout(resolve, 100));\n  }\n}\n\n(async () => {\n  console.time(\"Array.fromAsync() time\");\n  await Array.fromAsync(makeAsyncIterable());\n  console.timeEnd(\"Array.fromAsync() time\");\n  // Array.fromAsync() time: 503.610ms\n\n  console.time(\"Promise.all() time\");\n  await Promise.all(makeAsyncIterable());\n  console.timeEnd(\"Promise.all() time\");\n  // Promise.all() time: 101.728ms\n})();\n
\n
\n

No error handling for sync iterables

\n
\n

Similar to for await...of, if the object being iterated is a sync iterable, and an error is thrown while iterating, the return() method of the underlying iterator will not be called, so the iterator is not closed.

\n

js

\n
function* generatorWithRejectedPromises() {\n  try {\n    yield 0;\n    yield Promise.reject(3);\n  } finally {\n    console.log(\"called finally\");\n  }\n}\n\n(async () => {\n  try {\n    await Array.fromAsync(generatorWithRejectedPromises());\n  } catch (e) {\n    console.log(\"caught\", e);\n  }\n})();\n// caught 3\n// No \"called finally\" message\n
\n

If you need to close the iterator, you need to use a for...of loop instead, and await each value yourself.

\n

js

\n
(async () => {\n  const arr = [];\n  try {\n    for (const val of generatorWithRejectedPromises()) {\n      arr.push(await val);\n    }\n  } catch (e) {\n    console.log(\"caught\", e);\n  }\n})();\n// called finally\n// caught 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ES Array.fromAsync (2022)
# sec-array.fromAsync
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fromAsyncNoNo115NoNo16.4NoNo115No16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync\n

\n
\n", + "global_objects/array/isarray": "

Array.isArray()

The Array.isArray() static method determines whether the passed value is an Array.

\n

Try it

\n

Syntax

\n
\n

js

\n
Array.isArray(value)\n
\n

Parameters

\n
value

The value to be checked.

Return value

\n

true if value is an Array; otherwise, false. false is always returned if value is a TypedArray instance.

Description

\n
\n

Array.isArray() checks if the passed value is an Array. It does not check the value's prototype chain, nor does it rely on the Array constructor it is attached to. It returns true for any value that was created using the array literal syntax or the Array constructor. This makes it safe to use with cross-realm objects, where the identity of the Array constructor is different and would therefore cause instanceof Array to fail.

See the article \"Determining with absolute accuracy whether or not a JavaScript object is an array\" for more details.

Array.isArray() also rejects objects with Array.prototype in its prototype chain but aren't actual arrays, which instanceof Array would accept.

\n

Examples

\n

Using Array.isArray()

\n
\n

js

\n
// all following calls return true\nArray.isArray([]);\nArray.isArray([1]);\nArray.isArray(new Array());\nArray.isArray(new Array(\"a\", \"b\", \"c\", \"d\"));\nArray.isArray(new Array(3));\n// Little known fact: Array.prototype itself is an array:\nArray.isArray(Array.prototype);\n\n// all following calls return false\nArray.isArray();\nArray.isArray({});\nArray.isArray(null);\nArray.isArray(undefined);\nArray.isArray(17);\nArray.isArray(\"Array\");\nArray.isArray(true);\nArray.isArray(false);\nArray.isArray(new Uint8Array(32));\n// This is not an array, because it was not created using the\n// array literal syntax or the Array constructor\nArray.isArray({ __proto__: Array.prototype });\n
\n

instanceof vs. Array.isArray()

\n
\n

When checking for Array instance, Array.isArray() is preferred over instanceof because it works across realms.

\n

js

\n
const iframe = document.createElement(\"iframe\");\ndocument.body.appendChild(iframe);\nconst xArray = window.frames[window.frames.length - 1].Array;\nconst arr = new xArray(1, 2, 3); // [1, 2, 3]\n\n// Correctly checking for Array\nArray.isArray(arr); // true\n// The prototype of arr is xArray.prototype, which is a\n// different object from Array.prototype\narr instanceof Array; // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.isarray
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isArray4124910.554.41841451.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\n

\n
\n", + "global_objects/array/of": "

Array.of()

The Array.of() static method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

\n

Try it

\n

Syntax

\n
\n

js

\n
Array.of()\nArray.of(element1)\nArray.of(element1, element2)\nArray.of(element1, element2, /* …, */ elementN)\n
\n

Parameters

\n
\nelement1, …, elementN\n

Elements used to create the array.

Return value

\n

A new Array instance.

Description

\n
\n

The difference between Array.of() and the Array() constructor is in the handling of single arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7. (That implies an array of 7 empty slots, not slots with actual undefined values.)

\n

js

\n
Array.of(7); // [7]\nArray(7); // array of 7 empty slots\n\nArray.of(1, 2, 3); // [1, 2, 3]\nArray(1, 2, 3); // [1, 2, 3]\n
\n

The Array.of() method is a generic factory method. For example, if a subclass of Array inherits the of() method, the inherited of() method will return new instances of the subclass instead of Array instances. In fact, the this value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to of(). The final length will be set again when all elements are assigned. If the this value is not a constructor function, the plain Array constructor is used instead.

\n

Examples

\n

Using Array.of()

\n
\n

js

\n
Array.of(1); // [1]\nArray.of(1, 2, 3); // [1, 2, 3]\nArray.of(undefined); // [undefined]\n
\n

Calling of() on non-array constructors

\n
\n

The of() method can be called on any constructor function that accepts a single argument representing the length of the new array.

\n

js

\n
function NotArray(len) {\n  console.log(\"NotArray called with length\", len);\n}\n\nconsole.log(Array.of.call(NotArray, 1, 2, 3));\n// NotArray called with length 3\n// NotArray { '0': 1, '1': 2, '2': 3, length: 3 }\n\nconsole.log(Array.of.call(Object)); // [Number: 0] { length: 0 }\n
\n

When the this value is not a constructor, a plain Array object is returned.

\n

js

\n
console.log(Array.of.call({}, 1)); // [ 1 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.of
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
of451225No2693939252694.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of\n

\n
\n", + "global_objects/array/at": "

Array.prototype.at()

The at() method of Array instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
at(index)\n
\n

Parameters

\n
index

Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if index < 0, index + array.length is accessed.

Return value

\n

The element in the array matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.

Description

\n
\n

The at() method is equivalent to the bracket notation when index is non-negative. For example, array[0] and array.at(0) both return the first item. However, when counting elements from the end of the array, you cannot use array[-1] like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading array[\"-1\"], which is just a normal string property instead of an array index.

The usual practice is to access length and calculate the index from that — for example, array[array.length - 1]. The at() method allows relative indexing, so this can be shortened to array.at(-1).

By combining at() with with(), you can both read and write (respectively) an array using negative indices.

The at() method is generic. It only expects the this value to have a length property and integer-keyed properties.

\n

Examples

\n

Return the last value of an array

\n
\n

The following example provides a function which returns the last element found in a specified array.

\n

js

\n
// Our array with items\nconst cart = [\"apple\", \"banana\", \"pear\"];\n\n// A function which returns the last item of a given array\nfunction returnLast(arr) {\n  return arr.at(-1);\n}\n\n// Get the last item of our array 'cart'\nconst item1 = returnLast(cart);\nconsole.log(item1); // 'pear'\n\n// Add an item to our 'cart' array\ncart.push(\"orange\");\nconst item2 = returnLast(cart);\nconsole.log(item2); // 'orange'\n
\n
\n

Comparing methods

\n
\n

This example compares different ways to select the penultimate (last but one) item of an Array. While all the methods shown below are valid, this example highlights the succinctness and readability of the at() method.

\n

js

\n
// Our array with items\nconst colors = [\"red\", \"green\", \"blue\"];\n\n// Using length property\nconst lengthWay = colors[colors.length - 2];\nconsole.log(lengthWay); // 'green'\n\n// Using slice() method. Note an array is returned\nconst sliceWay = colors.slice(-2, -1);\nconsole.log(sliceWay[0]); // 'green'\n\n// Using at() method\nconst atWay = colors.at(-2);\nconsole.log(atWay); // 'green'\n
\n
\n

Calling at() on non-array objects

\n
\n

The at() method reads the length property of this and calculates the index to access.

\n

js

\n
const arrayLike = {\n  length: 2,\n  0: \"a\",\n  1: \"b\",\n  2: \"c\", // ignored by at() since length is 2\n};\nconsole.log(Array.prototype.at.call(arrayLike, 0)); // \"a\"\nconsole.log(Array.prototype.at.call(arrayLike, 2)); // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype.at
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
at929290No7815.49292906515.416.01.1216.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at\n

\n
\n", + "global_objects/array/@@iterator": "

Array.prototype[@@iterator]()

\n

The [@@iterator]() method of Array instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the array.

The initial value of this property is the same function object as the initial value of the Array.prototype.values property.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
array[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The same return value as Array.prototype.values(): a new iterable iterator object that yields the value of each index in the array.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes arrays iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

HTML

\n

html

\n
<ul id=\"letterResult\"></ul>\n
\n

JavaScript

\n

js

\n
const arr = [\"a\", \"b\", \"c\"];\nconst letterResult = document.getElementById(\"letterResult\");\nfor (const letter of arr) {\n  const li = document.createElement(\"li\");\n  li.textContent = letter;\n  letterResult.appendChild(li);\n}\n
\n

Result

\n
\n\n\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const arr = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nconst arrIter = arr[Symbol.iterator]();\nconsole.log(arrIter.next().value); // a\nconsole.log(arrIter.next().value); // b\nconsole.log(arrIter.next().value); // c\nconsole.log(arrIter.next().value); // d\nconsole.log(arrIter.next().value); // e\n
\n
\n

Handling strings and string arrays with the same function

\n
\n

Because both strings and arrays implement the iterable protocol, a generic function can be designed to handle both inputs in the same fashion. This is better than calling Array.prototype.values() directly, which requires the input to be an array, or at least an object with such a method.

\n

js

\n
function logIterable(it) {\n  if (typeof it[Symbol.iterator] !== \"function\") {\n    console.log(it, \"is not iterable.\");\n    return;\n  }\n  for (const letter of it) {\n    console.log(letter);\n  }\n}\n\n// Array\nlogIterable([\"a\", \"b\", \"c\"]);\n// a\n// b\n// c\n\n// String\nlogIterable(\"abc\");\n// a\n// b\n// c\n\n// Number\nlogIterable(123);\n// 123 is not iterable.\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-array.prototype-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator\n

\n
\n", + "global_objects/uint32array/uint32array": "

Uint32Array() constructor

The Uint32Array() constructor creates Uint32Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Uint32Array()\nnew Uint32Array(length)\nnew Uint32Array(typedArray)\nnew Uint32Array(object)\n\nnew Uint32Array(buffer)\nnew Uint32Array(buffer, byteOffset)\nnew Uint32Array(buffer, byteOffset, length)\n
\n

Note: Uint32Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Uint32Array

\n
\n

js

\n
// From a length\nconst uint32 = new Uint32Array(2);\nuint32[0] = 42;\nconsole.log(uint32[0]); // 42\nconsole.log(uint32.length); // 2\nconsole.log(uint32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Uint32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Uint32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Uint32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst uint32FromIterable = new Uint32Array(iterable);\nconsole.log(uint32FromIterable);\n// Uint32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Uint32Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array\n

\n
\n", + "global_objects/bigint64array/bigint64array": "

BigInt64Array() constructor

The BigInt64Array() constructor creates BigInt64Array objects. The contents are initialized to 0n.

\n

Syntax

\n
\n
\n

js

\n
new BigInt64Array()\nnew BigInt64Array(length)\nnew BigInt64Array(typedArray)\nnew BigInt64Array(object)\n\nnew BigInt64Array(buffer)\nnew BigInt64Array(buffer, byteOffset)\nnew BigInt64Array(buffer, byteOffset, length)\n
\n

Note: BigInt64Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a BigInt64Array

\n
\n

js

\n
// From a length\nconst bigint64 = new BigInt64Array(2);\nbigint64[0] = 42n;\nconsole.log(bigint64[0]); // 42n\nconsole.log(bigint64.length); // 2\nconsole.log(bigint64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new BigInt64Array([21n, 31n]);\nconsole.log(x[1]); // 31n\n\n// From another TypedArray\nconst y = new BigInt64Array(x);\nconsole.log(y[0]); // 21n\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new BigInt64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1n, 2n, 3n];\n})();\nconst bigint64FromIterable = new BigInt64Array(iterable);\nconsole.log(bigint64FromIterable);\n// BigInt64Array [1n, 2n, 3n]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigInt64Array677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array\n

\n
\n", + "global_objects/biguint64array/biguint64array": "

BigUint64Array() constructor

The BigUint64Array() constructor creates BigUint64Array objects. The contents are initialized to 0n.

\n

Syntax

\n
\n
\n

js

\n
new BigUint64Array()\nnew BigUint64Array(length)\nnew BigUint64Array(typedArray)\nnew BigUint64Array(object)\n\nnew BigUint64Array(buffer)\nnew BigUint64Array(buffer, byteOffset)\nnew BigUint64Array(buffer, byteOffset, length)\n
\n

Note: BigUint64Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a BigUint64Array

\n
\n

js

\n
// From a length\nconst biguint64 = new BigUint64Array(2);\nbiguint64[0] = 42n;\nconsole.log(biguint64[0]); // 42n\nconsole.log(biguint64.length); // 2\nconsole.log(biguint64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new BigUint64Array([21n, 31n]);\nconsole.log(x[1]); // 31n\n\n// From another TypedArray\nconst y = new BigUint64Array(x);\nconsole.log(y[0]); // 21n\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new BigUint64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1n, 2n, 3n];\n})();\nconst biguint64FromIterable = new BigUint64Array(iterable);\nconsole.log(biguint64FromIterable);\n// BigUint64Array [1n, 2n, 3n]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
BigUint64Array677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array\n

\n
\n", + "global_objects/float32array/float32array": "

Float32Array() constructor

The Float32Array() constructor creates Float32Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Float32Array()\nnew Float32Array(length)\nnew Float32Array(typedArray)\nnew Float32Array(object)\n\nnew Float32Array(buffer)\nnew Float32Array(buffer, byteOffset)\nnew Float32Array(buffer, byteOffset, length)\n
\n

Note: Float32Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Float32Array

\n
\n

js

\n
// From a length\nconst float32 = new Float32Array(2);\nfloat32[0] = 42;\nconsole.log(float32[0]); // 42\nconsole.log(float32.length); // 2\nconsole.log(float32.BYTES_PER_ELEMENT); // 4\n\n// From an array\nconst x = new Float32Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Float32Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(32);\nconst z = new Float32Array(buffer, 4, 4);\nconsole.log(z.byteOffset); // 4\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst float32FromIterable = new Float32Array(iterable);\nconsole.log(float32FromIterable);\n// Float32Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Float32Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array\n

\n
\n", + "global_objects/float64array/float64array": "

Float64Array() constructor

The Float64Array() constructor creates Float64Array objects. The contents are initialized to 0.

\n

Syntax

\n
\n
\n

js

\n
new Float64Array()\nnew Float64Array(length)\nnew Float64Array(typedArray)\nnew Float64Array(object)\n\nnew Float64Array(buffer)\nnew Float64Array(buffer, byteOffset)\nnew Float64Array(buffer, byteOffset, length)\n
\n

Note: Float64Array() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n

See TypedArray.

Exceptions

\n

See TypedArray.

Examples

\n

Different ways to create a Float64Array

\n
\n

js

\n
// From a length\nconst float64 = new Float64Array(2);\nfloat64[0] = 42;\nconsole.log(float64[0]); // 42\nconsole.log(float64.length); // 2\nconsole.log(float64.BYTES_PER_ELEMENT); // 8\n\n// From an array\nconst x = new Float64Array([21, 31]);\nconsole.log(x[1]); // 31\n\n// From another TypedArray\nconst y = new Float64Array(x);\nconsole.log(y[0]); // 21\n\n// From an ArrayBuffer\nconst buffer = new ArrayBuffer(64);\nconst z = new Float64Array(buffer, 8, 4);\nconsole.log(z.byteOffset); // 8\n\n// From an iterable\nconst iterable = (function* () {\n  yield* [1, 2, 3];\n})();\nconst float64FromIterable = new Float64Array(iterable);\nconsole.log(float64FromIterable);\n// Float64Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-typedarray-constructors
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Float64Array71241011.65.14184124.21.01.00.10.0
constructor_without_parameters712551011.65.1≤3718551251.01.00.10.0
iterable_allowed391452No261039395226104.01.04.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array\n

\n
\n", + "global_objects/map/set": "

Map.prototype.set()

The set() method of Map instances adds or updates an entry in this map with a specified key and a value.

\n

Try it

\n

Syntax

\n
\n

js

\n
set(key, value)\n
\n

Parameters

\n
key

The key of the element to add to the Map object. The key may be any JavaScript type (any primitive value or any type of JavaScript object).

value

The value of the element to add to the Map object. The value may be any JavaScript type (any primitive value or any type of JavaScript object).

Return value

\n

The Map object.

Examples

\n

Using set()

\n
\n

js

\n
const myMap = new Map();\n\n// Add new elements to the map\nmyMap.set(\"bar\", \"foo\");\nmyMap.set(1, \"foobar\");\n\n// Update an element in the map\nmyMap.set(\"bar\", \"baz\");\n
\n

Using the set() with chaining

\n
\n

Since the set() method returns back the same Map object, you can chain the method call like below:

\n

js

\n
// Add new elements to the map with chaining.\nmyMap.set(\"bar\", \"foo\").set(1, \"foobar\").set(2, \"baz\");\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.set
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set381213
11Returns 'undefined' instead of the 'Map' object.
2583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set\n

\n
\n", + "global_objects/map/size": "

Map.prototype.size

The size accessor property of Map instances returns the number of elements in this map.

\n

Try it

\n

Description

\n

The value of size is an integer representing how many entries the Map object has. A set accessor function for size is undefined; you can not change this property.

Examples

\n

Using size

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"a\", \"alpha\");\nmyMap.set(\"b\", \"beta\");\nmyMap.set(\"g\", \"gamma\");\n\nconsole.log(myMap.size); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-map.prototype.size
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
size3812
19From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
112583838
19From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
2583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size\n

\n
\n", + "global_objects/map/map": "

Map() constructor

The Map() constructor creates Map objects.

\n

Syntax

\n
\n
\n

js

\n
new Map()\nnew Map(iterable)\n
\n

Note: Map() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\niterable Optional\n

An Array or other iterable object whose elements are key-value pairs. (For example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) Each key-value pair is added to the new Map.

Examples

\n

Creating a new Map

\n
\n

js

\n
const myMap = new Map([\n  [1, \"one\"],\n  [2, \"two\"],\n  [3, \"three\"],\n]);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Map381213112583838142583.01.00.12.0
iterable_allowed381213No2593838142593.01.00.12.0
new_required381242112593838422593.01.00.12.0
null_allowed381237112593838372593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/Map\n

\n
\n", + "global_objects/map/@@species": "

Map[@@species]

The Map[@@species] static accessor property is an unused accessor property specifying how to copy Map objects.

\n

Syntax

\n
\n

js

\n
Map[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct copied Map instances.

Description

\n
\n

The @@species accessor property returns the default constructor for Map objects. Subclass constructors may override it to change the constructor assignment.

Note: This property is currently unused by all Map methods.

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the Map constructor for Map.

\n

js

\n
Map[Symbol.species]; // function Map()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom Map subclass, such as MyMap, the MyMap species is the MyMap constructor. However, you might want to overwrite this, in order to return parent Map objects in your derived class methods:

\n

js

\n
class MyMap extends Map {\n  // Overwrite MyMap species to the parent Map constructor\n  static get [Symbol.species]() {\n    return Map;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-map-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species511341No381051514141105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@species\n

\n
\n", + "global_objects/map/groupby": "

Map.groupBy()

\n

Note: In some versions of some browsers, this method was implemented as the method Array.prototype.groupToMap(). Due to web compatibility issues, it is now implemented as a static method. Check the browser compatibility table for details.

The Map.groupBy() static method groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.

The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with Object.groupBy().

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Map.groupBy(items, callbackFn)\n
\n

Parameters

\n
items

An iterable (such as an Array) whose elements will be grouped.

callbackFn

A function to execute for each element in the iterable. It should return a value (object or primitive) indicating the group of the current element. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

A Map object with keys for each group, each assigned to an array containing the elements of the associated group.

Description

\n
\n

Map.groupBy() calls a provided callbackFn function once for each element in an iterable. The callback function should return a value indicating the group of the associated element. The values returned by callbackFn are used as keys for the Map returned by Map.groupBy(). Each key has an associated array containing all the elements for which the callback returned the same value.

The elements in the returned Map and the original iterable are the same (not deep copies). Changing the internal structure of the elements will be reflected in both the original iterable and the returned Map.

This method is useful when you need to group information that is related to a particular object that might potentially change over time. This is because even if the object is modified, it will continue to work as a key to the returned Map. If you instead create a string representation for the object and use that as a grouping key in Object.groupBy(), you must maintain the mapping between the original object and its representation as the object changes.

Note: To access the groups in the returned Map, you must use the same object that was originally used as a key in the Map (although you may modify its properties). You can't use another object that just happens to have the same name and properties.

Map.groupBy does not read the value of this. It can be called on any object and a new Map instance will be returned.

\n

Examples

\n

Using Map.groupBy()

\n
\n

First we define an array containing objects representing an inventory of different foodstuffs. Each food has a type and a quantity.

\n

js

\n
const inventory = [\n  { name: \"asparagus\", type: \"vegetables\", quantity: 9 },\n  { name: \"bananas\", type: \"fruit\", quantity: 5 },\n  { name: \"goat\", type: \"meat\", quantity: 23 },\n  { name: \"cherries\", type: \"fruit\", quantity: 12 },\n  { name: \"fish\", type: \"meat\", quantity: 22 },\n];\n
\n

The code below uses Map.groupBy() with an arrow function that returns the object keys named restock or sufficient, depending on whether the element has quantity < 6. The returned result object is a Map so we need to call get() with the key to obtain the array.

\n

js

\n
const restock = { restock: true };\nconst sufficient = { restock: false };\nconst result = Map.groupBy(inventory, ({ quantity }) =>\n  quantity < 6 ? restock : sufficient,\n);\nconsole.log(result.get(restock));\n// [{ name: \"bananas\", type: \"fruit\", quantity: 5 }]\n
\n

Note that the function argument { quantity } is a basic example of object destructuring syntax for function arguments. This unpacks the quantity property of an object passed as a parameter, and assigns it to a variable named quantity in the body of the function. This is a very succinct way to access the relevant values of elements within a function.

The key to a Map can be modified and still used. However you can't recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.

\n

js

\n
// The key can be modified and still used\nrestock[\"fast\"] = true;\nconsole.log(result.get(restock));\n// [{ name: \"bananas\", type: \"fruit\", quantity: 5 }]\n\n// A new key can't be used, even if it has the same structure!\nconst restock2 = { restock: true };\nconsole.log(result.get(restock2)); // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
Array Grouping
# sec-map.groupby
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
groupBy117117119No10316.4–previewpreview117117119No16.4No1.37No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy\n

\n
\n", + "global_objects/map/clear": "

Map.prototype.clear()

The clear() method of Map instances removes all elements from this map.

\n

Try it

\n

Syntax

\n
\n

js

\n
clear()\n
\n

Parameters

\n

None.

Return value

\n

None (undefined).

Examples

\n

Using clear()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"bar\", \"baz\");\nmyMap.set(1, \"foo\");\n\nconsole.log(myMap.size); // 2\nconsole.log(myMap.has(\"bar\")); // true\n\nmyMap.clear();\n\nconsole.log(myMap.size); // 0\nconsole.log(myMap.has(\"bar\")); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.clear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
clear381219112583838192583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear\n

\n
\n", + "global_objects/map/entries": "

Map.prototype.entries()

The entries() method of Map instances returns a new map iterator object that contains the [key, value] pairs for each element in this map in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
entries()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using entries()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"0\", \"foo\");\nmyMap.set(1, \"bar\");\nmyMap.set({}, \"baz\");\n\nconst mapIter = myMap.entries();\n\nconsole.log(mapIter.next().value); // [\"0\", \"foo\"]\nconsole.log(mapIter.next().value); // [1, \"bar\"]\nconsole.log(mapIter.next().value); // [Object, \"baz\"]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.entries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
entries381220No2583838202583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries\n

\n
\n", + "global_objects/map/foreach": "

Map.prototype.forEach()

The forEach() method of Map instances executes a provided function once per each key/value pair in this map, in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
forEach(callbackFn)\nforEach(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each entry in the map. The function is called with the following arguments:

value

Value of each iteration.

key

Key of each iteration.

map

The map being iterated.

\nthisArg Optional\n

A value to use as this when executing callbackFn.

Return value

\n

None (undefined).

Description

\n
\n

The forEach method executes the provided callback once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value undefined.

callback is invoked with three arguments:

If a thisArg parameter is provided to forEach, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

Each value is visited once, except in the case when it was deleted and re-added before forEach has finished. callback is not invoked for values deleted before being visited. New values added before forEach has finished will be visited.

\n

Examples

\n

Printing the contents of a Map object

\n
\n

The following code logs a line for each element in an Map object:

\n

js

\n
function logMapElements(value, key, map) {\n  console.log(`map.get('${key}') = ${value}`);\n}\nnew Map([\n  [\"foo\", 3],\n  [\"bar\", {}],\n  [\"baz\", undefined],\n]).forEach(logMapElements);\n// Logs:\n// \"map.get('foo') = 3\"\n// \"map.get('bar') = [object Object]\"\n// \"map.get('baz') = undefined\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.foreach
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
forEach381225112583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach\n

\n
\n", + "global_objects/map/get": "

Map.prototype.get()

The get() method of Map instances returns a specified element from this map. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.

\n

Try it

\n

Syntax

\n
\n

js

\n
get(key)\n
\n

Parameters

\n
key

The key of the element to return from the Map object.

Return value

\n

The element associated with the specified key, or undefined if the key can't be found in the Map object.

Examples

\n

Using get()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"bar\", \"foo\");\n\nconsole.log(myMap.get(\"bar\")); // Returns \"foo\"\nconsole.log(myMap.get(\"baz\")); // Returns undefined\n
\n

Using get() to retrieve a reference to an object

\n
\n
\n

js

\n
const arr = [];\nconst myMap = new Map();\nmyMap.set(\"bar\", arr);\n\nmyMap.get(\"bar\").push(\"foo\");\n\nconsole.log(arr); // [\"foo\"]\nconsole.log(myMap.get(\"bar\")); // [\"foo\"]\n
\n

Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a WeakMap.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.get
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
get381213112583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get\n

\n
\n", + "global_objects/map/has": "

Map.prototype.has()

The has() method of Map instances returns a boolean indicating whether an element with the specified key exists in this map or not.

\n

Try it

\n

Syntax

\n
\n

js

\n
has(key)\n
\n

Parameters

\n
key

The key of the element to test for presence in the Map object.

Return value

\n

true if an element with the specified key exists in the Map object; otherwise false.

Examples

\n

Using has()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"bar\", \"foo\");\n\nconsole.log(myMap.has(\"bar\")); // true\nconsole.log(myMap.has(\"baz\")); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.has
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has381213112583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has\n

\n
\n", + "global_objects/map/keys": "

Map.prototype.keys()

The keys() method of Map instances returns a new map iterator object that contains the keys for each element in this map in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
keys()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using keys()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"0\", \"foo\");\nmyMap.set(1, \"bar\");\nmyMap.set({}, \"baz\");\n\nconst mapIter = myMap.keys();\n\nconsole.log(mapIter.next().value); // \"0\"\nconsole.log(mapIter.next().value); // 1\nconsole.log(mapIter.next().value); // {}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.keys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keys381220No2583838202583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys\n

\n
\n", + "global_objects/map/values": "

Map.prototype.values()

The values() method of Map instances returns a new map iterator object that contains the values for each element in this map in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
values()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using values()

\n
\n

js

\n
const myMap = new Map();\nmyMap.set(\"0\", \"foo\");\nmyMap.set(1, \"bar\");\nmyMap.set({}, \"baz\");\n\nconst mapIter = myMap.values();\n\nconsole.log(mapIter.next().value); // \"foo\"\nconsole.log(mapIter.next().value); // \"bar\"\nconsole.log(mapIter.next().value); // \"baz\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype.values
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
values381220No2583838202583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values\n

\n
\n", + "global_objects/map/@@iterator": "

Map.prototype[@@iterator]()

\n

The [@@iterator]() method of Map instances implements the iterable protocol and allows Map objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a map iterator object that yields the key-value pairs of the map in insertion order.

The initial value of this property is the same function object as the initial value of the Map.prototype.entries property.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
map[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The same return value as Map.prototype.entries(): a new iterable iterator object that yields the key-value pairs of the map.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes Map objects iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const myMap = new Map();\nmyMap.set(\"0\", \"foo\");\nmyMap.set(1, \"bar\");\nmyMap.set({}, \"baz\");\n\nfor (const entry of myMap) {\n  console.log(entry);\n}\n// [\"0\", \"foo\"]\n// [1, \"bar\"]\n// [{}, \"baz\"]\n\nfor (const [key, value] of myMap) {\n  console.log(`${key}: ${value}`);\n}\n// 0: foo\n// 1: bar\n// [Object]: baz\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const myMap = new Map();\nmyMap.set(\"0\", \"foo\");\nmyMap.set(1, \"bar\");\nmyMap.set({}, \"baz\");\n\nconst mapIter = myMap[Symbol.iterator]();\n\nconsole.log(mapIter.next().value); // [\"0\", \"foo\"]\nconsole.log(mapIter.next().value); // [1, \"bar\"]\nconsole.log(mapIter.next().value); // [Object, \"baz\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-map.prototype-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator\n

\n
\n", + "global_objects/set/add": "

Set.prototype.add()

The add() method of Set instances inserts a new element with a specified value in to this set, if there isn't an element with the same value already in this set

\n

Try it

\n

Syntax

\n
\n

js

\n
add(value)\n
\n

Parameters

\n
value

The value of the element to add to the Set object.

Return value

\n

The Set object with added value.

Examples

\n

Using the add() method

\n
\n

js

\n
const mySet = new Set();\n\nmySet.add(1);\nmySet.add(5).add(\"some text\"); // chainable\n\nconsole.log(mySet);\n// Set [1, 5, \"some text\"]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.add
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
add381213
11Returns 'undefined' instead of the 'Set' object.
2583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/add\n

\n
\n", + "global_objects/set/has": "

Set.prototype.has()

The has() method of Set instances returns a boolean indicating whether an element with the specified value exists in this set or not.

\n

Try it

\n

Syntax

\n
\n

js

\n
has(value)\n
\n

Parameters

\n
value

The value to test for presence in the Set object.

Return value

\n

Returns true if an element with the specified value exists in the Set object; otherwise false.

Examples

\n

Using the has() method

\n
\n

js

\n
const mySet = new Set();\nmySet.add(\"foo\");\n\nconsole.log(mySet.has(\"foo\")); // true\nconsole.log(mySet.has(\"bar\")); // false\n\nconst set1 = new Set();\nconst obj1 = { key1: 1 };\nset1.add(obj1);\n\nconsole.log(set1.has(obj1)); // true\nconsole.log(set1.has({ key1: 1 })); // false, because they are different object references\nconsole.log(set1.add({ key1: 1 })); // now set1 contains 2 entries\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.has
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has381213112583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has\n

\n
\n", + "global_objects/set/set": "

Set() constructor

The Set() constructor creates Set objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Set()\nnew Set(iterable)\n
\n

Note: Set() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\niterable Optional\n

If an iterable object is passed, all of its elements will be added to the new Set.

If you don't specify this parameter, or its value is null, the new Set is empty.

Return value

\n

A new Set object.

Examples

\n

Using the Set object

\n
\n

js

\n
const mySet = new Set();\n\nmySet.add(1); // Set [ 1 ]\nmySet.add(5); // Set [ 1, 5 ]\nmySet.add(5); // Set [ 1, 5 ]\nmySet.add(\"some text\"); // Set [ 1, 5, 'some text' ]\nconst o = { a: 1, b: 2 };\nmySet.add(o);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Set381213112583838142583.01.00.12.0
iterable_allowed381213No2593838142593.01.00.12.0
new_required381242112593838422593.01.00.12.0
null_allowed381237112593838372593.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set\n

\n
\n", + "global_objects/set/@@species": "

Set[@@species]

The Set[@@species] static accessor property is an unused accessor property specifying how to copy Set objects.

\n

Syntax

\n
\n

js

\n
Set[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct copied Set instances.

Description

\n
\n

The @@species accessor property returns the default constructor for Set objects. Subclass constructors may override it to change the constructor assignment.

Note: This property is currently unused by all Set methods.

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the Set constructor for Set.

\n

js

\n
Set[Symbol.species]; // function Set()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom Set subclass, such as MySet, the MySet species is the MySet constructor. However, you might want to overwrite this, in order to return parent Set objects in your derived class methods:

\n

js

\n
class MySet extends Set {\n  // Overwrite MySet species to the parent Set constructor\n  static get [Symbol.species]() {\n    return Set;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-set-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species511341No381051514141105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@species\n

\n
\n", + "global_objects/set/size": "

Set.prototype.size

The size accessor property of Set instances returns the number of (unique) elements in this set.

\n

Try it

\n

Description

\n

The value of size is an integer representing how many entries the Set object has. A set accessor function for size is undefined; you cannot change this property.

Examples

\n

Using size

\n
\n

js

\n
const mySet = new Set();\nmySet.add(1);\nmySet.add(5);\nmySet.add(\"some text\");\n\nconsole.log(mySet.size); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-set.prototype.size
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
size3812
19From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
112583838
19From Firefox 13 to Firefox 18, the size property was implemented as a Set.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
2583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/size\n

\n
\n", + "global_objects/set/clear": "

Set.prototype.clear()

The clear() method of Set instances removes all elements from this set.

\n

Try it

\n

Syntax

\n
\n

js

\n
clear()\n
\n

Parameters

\n

None.

Return value

\n

None (undefined).

Examples

\n

Using the clear() method

\n
\n

js

\n
const mySet = new Set();\nmySet.add(1);\nmySet.add(\"foo\");\n\nconsole.log(mySet.size); // 2\nconsole.log(mySet.has(\"foo\")); // true\n\nmySet.clear();\n\nconsole.log(mySet.size); // 0\nconsole.log(mySet.has(\"foo\")); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.clear
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
clear381219112583838192583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/clear\n

\n
\n", + "global_objects/set/delete": "

Set.prototype.delete()

The delete() method of Set instances removes a specified value from this set, if it is in the set.

\n

Try it

\n

Syntax

\n
\n

js

\n
setInstance.delete(value)\n
\n

Parameters

\n
value

The value to remove from Set.

Return value

\n

Returns true if value was already in Set; otherwise false.

Examples

\n

Using the delete() method

\n
\n

js

\n
const mySet = new Set();\nmySet.add(\"foo\");\n\nconsole.log(mySet.delete(\"bar\")); // false; no \"bar\" element found to be deleted.\nconsole.log(mySet.delete(\"foo\")); // true; successfully removed.\n\nconsole.log(mySet.has(\"foo\")); // false; the \"foo\" element is no longer present.\n
\n

Deleting an object from a set

\n
\n

Because objects are compared by reference, you have to delete them by checking individual properties if you don't have a reference to the original object.

\n

js

\n
const setObj = new Set(); // Create a new set.\n\nsetObj.add({ x: 10, y: 20 }); // Add object in the set.\n\nsetObj.add({ x: 20, y: 30 }); // Add object in the set.\n\n// Delete any point with `x > 10`.\nsetObj.forEach((point) => {\n  if (point.x > 10) {\n    setObj.delete(point);\n  }\n});\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.delete
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
delete381213112583838142583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/delete\n

\n
\n", + "global_objects/set/entries": "

Set.prototype.entries()

The entries() method of Set instances returns a new set iterator object that contains [value, value] for each element in this set, in insertion order. For Set objects there is no key like in Map objects. However, to keep the API similar to the Map object, each entry has the same value for its key and value here, so that an array [value, value] is returned.

\n

Try it

\n

Syntax

\n
\n

js

\n
entries()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using entries()

\n
\n

js

\n
const mySet = new Set();\nmySet.add(\"foobar\");\nmySet.add(1);\nmySet.add(\"baz\");\n\nconst setIter = mySet.entries();\n\nconsole.log(setIter.next().value); // [\"foobar\", \"foobar\"]\nconsole.log(setIter.next().value); // [1, 1]\nconsole.log(setIter.next().value); // [\"baz\", \"baz\"]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.entries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
entries381224No2583838242583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries\n

\n
\n", + "global_objects/set/foreach": "

Set.prototype.forEach()

The forEach() method of Set instances executes a provided function once for each value in this set, in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
forEach(callbackFn)\nforEach(callbackFn, thisArg)\n
\n

Parameters

\n
callback

A function to execute for each entry in the set. The function is called with the following arguments:

value

Value of each iteration.

key

Key of each iteration. This is always the same as value.

set

The set being iterated.

\nthisArg Optional\n

A value to use as this when executing callbackFn.

Return value

\n

None (undefined).

Description

\n
\n

The forEach() method executes the provided callback once for each value which actually exists in the Set object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value undefined.

callback is invoked with three arguments:

There are no keys in Set objects, however, so the first two arguments are both values contained in the Set. This is to make it consistent with other forEach() methods for Map and Array.

If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

Each value is visited once, except in the case when it was deleted and re-added before forEach() has finished. callback is not invoked for values deleted before being visited. New values added before forEach() has finished will be visited.

forEach() executes the callback function once for each element in the Set object; it does not return a value.

\n

Examples

\n

Logging the contents of a Set object

\n
\n

The following code logs a line for each element in a Set object:

\n

js

\n
function logSetElements(value1, value2, set) {\n  console.log(`s[${value1}] = ${value2}`);\n}\n\nnew Set([\"foo\", \"bar\", undefined]).forEach(logSetElements);\n\n// Logs:\n// \"s[foo] = foo\"\n// \"s[bar] = bar\"\n// \"s[undefined] = undefined\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.foreach
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
forEach381225112583838252583.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach\n

\n
\n", + "global_objects/set/keys": "

Set.prototype.keys()

The keys() method of Set instances is an alias for the values() method.

\n

Syntax

\n
\n

js

\n
keys()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using keys()

\n
\n

The keys() method is exactly equivalent to the values() method.

\n

js

\n
const mySet = new Set();\nmySet.add(\"foo\");\nmySet.add(\"bar\");\nmySet.add(\"baz\");\n\nconst setIter = mySet.keys();\n\nconsole.log(setIter.next().value); // \"foo\"\nconsole.log(setIter.next().value); // \"bar\"\nconsole.log(setIter.next().value); // \"baz\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.keys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keys383812122424No2525883838383824242525883.03.01.01.00.12.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/keys\n

\n
\n", + "global_objects/set/values": "

Set.prototype.values()

The values() method of Set instances returns a new set iterator object that contains the values for each element in this set in insertion order.

\n

Try it

\n

Syntax

\n
\n

js

\n
values()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Examples

\n

Using values()

\n
\n

js

\n
const mySet = new Set();\nmySet.add(\"foo\");\nmySet.add(\"bar\");\nmySet.add(\"baz\");\n\nconst setIter = mySet.values();\n\nconsole.log(setIter.next().value); // \"foo\"\nconsole.log(setIter.next().value); // \"bar\"\nconsole.log(setIter.next().value); // \"baz\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype.values
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
values383812122424No2525883838383824242525883.03.01.01.00.12.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values\n

\n
\n", + "global_objects/set/@@iterator": "

Set.prototype[@@iterator]()

\n

The [@@iterator]() method of Set instances implements the iterable protocol and allows Set objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a set iterator object that yields the values of the set in insertion order.

The initial value of this property is the same function object as the initial value of the Set.prototype.values property.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
set[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The same return value as Set.prototype.values(): a new iterable iterator object that yields the values of the set.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes Set objects iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const mySet = new Set();\nmySet.add(\"0\");\nmySet.add(1);\nmySet.add({});\n\nfor (const v of mySet) {\n  console.log(v);\n}\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const mySet = new Set();\nmySet.add(\"0\");\nmySet.add(1);\nmySet.add({});\n\nconst setIter = mySet[Symbol.iterator]();\n\nconsole.log(setIter.next().value); // \"0\"\nconsole.log(setIter.next().value); // 1\nconsole.log(setIter.next().value); // {}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-set.prototype-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator431236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No309434336
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
3094.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator\n

\n
\n", + "global_objects/weakmap/weakmap": "

WeakMap() constructor

The WeakMap() constructor creates WeakMap objects.

\n

Syntax

\n
\n
\n

js

\n
new WeakMap()\nnew WeakMap(iterable)\n
\n

Note: WeakMap() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
iterable

An Array or other iterable object that implements an @@iterator method that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a WeakMap key and whose second element is the value to associate with that key. Each key-value pair will be added to the new WeakMap. null is treated as undefined.

Examples

\n

Using WeakMap

\n
\n

js

\n
const wm1 = new WeakMap();\nconst wm2 = new WeakMap();\nconst wm3 = new WeakMap();\nconst o1 = {};\nconst o2 = function () {};\nconst o3 = window;\n\nwm1.set(o1, 37);\nwm1.set(o2, \"azerty\");\nwm2.set(o1, o2); // a value can be anything, including an object or a function\nwm2.set(o3, undefined);\nwm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!\n\nwm1.get(o2); // \"azerty\"\nwm2.get(o2); // undefined, because there is no key for o2 on wm2\nwm2.get(o3); // undefined, because that is the set value\n\nwm1.has(o2); // true\nwm2.has(o2); // false\nwm2.has(o3); // true (even if the value itself is 'undefined')\n\nwm3.set(o1, 37);\nwm3.get(o1); // 37\n\nwm1.has(o1); // true\nwm1.delete(o1);\nwm1.has(o1); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakMap3612611238373662483.01.00.12.0
iterable_allowed381236No2593838362593.01.00.12.0
new_required361242112393736422493.01.00.12.0
null_allowed361237112383736372483.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/WeakMap\n

\n
\n", + "global_objects/weakmap/delete": "

WeakMap.prototype.delete()

The delete() method of WeakMap instances removes the specified element from this WeakMap.

\n

Try it

\n

Syntax

\n
\n

js

\n
weakMapInstance.delete(key)\n
\n

Parameters

\n
key

The key of the element to remove from the WeakMap object.

Return value

\n

true if an element in the WeakMap object has been removed successfully. false if the key is not found in the WeakMap. Always returns false if key is not an object or a non-registered symbol.

Examples

\n

Using the delete() method

\n
\n

js

\n
const wm = new WeakMap();\nwm.set(window, \"foo\");\n\nwm.delete(window); // Returns true. Successfully removed.\n\nwm.has(window); // Returns false. The window object is no longer in the WeakMap.\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap.prototype.delete
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
delete3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/delete\n

\n
\n", + "global_objects/weakmap/get": "

WeakMap.prototype.get()

The get() method of WeakMap instances returns a specified element from this WeakMap.

\n

Try it

\n

Syntax

\n
\n

js

\n
get(key)\n
\n

Parameters

\n
key

The key of the element to return from the WeakMap object.

Return value

\n

The element associated with the specified key in the WeakMap object. If the key can't be found, undefined is returned. Always returns undefined if key is not an object or a non-registered symbol.

Examples

\n

Using the get() method

\n
\n

js

\n
const wm = new WeakMap();\nwm.set(window, \"foo\");\n\nwm.get(window); // Returns \"foo\".\nwm.get(\"baz\"); // Returns undefined.\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap.prototype.get
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
get3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
2483.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/get\n

\n
\n", + "global_objects/weakmap/has": "

WeakMap.prototype.has()

The has() method of WeakMap instances returns a boolean indicating whether an element with the specified key exists in this WeakMap or not.

\n

Try it

\n

Syntax

\n
\n

js

\n
has(key)\n
\n

Parameters

\n
key

The key of the element to test for presence in the WeakMap object.

Return value

\n

Returns true if an element with the specified key exists in the WeakMap object; otherwise false. Always returns false if key is not an object or a non-registered symbol.

Examples

\n

Using the has method

\n
\n

js

\n
const wm = new WeakMap();\nwm.set(window, \"foo\");\n\nwm.has(window); // returns true\nwm.has(\"baz\"); // returns false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap.prototype.has
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
112383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/has\n

\n
\n", + "global_objects/weakmap/set": "

WeakMap.prototype.set()

The set() method of WeakMap instances adds a new element with a specified key and value to this WeakMap.

\n

Try it

\n

Syntax

\n
\n

js

\n
set(key, value)\n
\n

Parameters

\n
key

Must be either an object or a non-registered symbol. The key of the entry to add to the WeakMap object.

value

Any value representing the value of the entry to add to the WeakMap object.

Return value

\n

The WeakMap object.

Exceptions

\n
TypeError

Thrown if key is not an object or a non-registered symbol.

Examples

\n

Using the set() method

\n
\n

js

\n
const wm = new WeakMap();\nconst obj = {};\n\n// Add new elements to the WeakMap\nwm.set(obj, \"foo\").set(window, \"bar\"); // chainable\n\n// Update an element in the WeakMap\nwm.set(obj, \"baz\");\n\n// Using a non-registered symbol as key\nconst sym = Symbol(\"foo\");\nwm.set(sym, \"baz\");\nwm.set(Symbol.iterator, \"qux\");\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakmap.prototype.set
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set3612
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
11Returns 'undefined' instead of the 'Map' object.
2383736
6Before Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
2483.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/set\n

\n
\n", + "global_objects/weakset/weakset": "

WeakSet() constructor

The WeakSet() constructor creates WeakSet objects.

\n

Syntax

\n
\n
\n

js

\n
new WeakSet()\nnew WeakSet(iterable)\n
\n

Note: WeakSet() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\niterable Optional\n

If an iterable object is passed, all of its elements will be added to the new WeakSet. null is treated as undefined.

Examples

\n

Using the WeakSet object

\n
\n
\n

js

\n
const ws = new WeakSet();\nconst foo = {};\nconst bar = {};\n\nws.add(foo);\nws.add(bar);\n\nws.has(foo); // true\nws.has(bar); // true\n\nws.delete(foo); // removes foo from the set\nws.has(foo); // false, foo has been removed\nws.has(bar); // true, bar is retained\n
\n

Note that foo !== bar. While they are similar objects, they are not the same object. And so they are both added to the set.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakset-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakSet361234No2393736342493.01.00.12.0
iterable_allowed381234No2593838342593.01.00.12.0
null_allowed361237No2393736372493.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/WeakSet\n

\n
\n", + "global_objects/weakset/add": "

WeakSet.prototype.add()

The add() method of WeakSet instances appends a new object to the end of this WeakSet.

\n

Try it

\n

Syntax

\n
\n

js

\n
add(value)\n
\n

Parameters

\n
value

Must be either an object or a non-registered symbol. The value to add to the WeakSet collection.

Return value

\n

The WeakSet object.

Exceptions

\n
TypeError

Thrown if value is not an object or a non-registered symbol.

Examples

\n

Using add

\n
\n

js

\n
const ws = new WeakSet();\n\nws.add(window); // add the window object to the WeakSet\n\nws.has(window); // true\n\n// WeakSet only takes objects as arguments\nws.add(1);\n// results in \"TypeError: Invalid value used in weak set\" in Chrome\n// and \"TypeError: 1 is not a non-null object\" in Firefox\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakset.prototype.add
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
add361234No2393736342493.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/add\n

\n
\n", + "global_objects/weakset/delete": "

WeakSet.prototype.delete()

The delete() method of WeakSet instances removes the specified element from this WeakSet.

\n

Try it

\n

Syntax

\n
\n

js

\n
weakSetInstance.delete(value)\n
\n

Parameters

\n
value

The value to remove from the WeakSet object.

Return value

\n

true if an element in the WeakSet object has been removed successfully. false if the value is not found in the WeakSet. Always returns false if value is not an object or a non-registered symbol.

Examples

\n

Using the delete() method

\n
\n

js

\n
const ws = new WeakSet();\nconst obj = {};\n\nws.add(window);\n\nws.delete(obj); // Returns false. No obj found to be deleted.\nws.delete(window); // Returns true. Successfully removed.\n\nws.has(window); // Returns false. The window is no longer present in the WeakSet.\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakset.prototype.delete
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
delete361234No2393736342493.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/delete\n

\n
\n", + "global_objects/weakset/has": "

WeakSet.prototype.has()

The has() method of WeakSet instances returns a boolean indicating whether an object exists in this WeakSet or not.

\n

Try it

\n

Syntax

\n
\n

js

\n
has(value)\n
\n

Parameters

\n
value

The value to test for presence in the WeakSet.

Return value

\n

Returns true if an element with the specified value exists in the WeakSet object; otherwise false. Always returns false if value is not an object or a non-registered symbol.

Examples

\n

Using the has() method

\n
\n

js

\n
const ws = new WeakSet();\nconst obj = {};\nws.add(window);\n\nws.has(window); // returns true\nws.has(obj); // returns false\n\n// Storing a non-registered symbol\nconst sym = Symbol(\"foo\");\nws.add(sym);\nws.add(Symbol.iterator);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weakset.prototype.has
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has361234No2393736342493.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/has\n

\n
\n", + "global_objects/arraybuffer/arraybuffer": "

ArrayBuffer() constructor

The ArrayBuffer() constructor creates ArrayBuffer objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new ArrayBuffer(length)\nnew ArrayBuffer(length, options)\n
\n

Note: ArrayBuffer() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
length

The size, in bytes, of the array buffer to create.

\noptions Optional\n

An object, which can contain the following properties:

\nmaxByteLength Optional\n

The maximum size, in bytes, that the array buffer can be resized to.

Return value

\n

A new ArrayBuffer object of the specified size, with its maxByteLength property set to the specified maxByteLength if one was specified. Its contents are initialized to 0.

Exceptions

\n
RangeError

Thrown in one of the following cases:

  • \nlength or maxByteLength is larger than Number.MAX_SAFE_INTEGER (≥ 253) or negative.
  • \nlength is larger than maxByteLength.

Examples

\n

Creating an ArrayBuffer

\n
\n

In this example, we create a 8-byte buffer with a Int32Array view referring to the buffer:

\n

js

\n
const buffer = new ArrayBuffer(8);\nconst view = new Int32Array(buffer);\n
\n
\n

Creating a resizable ArrayBuffer

\n
\n

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then resize() it to 12 bytes:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\n\nbuffer.resize(12);\n
\n

Note: It is recommended that maxByteLength is set to the smallest value possible for your use case. It should never exceed 1073741824 (1GB) to reduce the risk of out-of-memory errors.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arraybuffer-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ArrayBuffer71241011.65.14184124.21.01.00.10.0
maxByteLength_option111111NoNo9716.4111111NoNo16.422.01.3320.0.0
new_required71444No155.1≤3718441451.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer\n

\n
\n", + "global_objects/arraybuffer/resizable": "

ArrayBuffer.prototype.resizable

The resizable accessor property of ArrayBuffer instances returns whether this array buffer can be resized or not.

\n

Try it

\n

Description

\n

The resizable property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the array is constructed. If the maxByteLength option was set in the constructor, resizable will return true; if not, it will return false.

Examples

\n

Using resizable

\n
\n

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its resizable property, resizing it if resizable returns true:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\n\nif (buffer.resizable) {\n  console.log(\"Buffer is resizable!\");\n  buffer.resize(12);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-arraybuffer.prototype.resizable
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resizable111111NoNo9716.4111111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resizable\n

\n
\n", + "global_objects/arraybuffer/maxbytelength": "

ArrayBuffer.prototype.maxByteLength

The maxByteLength accessor property of ArrayBuffer instances returns the maximum length (in bytes) that this array buffer can be resized to.

\n

Try it

\n

Description

\n
\n

The maxByteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the array is constructed, set via the maxByteLength option of the ArrayBuffer() constructor, and cannot be changed.

This property returns 0 if this ArrayBuffer has been detached. If this ArrayBuffer was constructed without specifying a maxByteLength value, this property returns a value equal to the value of the ArrayBuffer's byteLength.

\n

Examples

\n

Using maxByteLength

\n
\n

In this example, we create an 8-byte buffer that is resizable to a max length of 16 bytes, then return its maxByteLength:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\n\nbuffer.maxByteLength; // 16\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-arraybuffer.prototype.maxbytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
maxByteLength111111NoNo9716.4111111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/maxByteLength\n

\n
\n", + "global_objects/arraybuffer/resize": "

ArrayBuffer.prototype.resize()

The resize() method of ArrayBuffer instances resizes the ArrayBuffer to the specified size, in bytes.

\n

Try it

\n

Syntax

\n
\n

js

\n
resize(newLength)\n
\n

Parameters

\n
newLength

The new length, in bytes, to resize the ArrayBuffer to.

Return value

\n

None (undefined).

Exceptions

\n
TypeError

Thrown if the ArrayBuffer is detached or is not resizable.

RangeError

Thrown if newLength is larger than the maxByteLength of the ArrayBuffer.

Description

\n
\n

The resize() method resizes an ArrayBuffer to the size specified by the newLength parameter, provided that the ArrayBuffer is resizable and the new size is less than or equal to the maxByteLength of the ArrayBuffer. New bytes are initialized to 0.

Note that you can use resize() to shrink as well as grow an ArrayBuffer — it is permissible for newLength to be smaller than the ArrayBuffer's current byteLength.

\n

Examples

\n

Using resize()

\n
\n

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its resizable property, resizing it if resizable returns true:

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\n\nif (buffer.resizable) {\n  console.log(\"Buffer is resizable!\");\n  buffer.resize(12);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arraybuffer.prototype.resize
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resize111111NoNo9716.4111111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize\n

\n
\n", + "global_objects/arraybuffer/transfer": "

ArrayBuffer.prototype.transfer()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The transfer() method of ArrayBuffer instances creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

\n
\n

Syntax

\n
\n

js

\n
transfer()\ntransfer(newByteLength)\n
\n

Parameters

\n
\nnewByteLength Optional\n

The byteLength of the new ArrayBuffer. Defaults to the byteLength of this ArrayBuffer.

  • If newByteLength is smaller than the byteLength of this ArrayBuffer, the \"overflowing\" bytes are dropped.
  • If newByteLength is larger than the byteLength of this ArrayBuffer, the extra bytes are filled with zeros.
  • If this ArrayBuffer is resizable, newByteLength must not be greater than its maxByteLength.

Return value

\n

A new ArrayBuffer object. Its contents are initialized to the contents of this ArrayBuffer, and extra bytes, if any, are filled with zeros. The new ArrayBuffer is resizable if and only if this ArrayBuffer is resizable, in which case its maxByteLength is the same as this ArrayBuffer's. The original ArrayBuffer is detached.

Exceptions

\n
RangeError

Thrown if this ArrayBuffer is resizable and newByteLength is greater than the maxByteLength of this ArrayBuffer.

TypeError

Thrown if this ArrayBuffer is already detached.

Description

\n
\n

The transfer() method performs the same operation as the structured clone algorithm. It copies the bytes of this ArrayBuffer into a new ArrayBuffer object, then detaches this ArrayBuffer object. See transferring ArrayBuffers for more information.

transfer() preserves the resizability of this ArrayBuffer. If you want the new ArrayBuffer to be non-resizable, use transferToFixedLength() instead. There's no way to transfer a buffer that makes a fixed-length buffer become resizable.

transfer() is very efficient because implementations may implement this method as a zero-copy move or a realloc — there does not need to be an actual copy of the data.

\n

Examples

\n

Transferring an ArrayBuffer

\n
\n

js

\n
// Create an ArrayBuffer and write a few bytes\nconst buffer = new ArrayBuffer(8);\nconst view = new Uint8Array(buffer);\nview[1] = 2;\nview[7] = 4;\n\n// Copy the buffer to the same size\nconst buffer2 = buffer.transfer();\nconsole.log(buffer.detached); // true\nconsole.log(buffer2.byteLength); // 8\nconst view2 = new Uint8Array(buffer2);\nconsole.log(view2[1]); // 2\nconsole.log(view2[7]); // 4\n\n// Copy the buffer to a smaller size\nconst buffer3 = buffer2.transfer(4);\nconsole.log(buffer3.byteLength); // 4\nconst view3 = new Uint8Array(buffer3);\nconsole.log(view3[1]); // 2\nconsole.log(view3[7]); // undefined\n\n// Copy the buffer to a larger size\nconst buffer4 = buffer3.transfer(8);\nconsole.log(buffer4.byteLength); // 8\nconst view4 = new Uint8Array(buffer4);\nconsole.log(view4[1]); // 2\nconsole.log(view4[7]); // 0\n\n// Already detached, throws TypeError\nbuffer.transfer(); // TypeError: Cannot perform ArrayBuffer.prototype.transfer on a detached ArrayBuffer\n
\n

Transferring a resizable ArrayBuffer

\n
\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst view = new Uint8Array(buffer);\nview[1] = 2;\nview[7] = 4;\n\n// Copy the buffer to a smaller size\nconst buffer2 = buffer.transfer(4);\nconsole.log(buffer2.byteLength); // 4\nconsole.log(buffer2.maxByteLength); // 16\nconst view2 = new Uint8Array(buffer2);\nconsole.log(view2[1]); // 2\nconsole.log(view2[7]); // undefined\nbuffer2.resize(8);\nconsole.log(view2[7]); // 0\n\n// Copy the buffer to a larger size within maxByteLength\nconst buffer3 = buffer2.transfer(12);\nconsole.log(buffer3.byteLength); // 12\n\n// Copy the buffer to a larger size than maxByteLength\nbuffer3.transfer(20); // RangeError: Invalid array buffer length\n
\n

Specifications

\n
\n\n\n
Specification
ArrayBuffer transfer
# sec-arraybuffer.prototype.transfer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
transfer114114previewNo100No114114NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transfer\n

\n
\n", + "global_objects/arraybuffer/transfertofixedlength": "

ArrayBuffer.prototype.transferToFixedLength()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The transferToFixedLength() method of ArrayBuffer instances creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

\n
\n

Syntax

\n
\n

js

\n
transferToFixedLength()\ntransferToFixedLength(newByteLength)\n
\n

Parameters

\n
newByteLength

The byteLength of the new ArrayBuffer. Defaults to the byteLength of this ArrayBuffer.

  • If newByteLength is smaller than the byteLength of this ArrayBuffer, the \"overflowing\" bytes are dropped.
  • If newByteLength is larger than the byteLength of this ArrayBuffer, the extra bytes are filled with zeros.

Return value

\n

A new ArrayBuffer object. Its contents are initialized to the contents of this ArrayBuffer, and extra bytes, if any, are filled with zeros. The new ArrayBuffer is always non-resizable. The original ArrayBuffer is detached.

Exceptions

\n
TypeError

Thrown if this ArrayBuffer is already detached.

Description

\n

Unlike transfer(), transferToFixedLength() always creates a non-resizable ArrayBuffer. This means newByteLength can be larger than the maxByteLength, even if this ArrayBuffer is resizable. See transferring ArrayBuffers for more information.

Examples

\n

Transferring a resizable ArrayBuffer to fixed-length

\n
\n
\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst view = new Uint8Array(buffer);\nview[1] = 2;\nview[7] = 4;\n\nconst buffer2 = buffer.transferToFixedLength();\nconsole.log(buffer2.byteLength); // 8\nconsole.log(buffer2.resizable); // false\nconst view2 = new Uint8Array(buffer2);\nconsole.log(view2[1]); // 2\nconsole.log(view2[7]); // 4\n
\n

Using transferToFixedLength, newByteLength can be larger than the maxByteLength of the original ArrayBuffer.

\n

js

\n
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });\nconst view = new Uint8Array(buffer);\nview[1] = 2;\nview[7] = 4;\n\nconst buffer2 = buffer.transferToFixedLength(20);\nconsole.log(buffer2.byteLength); // 20\nconsole.log(buffer2.resizable); // false\nconst view2 = new Uint8Array(buffer2);\nconsole.log(view2[1]); // 2\nconsole.log(view2[7]); // 4\n
\n
\n

Specifications

\n
\n\n\n
Specification
ArrayBuffer transfer
# sec-arraybuffer.prototype.transfertofixedlength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
transferToFixedLength114114previewNo100No114114NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transferToFixedLength\n

\n
\n", + "global_objects/arraybuffer/bytelength": "

ArrayBuffer.prototype.byteLength

The byteLength accessor property of ArrayBuffer instances returns the length (in bytes) of this array buffer.

\n

Try it

\n

Description

\n

The byteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this ArrayBuffer has been detached.

Examples

\n

Using byteLength

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nbuffer.byteLength; // 8\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-arraybuffer.prototype.bytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteLength71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength\n

\n
\n", + "global_objects/arraybuffer/slice": "

ArrayBuffer.prototype.slice()

The slice() method of ArrayBuffer instances returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin, inclusive, up to end, exclusive.

\n

Try it

\n

Syntax

\n
\n

js

\n
slice()\nslice(start)\nslice(start, end)\n
\n

Parameters

\n
\nstart Optional\n

Zero-based index at which to start extraction, converted to an integer.

  • Negative index counts back from the end of the buffer — if start < 0, start + buffer.length is used.
  • If start < -buffer.length or start is omitted, 0 is used.
  • If start >= buffer.length, nothing is extracted.
\nend Optional\n

Zero-based index at which to end extraction, converted to an integer. slice() extracts up to but not including end.

  • Negative index counts back from the end of the buffer — if end < 0, end + buffer.length is used.
  • If end < -buffer.length, 0 is used.
  • If end >= buffer.length or end is omitted, buffer.length is used, causing all elements until the end to be extracted.
  • If end is positioned before or at start after normalization, nothing is extracted.

Return value

\n

A new ArrayBuffer object.

Examples

\n

Copying an ArrayBuffer

\n
\n

js

\n
const buf1 = new ArrayBuffer(8);\nconst buf2 = buf1.slice(0);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arraybuffer.prototype.slice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
slice1712
12The non-standard ArrayBuffer.slice() method has been removed in Firefox 53 (but the standardized version ArrayBuffer.prototype.slice() is kept.
1112.15.14.418
14The non-standard ArrayBuffer.slice() method has been removed in Firefox 53 (but the standardized version ArrayBuffer.prototype.slice() is kept.
12.161.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice\n

\n
\n", + "global_objects/arraybuffer/detached": "

ArrayBuffer.prototype.detached

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The detached accessor property of ArrayBuffer instances returns a boolean indicating whether or not this buffer has been detached (transferred).

\n
\n

Description

\n

The detached property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is false when the ArrayBuffer is first created. The value becomes true if the ArrayBuffer is transferred, which detaches the instance from its underlying memory. Once a buffer becomes detached, it is no longer usable.

Examples

\n

Using detached

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconsole.log(buffer.detached); // false\nconst newBuffer = buffer.transfer();\nconsole.log(buffer.detached); // true\nconsole.log(newBuffer.detached); // false\n
\n

Specifications

\n
\n\n\n
Specification
ArrayBuffer transfer
# sec-get-arraybuffer.prototype.detached
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
detached114114previewNo100No114114NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/detached\n

\n
\n", + "global_objects/arraybuffer/@@species": "

ArrayBuffer[@@species]

\n

The ArrayBuffer[@@species] static accessor property returns the constructor used to construct return values from array buffer methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Syntax

\n
\n

js

\n
ArrayBuffer[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct return values from array buffer methods that create new array buffers.

Description

\n
\n

The @@species accessor property returns the default constructor for ArrayBuffer objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass ArrayBuffer {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubArrayBuffer extends ArrayBuffer {}\nSubArrayBuffer[Symbol.species] === SubArrayBuffer; // true\n
\n

When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, slice()), the object's constructor[@@species] will be accessed. The returned constructor will be used to construct the return value of the array buffer method.

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the ArrayBuffer constructor for ArrayBuffer.

\n

js

\n
ArrayBuffer[Symbol.species]; // function ArrayBuffer()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom ArrayBuffer subclass, such as MyArrayBuffer, the MyArrayBuffer species is the MyArrayBuffer constructor. However, you might want to overwrite this, in order to return parent ArrayBuffer objects in your derived class methods:

\n

js

\n
class MyArrayBuffer extends ArrayBuffer {\n  // Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor\n  static get [Symbol.species]() {\n    return ArrayBuffer;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-arraybuffer-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species511348No381051514841105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/@@species\n

\n
\n", + "global_objects/arraybuffer/isview": "

ArrayBuffer.isView()

The ArrayBuffer.isView() static method determines whether the passed value is one of the ArrayBuffer views, such as typed array objects or a DataView.

\n

Try it

\n

Syntax

\n
\n

js

\n
ArrayBuffer.isView(value)\n
\n

Parameters

\n
value

The value to be checked.

Return value

\n

true if the given argument is one of the ArrayBuffer views; otherwise, false.

Examples

\n

Using isView

\n
\n

js

\n
ArrayBuffer.isView(); // false\nArrayBuffer.isView([]); // false\nArrayBuffer.isView({}); // false\nArrayBuffer.isView(null); // false\nArrayBuffer.isView(undefined); // false\nArrayBuffer.isView(new ArrayBuffer(10)); // false\n\nArrayBuffer.isView(new Uint8Array()); // true\nArrayBuffer.isView(new Float32Array()); // true\nArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true\n\nconst buffer = new ArrayBuffer(2);\nconst dv = new DataView(buffer);\nArrayBuffer.isView(dv); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arraybuffer.isview
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isView321229111974.4.332291972.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView\n

\n
\n", + "errors/invalid_array_length": "

RangeError: invalid array length

\n

The JavaScript exception \"Invalid array length\" occurs when specifying an array length that is either negative, a floating number or exceeds the maximum supported by the platform (i.e. when creating an Array or ArrayBuffer, or when setting the length property).

The maximum allowed array length depends on the platform, browser and browser version. For Array the maximum length is 232-1. For ArrayBuffer the maximum is 231-1 (2GiB-1) on 32-bit systems. From Firefox version 89 the maximum value of ArrayBuffer is 233 (8GiB) on 64-bit systems.

Note: Array and ArrayBuffer are independent data structures (the implementation of one does not affect the other).

\n
\n

Message

\n
RangeError: invalid array length (V8-based & Firefox)\nRangeError: Array buffer allocation failed (V8-based)\nRangeError: Array size is not a small enough positive integer. (Safari)\n

Error type

\n
RangeError

What went wrong?

\n
\n

An invalid array length might appear in these situations:

If you are creating an Array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the Array.

Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.

\n

Examples

\n

Invalid cases

\n
\n

js

\n
new Array(Math.pow(2, 40));\nnew Array(-1);\nnew ArrayBuffer(Math.pow(2, 32)); // 32-bit system\nnew ArrayBuffer(-1);\n\nconst a = [];\na.length = a.length - 1; // set the length property to -1\n\nconst b = new Array(Math.pow(2, 32) - 1);\nb.length = b.length + 1; // set the length property to 2^32\nb.length = 2.5; // set the length property to a floating-point number\n\nconst c = new Array(2.5); // pass a floating-point number\n
\n

Valid cases

\n
\n

js

\n
[Math.pow(2, 40)]; // [ 1099511627776 ]\n[-1]; // [ -1 ]\nnew ArrayBuffer(Math.pow(2, 31) - 1);\nnew ArrayBuffer(Math.pow(2, 33)); // 64-bit systems after Firefox 89\nnew ArrayBuffer(0);\n\nconst a = [];\na.length = Math.max(0, a.length - 1);\n\nconst b = new Array(Math.pow(2, 32) - 1);\nb.length = Math.min(0xffffffff, b.length + 1);\n// 0xffffffff is the hexadecimal notation for 2^32 - 1\n// which can also be written as (-1 >>> 0)\n\nb.length = 3;\n\nconst c = new Array(3);\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length\n

\n
\n", + "global_objects/sharedarraybuffer/sharedarraybuffer": "

SharedArrayBuffer() constructor

\n

Note: The SharedArrayBuffer constructor may not always be globally available unless certain security requirements are met.

The SharedArrayBuffer() constructor creates SharedArrayBuffer objects.

\n
\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new SharedArrayBuffer(length)\nnew SharedArrayBuffer(length, options)\n
\n

Note: SharedArrayBuffer() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
length

The size, in bytes, of the array buffer to create.

\noptions Optional\n

An object, which can contain the following properties:

\nmaxByteLength Optional\n

The maximum size, in bytes, that the shared array buffer can be resized to.

Return value

\n

A new SharedArrayBuffer object of the specified size, with its maxByteLength property set to the specified maxByteLength if one was specified. Its contents are initialized to 0.

Examples

\n

Always use the new operator to create a SharedArrayBuffer

\n
\n

SharedArrayBuffer constructors are required to be constructed with a new operator. Calling a SharedArrayBuffer constructor as a function without new will throw a TypeError.

\n

js

\n
const sab = SharedArrayBuffer(1024);\n// TypeError: calling a builtin SharedArrayBuffer constructor\n// without new is forbidden\n
\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\n
\n
\n

Growing a growable SharedArrayBuffer

\n
\n

In this example, we create an 8-byte buffer that is growable to a max length of 16 bytes, then grow() it to 12 bytes:

\n

js

\n
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });\n\nbuffer.grow(12);\n
\n

Note: It is recommended that maxByteLength is set to the smallest value possible for your use case. It should never exceed 1073741824 (1GB), to reduce the risk of out-of-memory errors.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-sharedarraybuffer-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
SharedArrayBuffer687979No5515.2No89796315.215.01.08.10.0
maxByteLength_option111111NoNo9716.4No111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n

\n
\n", + "global_objects/sharedarraybuffer/growable": "

SharedArrayBuffer.prototype.growable

The growable accessor property of SharedArrayBuffer instances returns whether this SharedArrayBuffer can be grow or not.

\n

Description

\n

The growable property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the array is constructed. If a maxByteLength option was set in the constructor, growable will return true; if not, it will return false.

Examples

\n

Using growable

\n
\n

In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its growable property, growing it if growable returns true:

\n

js

\n
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });\n\nif (buffer.growable) {\n  console.log(\"SAB is growable!\");\n  buffer.grow(12);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-sharedarraybuffer.prototype.growable
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
growable111111NoNo9716.4No111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/growable\n

\n
\n", + "global_objects/sharedarraybuffer/maxbytelength": "

SharedArrayBuffer.prototype.maxByteLength

The maxByteLength accessor property of SharedArrayBuffer instances returns the maximum length (in bytes) that this SharedArrayBuffer can be grown to.

\n

Description

\n
\n

The maxByteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the shared array is constructed, set via the maxByteLength option of the SharedArrayBuffer() constructor, and cannot be changed.

If this SharedArrayBuffer was constructed without specifying a maxByteLength value, this property returns a value equal to the value of the SharedArrayBuffer's byteLength.

\n

Examples

\n

Using maxByteLength

\n
\n

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then return its maxByteLength:

\n

js

\n
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });\n\nbuffer.maxByteLength; // 16\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-sharedarraybuffer.prototype.maxbytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
maxByteLength111111NoNo9716.4No111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/maxByteLength\n

\n
\n", + "global_objects/sharedarraybuffer/grow": "

SharedArrayBuffer.prototype.grow()

The grow() method of SharedArrayBuffer instances grows the SharedArrayBuffer to the specified size, in bytes.

\n

Syntax

\n
\n

js

\n
grow(newLength)\n
\n

Parameters

\n
newLength

The new length, in bytes, to resize the SharedArrayBuffer to.

Return value

\n

None (undefined).

Exceptions

\n
TypeError

Thrown if the SharedArrayBuffer is not growable.

RangeError

Thrown if newLength is larger than the maxByteLength of the SharedArrayBuffer or smaller than the byteLength.

Description

\n

The grow() method grows a SharedArrayBuffer to the size specified by the newLength parameter, provided that the SharedArrayBuffer is resizable and the new size is less than or equal to the maxByteLength of the SharedArrayBuffer. New bytes are initialized to 0.

Examples

\n

Using grow()

\n
\n

In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its growable property, growing it if growable returns true:

\n

js

\n
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });\n\nif (buffer.growable) {\n  console.log(\"SAB is growable!\");\n  buffer.grow(12);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-sharedarraybuffer.prototype.grow
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
grow111111NoNo9716.4No111NoNo16.422.01.3320.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/grow\n

\n
\n", + "global_objects/sharedarraybuffer/@@species": "

SharedArrayBuffer[@@species]

\n

The SharedArrayBuffer[@@species] static accessor property returns the constructor used to construct return values from SharedArrayBuffer methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Syntax

\n
\n

js

\n
SharedArrayBuffer[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct return values from array buffer methods that create new array buffer.

Description

\n
\n

The @@species accessor property returns the default constructor for SharedArrayBuffer objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass SharedArrayBuffer {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubArrayBuffer extends SharedArrayBuffer {}\nSubArrayBuffer[Symbol.species] === SharedArrayBuffer; // true\n
\n

When calling array buffer methods that do not mutate the existing array but return a new array buffer instance (for example, slice()), the array's constructor[@@species] will be accessed. The returned constructor will be used to construct the return value of the array buffer method.

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is the SharedArrayBuffer constructor for SharedArrayBuffer.

\n

js

\n
SharedArrayBuffer[Symbol.species]; // function SharedArrayBuffer()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom SharedArrayBuffer subclass, such as MySharedArrayBuffer, the MySharedArrayBuffer species is the MySharedArrayBuffer constructor. However, you might want to overwrite this, in order to return parent SharedArrayBuffer objects in your derived class methods:

\n

js

\n
class MySharedArrayBuffer extends SharedArrayBuffer {\n  // Overwrite MySharedArrayBuffer species to the parent SharedArrayBuffer constructor\n  static get [Symbol.species]() {\n    return SharedArrayBuffer;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-sharedarraybuffer-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species687979No5515.2No89796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/@@species\n

\n
\n", + "global_objects/sharedarraybuffer/bytelength": "

SharedArrayBuffer.prototype.byteLength

The byteLength accessor property of SharedArrayBuffer instances returns the length (in bytes) of this SharedArrayBuffer.

\n

Try it

\n

Description

\n

The byteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the shared array is constructed and cannot be changed.

Examples

\n

Using byteLength

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nsab.byteLength; // 1024\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-sharedarraybuffer.prototype.bytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteLength687979No5515.2No89796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/byteLength\n

\n
\n", + "global_objects/sharedarraybuffer/slice": "

SharedArrayBuffer.prototype.slice()

The slice() method of SharedArrayBuffer instances returns a new SharedArrayBuffer whose contents are a copy of this SharedArrayBuffer's bytes from begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. This method has the same algorithm as Array.prototype.slice().

\n

Try it

\n

Syntax

\n
\n

js

\n
slice()\nslice(begin)\nslice(begin, end)\n
\n

Parameters

\n
\nbegin Optional\n

Zero-based index at which to begin extraction.

A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

If begin is undefined, slice begins from index 0.

\nend Optional\n

Zero-based index before which to end extraction. slice extracts up to but not including end.

For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

If end is omitted, slice extracts through the end of the sequence (sab.byteLength).

Return value

\n

A new SharedArrayBuffer containing the extracted elements.

Examples

\n

Using slice()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nsab.slice(); // SharedArrayBuffer { byteLength: 1024 }\nsab.slice(2); // SharedArrayBuffer { byteLength: 1022 }\nsab.slice(-2); // SharedArrayBuffer { byteLength: 2 }\nsab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 }\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-sharedarraybuffer.prototype.slice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
slice687979No5515.2No89796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/slice\n

\n
\n", + "global_objects/dataview/setbigint64": "

DataView.prototype.setBigInt64()

The setBigInt64() method of DataView instances takes a BigInt and stores it as a 64-bit signed integer in the 8 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setBigInt64(byteOffset, value)\nsetBigInt64(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set as a BigInt. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setBigInt64()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setBigInt64(0, 3n);\ndataview.getBigInt64(1); // 768n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setbigint64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setBigInt64677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setBigInt64\n

\n
\n", + "global_objects/dataview/setbiguint64": "

DataView.prototype.setBigUint64()

The setBigUint64() method of DataView instances takes a BigInt and stores it as a 64-bit unsigned integer in the 8 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setBigUint64(byteOffset, value)\nsetBigUint64(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set as a BigInt. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setBigUint64()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setBigUint64(0, 3n);\ndataview.getBigUint64(1); // 768n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setbiguint64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setBigUint64677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setBigUint64\n

\n
\n", + "global_objects/dataview/dataview": "

DataView() constructor

The DataView() constructor creates DataView objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new DataView(buffer)\nnew DataView(buffer, byteOffset)\nnew DataView(buffer, byteOffset, byteLength)\n
\n

Note: DataView() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
buffer

An existing ArrayBuffer or SharedArrayBuffer to use as the storage backing the new DataView object.

\nbyteOffset Optional\n

The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte.

\nbyteLength Optional\n

The number of elements in the byte array. If unspecified, the view's length will match the buffer's length.

Return value

\n

A new DataView object representing the specified data buffer.

Exceptions

\n
RangeError

Thrown if the byteOffset or byteLength parameter values result in the view extending past the end of the buffer. In other words, byteOffset + byteLength > buffer.byteLength.

Examples

\n

Using DataView

\n
\n

js

\n
const buffer = new ArrayBuffer(16);\nconst view = new DataView(buffer, 0);\n\nview.setInt16(1, 42);\nview.getInt16(1); // 42\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DataView912151012.15.14181512.151.01.00.10.0
new_required111340No155.1≤3718401451.01.00.10.0
sharedarraybuffer_support687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/DataView\n

\n
\n", + "global_objects/dataview/buffer": "

DataView.prototype.buffer

The buffer accessor property of DataView instances returns the ArrayBuffer or SharedArrayBuffer referenced by this view at construction time.

\n

Try it

\n

Description

\n

The buffer property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the DataView is constructed and cannot be changed.

Examples

\n

Using the buffer property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst dataview = new DataView(buffer);\ndataview.buffer; // ArrayBuffer { byteLength: 8 }\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-dataview.prototype.buffer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
buffer912151012.15.14181512.151.01.00.10.0
sharedarraybuffer_support607979No4710.1–11.16060794410.3–11.38.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/buffer\n

\n
\n", + "global_objects/dataview/bytelength": "

DataView.prototype.byteLength

The byteLength accessor property of DataView instances returns the length (in bytes) of this view.

\n

Try it

\n

Description

\n

The byteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when an DataView is constructed and cannot be changed. If the DataView is not specifying an offset or a byteLength, the byteLength of the referenced ArrayBuffer or SharedArrayBuffer will be returned.

Examples

\n

Using the byteLength property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst dataview = new DataView(buffer);\ndataview.byteLength; // 8 (matches the byteLength of the buffer)\n\nconst dataview2 = new DataView(buffer, 1, 5);\ndataview2.byteLength; // 5 (as specified when constructing the DataView)\n\nconst dataview3 = new DataView(buffer, 2);\ndataview3.byteLength; // 6 (due to the offset of the constructed DataView)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-dataview.prototype.bytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteLength912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/byteLength\n

\n
\n", + "global_objects/dataview/byteoffset": "

DataView.prototype.byteOffset

The byteOffset accessor property of DataView instances returns the offset (in bytes) of this view from the start of its ArrayBuffer or SharedArrayBuffer.

\n

Try it

\n

Description

\n

The byteOffset property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when an DataView is constructed and cannot be changed.

Examples

\n

Using the byteOffset property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst dataview = new DataView(buffer);\ndataview.byteOffset; // 0 (no offset specified)\n\nconst dataview2 = new DataView(buffer, 3);\ndataview2.byteOffset; // 3 (as specified when constructing the DataView)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-dataview.prototype.byteoffset
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteOffset912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/byteOffset\n

\n
\n", + "global_objects/dataview/getbigint64": "

DataView.prototype.getBigInt64()

The getBigInt64() method of DataView instances reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getBigInt64(byteOffset)\ngetBigInt64(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

A BigInt from -263 to 263-1, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getBigInt64()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getBigInt64(1)); // 72623859790382856n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getbigint64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getBigInt64677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getBigInt64\n

\n
\n", + "global_objects/dataview/getbiguint64": "

DataView.prototype.getBigUint64()

The getBigUint64() method of DataView instances reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getBigUint64(byteOffset)\ngetBigUint64(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

A BigInt from 0 to 264-1, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getBigUint64()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getBigUint64(1)); // 72623859790382856n\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getbiguint64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getBigUint64677968No541567676848159.01.010.4.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getBigUint64\n

\n
\n", + "global_objects/dataview/getfloat32": "

DataView.prototype.getFloat32()

The getFloat32() method of DataView instances reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getFloat32(byteOffset)\ngetFloat32(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

A floating point number from -3.4e38 to 3.4e38.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getFloat32()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getFloat32(1)); // 2.387939260590663e-38\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getfloat32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getFloat32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getFloat32\n

\n
\n", + "global_objects/dataview/getfloat64": "

DataView.prototype.getFloat64()

The getFloat64() method of DataView instances reads 8 bytes starting at the specified byte offset of this DataView and interprets them as a 64-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getFloat64(byteOffset)\ngetFloat64(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

Any number value.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getFloat64()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getFloat64(1)); // 8.20788039913184e-304\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getfloat64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getFloat64912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getFloat64\n

\n
\n", + "global_objects/dataview/getint16": "

DataView.prototype.getInt16()

The getInt16() method of DataView instances reads 2 bytes starting at the specified byte offset of this DataView and interprets them as a 16-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getInt16(byteOffset)\ngetInt16(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

An integer from -32768 to 32767, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getInt16()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getInt16(1)); // 258\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getint16
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getInt16912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getInt16\n

\n
\n", + "global_objects/dataview/getint32": "

DataView.prototype.getInt32()

The getInt32() method of DataView instances reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getInt32(byteOffset)\ngetInt32(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

An integer from -2147483648 to 2147483647, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getInt32()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getInt32(1)); // 16909060\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getint32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getInt32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getInt32\n

\n
\n", + "global_objects/dataview/getint8": "

DataView.prototype.getInt8()

The getInt8() method of DataView instances reads 1 byte at the specified byte offset of this DataView and interprets it as an 8-bit signed integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
getInt8(byteOffset)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

Return value

\n

An integer from -128 to 127, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getInt8()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getInt8(1)); // 1\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getint8
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getInt8912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getInt8\n

\n
\n", + "global_objects/dataview/getuint16": "

DataView.prototype.getUint16()

The getUint16() method of DataView instances reads 2 bytes starting at the specified byte offset of this DataView and interprets them as a 16-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUint16(byteOffset)\ngetUint16(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

An integer from 0 to 65535, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getUint16()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getUint16(1)); // 258\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getuint16
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUint16912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getUint16\n

\n
\n", + "global_objects/dataview/getuint32": "

DataView.prototype.getUint32()

The getUint32() method of DataView instances reads 4 bytes starting at the specified byte offset of this DataView and interprets them as a 32-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUint32(byteOffset)\ngetUint32(byteOffset, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is read.

Return value

\n

An integer from 0 to 4294967295, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getUint32()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getUint32(1)); // 16909060\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getuint32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUint32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getUint32\n

\n
\n", + "global_objects/dataview/getuint8": "

DataView.prototype.getUint8()

The getUint8() method of DataView instances reads 1 byte at the specified byte offset of this DataView and interprets it as an 8-bit unsigned integer.

\n

Try it

\n

Syntax

\n
\n

js

\n
getUint8(byteOffset)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to read the data from.

Return value

\n

An integer from 0 to 255, inclusive.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would read beyond the end of the view.

Examples

\n

Using getUint8()

\n
\n

js

\n
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst dataview = new DataView(buffer);\nconsole.log(dataview.getUint8(1)); // 1\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.getuint8
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getUint8912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getUint8\n

\n
\n", + "global_objects/dataview/setfloat32": "

DataView.prototype.setFloat32()

The setFloat32() method of DataView instances takes a number and stores it as a 32-bit floating point number in the 4 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setFloat32(byteOffset, value)\nsetFloat32(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setFloat32()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setFloat32(0, 3);\ndataview.getFloat32(1); // 2\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setfloat32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setFloat32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setFloat32\n

\n
\n", + "global_objects/dataview/setfloat64": "

DataView.prototype.setFloat64()

The setFloat64() method of DataView instances takes a number and stores it as a 64-bit floating point number in the 8 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setFloat64(byteOffset, value)\nsetFloat64(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setFloat64()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setFloat64(0, 3);\ndataview.getFloat64(1); // 3.785766995733679e-270\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setfloat64
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setFloat64912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setFloat64\n

\n
\n", + "global_objects/dataview/setint16": "

DataView.prototype.setInt16()

The setInt16() method of DataView instances takes a number and stores it as a 16-bit signed integer in the 2 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setInt16(byteOffset, value)\nsetInt16(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setInt16()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setInt16(0, 3);\ndataview.getInt16(1); // 768\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setint16
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setInt16912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setInt16\n

\n
\n", + "global_objects/dataview/setint32": "

DataView.prototype.setInt32()

The setInt32() method of DataView instances takes a number and stores it as a 32-bit signed integer in the 4 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setInt32(byteOffset, value)\nsetInt32(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setInt32()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setInt32(0, 3);\ndataview.getInt32(1); // 768\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setint32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setInt32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setInt32\n

\n
\n", + "global_objects/dataview/setint8": "

DataView.prototype.setInt8()

The setInt8() method of DataView instances takes a number and stores it as an 8-bit signed integer in the byte at the specified byte offset of this DataView.

\n

Try it

\n

Syntax

\n
\n

js

\n
setInt8(byteOffset, value)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setInt8()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setInt8(0, 3);\ndataview.getInt8(0); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setint8
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setInt8912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setInt8\n

\n
\n", + "global_objects/dataview/setuint16": "

DataView.prototype.setUint16()

The setUint16() method of DataView instances takes a number and stores it as a 16-bit unsigned integer in the 2 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUint16(byteOffset, value)\nsetUint16(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setUint16()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setUint16(0, 3);\ndataview.getUint16(1); // 768\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setuint16
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUint16912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setUint16\n

\n
\n", + "global_objects/dataview/setuint32": "

DataView.prototype.setUint32()

The setUint32() method of DataView instances takes a number and stores it as a 32-bit unsigned integer in the 4 bytes starting at the specified byte offset of this DataView. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUint32(byteOffset, value)\nsetUint32(byteOffset, value, littleEndian)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

\nlittleEndian Optional\n

Indicates whether the data is stored in little- or big-endian format. If false or undefined, a big-endian value is written.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setUint32()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setUint32(0, 3);\ndataview.getUint32(1); // 768\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setuint32
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUint32912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setUint32\n

\n
\n", + "global_objects/dataview/setuint8": "

DataView.prototype.setUint8()

The setUint8() method of DataView instances takes a number and stores it as an 8-bit unsigned integer in the byte at the specified byte offset of this DataView.

\n

Try it

\n

Syntax

\n
\n

js

\n
setUint8(byteOffset, value)\n
\n

Parameters

\n
byteOffset

The offset, in bytes, from the start of the view to store the data in.

value

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

Return value

\n

undefined.

Exceptions

\n
RangeError

Thrown if the byteOffset is set such that it would store beyond the end of the view.

Examples

\n

Using setUint8()

\n
\n

js

\n
const buffer = new ArrayBuffer(10);\nconst dataview = new DataView(buffer);\ndataview.setUint8(0, 3);\ndataview.getUint8(0); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-dataview.prototype.setuint8
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setUint8912151012.15.14181512.151.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setUint8\n

\n
\n", + "global_objects/atomics/add": "

Atomics.add()

The Atomics.add() static method adds a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.add(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to add a value to.

value

The number to add.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using add()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\n\nAtomics.add(ta, 0, 12); // returns 0, the old value\nAtomics.load(ta, 0); // 12\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.add
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
add687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/add\n

\n
\n", + "global_objects/atomics/and": "

Atomics.and()

The Atomics.and() static method computes a bitwise AND with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.and(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to compute the bitwise AND.

value

The number to compute the bitwise AND with.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Description

\n
\n

The bitwise AND operation only yields 1, if both a and b are 1. The truth table for the AND operation is:

a b a & b
0 0 0
0 1 0
1 0 0
1 1 1

For example, a bitwise AND of 5 & 1 results in 0001 which is 1 in decimal.

5  0101\n1  0001\n   ----\n1  0001\n
\n

Examples

\n

Using and()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\nta[0] = 5;\n\nAtomics.and(ta, 0, 1); // returns 5, the old value\nAtomics.load(ta, 0); // 1\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.and
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
and687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/and\n

\n
\n", + "global_objects/atomics/compareexchange": "

Atomics.compareExchange()

The Atomics.compareExchange() static method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value. It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to exchange a value.

expectedValue

The value to check for equality.

replacementValue

The number to exchange.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using compareExchange()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\nta[0] = 7;\n\nAtomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value\nAtomics.load(ta, 0); // 12\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.compareexchange
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
compareExchange687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/compareExchange\n

\n
\n", + "global_objects/atomics/exchange": "

Atomics.exchange()

The Atomics.exchange() static method stores a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens between the read of the old value and the write of the new value.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.exchange(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to exchange a value.

value

The number to exchange.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using exchange()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\n\nAtomics.exchange(ta, 0, 12); // returns 0, the old value\nAtomics.load(ta, 0); // 12\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.exchange
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
exchange687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/exchange\n

\n
\n", + "global_objects/atomics/islockfree": "

Atomics.isLockFree()

The Atomics.isLockFree() static method is used to determine whether the Atomics methods use locks or atomic hardware operations when applied to typed arrays with the given element byte size. It returns false if the given size is not one of the BYTES_PER_ELEMENT property of integer TypedArray types.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.isLockFree(size)\n
\n

Parameters

\n
size

The size in bytes to check.

Return value

\n

A true or false value indicating whether the operation is lock free.

Examples

\n

Using isLockFree

\n
\n

js

\n
Atomics.isLockFree(1); // true\nAtomics.isLockFree(2); // true\nAtomics.isLockFree(3); // false\nAtomics.isLockFree(4); // true\nAtomics.isLockFree(5); // false\nAtomics.isLockFree(6); // false\nAtomics.isLockFree(7); // false\nAtomics.isLockFree(8); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.islockfree
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isLockFree687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/isLockFree\n

\n
\n", + "global_objects/atomics/load": "

Atomics.load()

The Atomics.load() static method returns a value at a given position in the array.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.load(typedArray, index)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to load from.

Return value

\n

The value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using load\n

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\n\nAtomics.add(ta, 0, 12);\nAtomics.load(ta, 0); // 12\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.load
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
load687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/load\n

\n
\n", + "global_objects/atomics/notify": "

Atomics.notify()

\n

The Atomics.notify() static method notifies up some agents that are sleeping in the wait queue.

Note: This operation only works with an Int32Array or BigInt64Array that views a SharedArrayBuffer. It will return 0 on non-shared ArrayBuffer objects.

\n
\n

Syntax

\n
\n

js

\n
Atomics.notify(typedArray, index, count)\n
\n

Parameters

\n
typedArray

An Int32Array or BigInt64Array that views a SharedArrayBuffer.

index

The position in the typedArray to wake up on.

\ncount Optional\n

The number of sleeping agents to notify. Defaults to Infinity.

Return value

\n

Exceptions

\n
TypeError

Thrown if typedArray is not an Int32Array or BigInt64Array that views a SharedArrayBuffer.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using notify\n

\n
\n

Given a shared Int32Array:

\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst int32 = new Int32Array(sab);\n
\n

A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).

\n

js

\n
Atomics.wait(int32, 0, 0);\nconsole.log(int32[0]); // 123\n
\n

A writing thread stores a new value and notifies the waiting thread once it has written:

\n

js

\n
console.log(int32[0]); // 0;\nAtomics.store(int32, 0, 123);\nAtomics.notify(int32, 0, 1);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.notify
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
notify687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/notify\n

\n
\n", + "global_objects/atomics/or": "

Atomics.or()

The Atomics.or() static method computes a bitwise OR with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.or(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to compute the bitwise OR.

value

The number to compute the bitwise OR with.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Description

\n
\n

The bitwise OR operation yields 1, if either a or b are 1. The truth table for the OR operation is:

a b a | b
0 0 0
0 1 1
1 0 1
1 1 1

For example, a bitwise OR of 5 | 1 results in 0101 which is 5 in decimal.

5  0101\n1  0001\n   ----\n5  0101\n
\n

Examples

\n

Using or

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\nta[0] = 2;\n\nAtomics.or(ta, 0, 1); // returns 2, the old value\nAtomics.load(ta, 0); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.or
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
or687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/or\n

\n
\n", + "global_objects/atomics/store": "

Atomics.store()

The Atomics.store() static method stores a given value at the given position in the array and returns that value.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.store(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to store a value in.

value

The number to store.

Return value

\n

The value that has been stored.

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using store()

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\n\nAtomics.store(ta, 0, 12); // 12\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.store
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
store687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/store\n

\n
\n", + "global_objects/atomics/sub": "

Atomics.sub()

The Atomics.sub() static method subtracts a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.sub(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to subtract a value from.

value

The number to subtract.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using sub

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\nta[0] = 48;\n\nAtomics.sub(ta, 0, 12); // returns 48, the old value\nAtomics.load(ta, 0); // 36\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.sub
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sub687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/sub\n

\n
\n", + "global_objects/atomics/wait": "

Atomics.wait()

\n

The Atomics.wait() static method verifies that a shared memory location still contains a given value and if so sleeps, awaiting a wake-up notification or times out. It returns a string which is either \"ok\", \"not-equal\", or \"timed-out\".

Note: This operation only works with an Int32Array or BigInt64Array that views a SharedArrayBuffer, and may not be allowed on the main thread. For a non-blocking, asynchronous version of this method, see Atomics.waitAsync().

\n
\n

Syntax

\n
\n

js

\n
Atomics.wait(typedArray, index, value)\nAtomics.wait(typedArray, index, value, timeout)\n
\n

Parameters

\n
typedArray

An Int32Array or BigInt64Array that views a SharedArrayBuffer.

index

The position in the typedArray to wait on.

value

The expected value to test.

\ntimeout Optional\n

Time to wait in milliseconds. NaN (and values that get converted to NaN, such as undefined) becomes Infinity. Negative values become 0.

Return value

\n

A string which is either \"ok\", \"not-equal\", or \"timed-out\".

Exceptions

\n
TypeError

Thrown in one of the following cases:

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using wait()

\n
\n

Given a shared Int32Array:

\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst int32 = new Int32Array(sab);\n
\n

A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).

\n

js

\n
Atomics.wait(int32, 0, 0);\nconsole.log(int32[0]); // 123\n
\n

A writing thread stores a new value and notifies the waiting thread once it has written:

\n

js

\n
console.log(int32[0]); // 0;\nAtomics.store(int32, 0, 123);\nAtomics.notify(int32, 0, 1);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.wait
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
wait687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wait\n

\n
\n", + "global_objects/atomics/waitasync": "

Atomics.waitAsync()

\n

The Atomics.waitAsync() static method waits asynchronously on a shared memory location and returns a Promise.

Unlike Atomics.wait(), waitAsync is non-blocking and usable on the main thread.

Note: This operation only works with an Int32Array or BigInt64Array that views a SharedArrayBuffer.

\n
\n

Syntax

\n
\n

js

\n
Atomics.waitAsync(typedArray, index, value)\nAtomics.waitAsync(typedArray, index, value, timeout)\n
\n

Parameters

\n
typedArray

An Int32Array or BigInt64Array that views a SharedArrayBuffer.

index

The position in the typedArray to wait on.

value

The expected value to test.

\ntimeout Optional\n

Time to wait in milliseconds. NaN (and values that get converted to NaN, such as undefined) becomes Infinity. Negative values become 0.

Return value

\n
\n

An Object with the following properties:

async

A boolean indicating whether the value property is a Promise or not.

value

If async is false, it will be a string which is either \"not-equal\" or \"timed-out\" (only when the timeout parameter is 0). If async is true, it will be a Promise which is fulfilled with a string value, either \"ok\" or \"timed-out\". The promise is never rejected.

\n

Exceptions

\n
TypeError

Thrown if typedArray is not an Int32Array or BigInt64Array that views a SharedArrayBuffer.

RangeError

Thrown if index is out of bounds in the typedArray.

Examples

\n

Using waitAsync()

\n
\n

Given a shared Int32Array.

\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst int32 = new Int32Array(sab);\n
\n

A reading thread is sleeping and waiting on location 0 which is expected to be 0. The result.value will be a promise.

\n

js

\n
const result = Atomics.waitAsync(int32, 0, 0, 1000);\n// { async: true, value: Promise {<pending>} }\n
\n

In the reading thread or in another thread, the memory location 0 is called and the promise can be resolved with \"ok\".

\n

js

\n
Atomics.notify(int32, 0);\n// { async: true, value: Promise {<fulfilled>: 'ok'} }\n
\n

If it isn't resolving to \"ok\", the value in the shared memory location wasn't the expected (the value would be \"not-equal\" instead of a promise) or the timeout was reached (the promise will resolve to \"time-out\").

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.waitasync
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
waitAsync8787NoNo7516.48989No6316.415.01.416.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/waitAsync\n

\n
\n", + "global_objects/atomics/xor": "

Atomics.xor()

The Atomics.xor() static method computes a bitwise XOR with a given value at a given position in the array, and returns the old value at that position. This atomic operation guarantees that no other write happens until the modified value is written back.

\n

Try it

\n

Syntax

\n
\n

js

\n
Atomics.xor(typedArray, index, value)\n
\n

Parameters

\n
typedArray

An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.

index

The position in the typedArray to compute the bitwise XOR.

value

The number to compute the bitwise XOR with.

Return value

\n

The old value at the given position (typedArray[index]).

Exceptions

\n
TypeError

Thrown if typedArray is not one of the allowed integer types.

RangeError

Thrown if index is out of bounds in the typedArray.

Description

\n
\n

The bitwise XOR operation yields 1, if a and b are different. The truth table for the XOR operation is:

a b a ^ b
0 0 0
0 1 1
1 0 1
1 1 0

For example, a bitwise XOR of 5 ^ 1 results in 0100 which is 4 in decimal.

5  0101\n1  0001\n   ----\n4  0100\n
\n

Examples

\n

Using xor

\n
\n

js

\n
const sab = new SharedArrayBuffer(1024);\nconst ta = new Uint8Array(sab);\nta[0] = 5;\n\nAtomics.xor(ta, 0, 1); // returns 5, the old value\nAtomics.load(ta, 0); // 4\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-atomics.xor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
xor687978No5515.28989796315.215.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/xor\n

\n
\n", + "global_objects/weakref/weakref": "

WeakRef() constructor

The WeakRef() constructor creates WeakRef objects.

\n

Syntax

\n
\n
\n

js

\n
new WeakRef(target)\n
\n

Note: WeakRef() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
target

The target value the WeakRef should refer to (also called the referent). Must be an object or a non-registered symbol.

Return value

\n

A new WeakRef object referring to the given target value.

Exceptions

\n
TypeError

Thrown if target is not an object or a non-registered symbol.

Examples

\n

Creating a new WeakRef object

\n
\n

See the main WeakRef page for a complete example.

\n

js

\n
class Counter {\n  constructor(element) {\n    // Remember a weak reference to a DOM element\n    this.ref = new WeakRef(element);\n    this.start();\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weak-ref-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
WeakRef848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef/WeakRef\n

\n
\n", + "global_objects/weakref/deref": "

WeakRef.prototype.deref()

The deref() method of WeakRef instances returns this WeakRef's target value, or undefined if the target value has been garbage-collected.

\n

Syntax

\n
\n

js

\n
deref()\n
\n

Parameters

\n

None.

Return value

\n

The target value of the WeakRef, which is either an object or a non-registered symbol. Returns undefined if the value has been garbage-collected.

Description

\n

See the Notes on WeakRefs section of the WeakRef page for some important notes.

Examples

\n

Using deref()

\n
\n

See the Examples section of the WeakRef page for the complete example.

\n

js

\n
const tick = () => {\n  // Get the element from the weak reference, if it still exists\n  const element = this.ref.deref();\n  if (element) {\n    element.textContent = ++this.count;\n  } else {\n    // The element doesn't exist anymore\n    console.log(\"The element is gone.\");\n    this.stop();\n    this.ref = null;\n  }\n};\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-weak-ref.prototype.deref
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
deref848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef/deref\n

\n
\n", + "global_objects/finalizationregistry/finalizationregistry": "

FinalizationRegistry() constructor

The FinalizationRegistry() constructor creates FinalizationRegistry objects.

\n

Syntax

\n
\n
\n

js

\n
new FinalizationRegistry(callbackFn)\n
\n

Note: FinalizationRegistry() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
callback

A function to be invoked each time a registered target value is garbage collected. Its return value is ignored. The function is called with the following arguments:

heldValue

The value that was passed to the second parameter of the register() method when the target object was registered.

Examples

\n

Creating a new registry

\n
\n

You create the registry passing in the callback:

\n

js

\n
const registry = new FinalizationRegistry((heldValue) => {\n  // …\n});\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-finalization-registry-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
FinalizationRegistry848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/FinalizationRegistry\n

\n
\n", + "global_objects/finalizationregistry/register": "

FinalizationRegistry.prototype.register()

The register() method of FinalizationRegistry instances registers an value with this FinalizationRegistry so that if the value is garbage-collected, the registry's callback may get called.

\n

Syntax

\n
\n

js

\n
register(target, heldValue)\nregister(target, heldValue, unregisterToken)\n
\n

Parameters

\n
target

The target value to register.

heldValue

The value to pass to the finalizer for this target. This cannot be the target itself but can be anything else, including functions and primitives.

\nunregisterToken Optional\n

A token that may be used with the unregister method later to unregister the target value. If provided (and not undefined), this must be an object or a non-registered symbol. If not provided, the target cannot be unregistered.

Return value

\n

None (undefined).

Exceptions

\n
TypeError

Thrown in one of the following cases:

  • \ntarget is not an object or a non-registered symbol (object as opposed to primitives; functions are objects as well)
  • \ntarget is the same as heldvalue (target === heldValue)
  • \nunregisterToken is not an object or a non-registered symbol\n

Description

\n

See the Avoid where possible and Notes on cleanup callbacks sections of the FinalizationRegistry page for important caveats.

Examples

\n

Using register

\n
\n

The following registers the value referenced by target, passing in the held value \"some value\" and passing the target itself as the unregistration token:

\n

js

\n
registry.register(target, \"some value\", target);\n
\n

The following registers the value referenced by target, passing in another object as the held value, and not passing in any unregistration token (which means target can't be unregistered):

\n

js

\n
registry.register(target, { useful: \"info about target\" });\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-finalization-registry.prototype.register
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
register848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/register\n

\n
\n", + "global_objects/finalizationregistry/unregister": "

FinalizationRegistry.prototype.unregister()

The unregister() method of FinalizationRegistry instances unregisters a target value from this FinalizationRegistry.

\n

Syntax

\n
\n

js

\n
unregister(unregisterToken)\n
\n

Parameters

\n
unregisterToken

The token used with the register() method when registering the target value. Multiple cells registered with the same unregisterToken will be unregistered together.

Return value

\n

A boolean value that is true if at least one cell was unregistered and false if no cell was unregistered.

Exceptions

\n
TypeError

Thrown if unregisterToken is not an object or a non-registered symbol.

Description

\n

When a target value has been reclaimed, it is no longer registered in the registry. There is no need to call unregister in your cleanup callback. Only call unregister if you haven't received a cleanup callback and no longer need to receive one.

Examples

\n

Using unregister

\n
\n

This example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister:

\n

js

\n
class Thingy {\n  static #cleanup = (label) => {\n    //               ^^^^^−−−−− held value\n    console.error(\n      `The \"release\" method was never called for the object with the label \"${label}\"`,\n    );\n  };\n  #registry = new FinalizationRegistry(Thingy.#cleanup);\n\n  /**\n   * Constructs a `Thingy` instance.\n   * Be sure to call `release` when you're done with it.\n   *\n   * @param label A label for the `Thingy`.\n   */\n  constructor(label) {\n    //                            vvvvv−−−−− held value\n    this.#registry.register(this, label, this);\n    //          target −−−−−^^^^         ^^^^−−−−− unregister token\n  }\n\n  /**\n   * Releases resources held by this `Thingy` instance.\n   */\n  release() {\n    this.#registry.unregister(this);\n    //                        ^^^^−−−−− unregister token\n  }\n}\n
\n

This example shows registering a target object using a different object as its unregister token:

\n

js

\n
class Thingy {\n  static #cleanup = (file) => {\n    //               ^^^^−−−−− held value\n    console.error(\n      `The \"release\" method was never called for the \"Thingy\" for the file \"${file.name}\"`,\n    );\n  };\n  #registry = new FinalizationRegistry(Thingy.#cleanup);\n  #file;\n\n  /**\n   * Constructs a `Thingy` instance for the given file.\n   * Be sure to call `release` when you're done with it.\n   *\n   * @param filename The name of the file.\n   */\n  constructor(filename) {\n    this.#file = File.open(filename);\n    //                            vvvvv−−−−− held value\n    this.#registry.register(this, label, this.#file);\n    //          target −−−−−^^^^         ^^^^^^^^^^−−−−− unregister token\n  }\n\n  /**\n   * Releases resources held by this `Thingy` instance.\n   */\n  release() {\n    if (this.#file) {\n      this.#registry.unregister(this.#file);\n      //                        ^^^^^^^^^^−−−−− unregister token\n      File.close(this.#file);\n      this.#file = null;\n    }\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-finalization-registry.prototype.unregister
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
unregister848479No7014.18484796014.514.01.014.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/unregister\n

\n
\n", + "global_objects/iterator/@@iterator": "

Iterator.prototype[@@iterator]()

The [@@iterator]() method of Iterator instances implements the iterable protocol and allows built-in iterators to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns the value of this, which is the iterator object itself.

\n

Syntax

\n
\n

js

\n
iterator[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The value of this, which is the iterator object itself.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes built-in iterators iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const arrIterator = [1, 2, 3].values();\nfor (const value of arrIterator) {\n  console.log(value);\n}\n// Logs: 1, 2, 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%iteratorprototype%-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/@@iterator\n

\n
\n", + "global_objects/typedarray/values": "

TypedArray.prototype.values()

The values() method of TypedArray instances returns a new array iterator object that iterates the value of each item in the typed array. This method has the same algorithm as Array.prototype.values().

\n

Try it

\n

Syntax

\n
\n

js

\n
values()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n

See Array.prototype.values() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Iteration using for...of loop

\n
\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nconst values = arr.values();\nfor (const n of values) {\n  console.log(n);\n}\n
\n

Alternative iteration

\n
\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nconst values = arr.values();\nconsole.log(values.next().value); // 10\nconsole.log(values.next().value); // 20\nconsole.log(values.next().value); // 30\nconsole.log(values.next().value); // 40\nconsole.log(values.next().value); // 50\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.values
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
values381237No251038383725103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/values\n

\n
\n", + "global_objects/typedarray/keys": "

TypedArray.prototype.keys()

The keys() method of TypedArray instances returns a new array iterator object that contains the keys for each index in the typed array. This method has the same algorithm as Array.prototype.keys().

\n

Try it

\n

Syntax

\n
\n

js

\n
keys()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n

See Array.prototype.keys() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Iteration using for...of loop

\n
\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nconst arrKeys = arr.keys();\nfor (const n of arrKeys) {\n  console.log(n);\n}\n
\n

Alternative iteration

\n
\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nconst arrKeys = arr.keys();\nconsole.log(arrKeys.next().value); // 0\nconsole.log(arrKeys.next().value); // 1\nconsole.log(arrKeys.next().value); // 2\nconsole.log(arrKeys.next().value); // 3\nconsole.log(arrKeys.next().value); // 4\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.keys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
keys381237No251038383725103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/keys\n

\n
\n", + "global_objects/typedarray/entries": "

TypedArray.prototype.entries()

The entries() method of TypedArray instances returns a new array iterator object that contains the key/value pairs for each index in the typed array. This method has the same algorithm as Array.prototype.entries().

\n

Try it

\n

Syntax

\n
\n

js

\n
entries()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object.

Description

\n

See Array.prototype.entries() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Iteration using for...of loop

\n
\n

js

\n
const array = new Uint8Array([10, 20, 30, 40, 50]);\nconst arrayEntries = arr.entries();\nfor (const element of arrayEntries) {\n  console.log(element);\n}\n
\n

Alternative iteration

\n
\n

js

\n
const array = new Uint8Array([10, 20, 30, 40, 50]);\nconst arrayEntries = arr.entries();\n\nconsole.log(arrayEntries.next().value); // [0, 10]\nconsole.log(arrayEntries.next().value); // [1, 20]\nconsole.log(arrayEntries.next().value); // [2, 30]\nconsole.log(arrayEntries.next().value); // [3, 40]\nconsole.log(arrayEntries.next().value); // [4, 50]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.entries
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
entries451237No329.1454537329.35.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/entries\n

\n
\n", + "global_objects/typedarray/@@iterator": "

TypedArray.prototype[@@iterator]()

\n

The [@@iterator]() method of TypedArray instances implements the iterable protocol and allows typed arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the typed array.

The initial value of this property is the same function object as the initial value of the TypedArray.prototype.values property.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
typedArray[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The same return value as TypedArray.prototype.values(): a new iterable iterator object that yields the value of each index in the typed array.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes typed arrays iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nfor (const n of arr) {\n  console.log(n);\n}\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const arr = new Uint8Array([10, 20, 30, 40, 50]);\nconst arrIter = arr[Symbol.iterator]();\nconsole.log(arrIter.next().value); // 10\nconsole.log(arrIter.next().value); // 20\nconsole.log(arrIter.next().value); // 30\nconsole.log(arrIter.next().value); // 40\nconsole.log(arrIter.next().value); // 50\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator381236
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
No2510383836
27–36A placeholder property named @@iterator is used.
17–27A placeholder property named iterator is used.
\n
25103.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator\n

\n
\n", + "functions/arguments/@@iterator": "

arguments[@@iterator]()

\n

The [@@iterator]() method of arguments objects implements the iterable protocol and allows arguments objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the arguments object.

The initial value of this property is the same function object as the initial value of the Array.prototype.values property (and also the same as Array.prototype[@@iterator]).

\n
\n

Syntax

\n
\n

js

\n
arguments[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

The same return value as Array.prototype.values(): a new iterable iterator object that yields the value of each index in the arguments object.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes arguments objects iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
function f() {\n  for (const letter of arguments) {\n    console.log(letter);\n  }\n}\nf(\"w\", \"y\", \"k\", \"o\", \"p\");\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
function f() {\n  const argsIter = arguments[Symbol.iterator]();\n  console.log(argsIter.next().value); // a\n  console.log(argsIter.next().value); // b\n  console.log(argsIter.next().value); // c\n  console.log(argsIter.next().value); // d\n  console.log(argsIter.next().value); // e\n}\nf(\"w\", \"y\", \"k\", \"o\", \"p\");\n
\n
\n

Specifications

\n
\n\n\n\n\n\n
Specification
ECMAScript Language Specification
# sec-createunmappedargumentsobject
ECMAScript Language Specification
# sec-createmappedargumentsobject
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator521246No3995252464196.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator\n

\n
\n", + "global_objects/intl/segmenter/segment/segments/@@iterator": "

Segments.prototype[@@iterator]()

The [@@iterator]() method of Segments instances implements the iterable protocol and allows Segments objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a segments iterator object that yields data about each segment.

\n

Try it

\n

Syntax

\n
\n

js

\n
segments[Symbol.iterator]()\n
\n

Parameters

\n

None.

Return value

\n

A new iterable iterator object that yields data about each segment. Each yielded object has the same properties as the object returned by the containing() method.

Examples

\n

Iteration using for...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@iterator method makes Segments objects iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

\n

js

\n
const segmenter = new Intl.Segmenter(\"zh-CN\", { granularity: \"word\" });\nconst input = \"你好,世界!我爱编程。\";\n\nfor (const value of segmenter.segment(input)) {\n  console.log(value);\n}\n\n/*\n{segment: '你好', index: 0, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: ',', index: 2, input: '你好,世界!我爱编程。', isWordLike: false}\n{segment: '世界', index: 3, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: '!', index: 5, input: '你好,世界!我爱编程。', isWordLike: false}\n{segment: '我', index: 6, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: '爱', index: 7, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: '编', index: 8, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: '程', index: 9, input: '你好,世界!我爱编程。', isWordLike: true}\n{segment: '。', index: 10, input: '你好,世界!我爱编程。', isWordLike: false}\n*/\n
\n
\n

Manually hand-rolling the iterator

\n
\n

You may still manually call the next() method of the returned iterator object to achieve maximum control over the iteration process.

\n

js

\n
const segmenter = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\nconst input = \"Moi ? N'est-ce pas ?\";\nconst segments = segmenter.segment(input);\nconst iterator = segments[Symbol.iterator]();\n\nlet result = iterator.next();\n\nwhile (!result.done) {\n  console.log(result.value);\n  result = iterator.next();\n}\n\n/*\n{segment: 'Moi', index: 0, input: \"Moi ? N'est-ce pas ?\", isWordLike: true}\n{segment: ' ', index: 3, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: '?', index: 4, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: ' ', index: 5, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: \"N'est\", index: 6, input: \"Moi ? N'est-ce pas ?\", isWordLike: true}\n{segment: '-', index: 11, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: 'ce', index: 12, input: \"Moi ? N'est-ce pas ?\", isWordLike: true}\n{segment: ' ', index: 14, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: 'pas', index: 15, input: \"Moi ? N'est-ce pas ?\", isWordLike: true}\n{segment: ' ', index: 18, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n{segment: '?', index: 19, input: \"Moi ? N'est-ce pas ?\", isWordLike: false}\n*/\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-%segmentsprototype%-@@iterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator8787NoNo7314.18787No6214.514.01.816.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/@@iterator\n

\n
\n", + "global_objects/intl/segmenter/segment/segments": "

Segments

A Segments object is an iterable collection of the segments of a text string. It is returned by a call to the segment() method of an Intl.Segmenter object.

\n

Try it

\n

Instance methods

\n
Segments.prototype.containing()

Returns an object describing the segment in the original string that includes the code unit at a specified index.

Segments.prototype[@@iterator]()

Returns an iterator to iterate over the segments.

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-segments-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@iterator8787NoNo7314.18787No6214.514.01.816.0.0
Segments8787NoNo7314.18787No6214.514.01.816.0.0
containing8787NoNo7314.18787No6214.514.01.816.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments\n

\n
\n", + "global_objects/intl/segmenter/segment": "

Intl.Segmenter.prototype.segment()

The segment() method of Intl.Segmenter instances segments a string according to the locale and granularity of this Intl.Segmenter object.

\n

Try it

\n

Syntax

\n
\n

js

\n
segment(input)\n
\n

Parameters

\n
input

The text to be segmented as a string.

Return value

\n

A new iterable Segments object containing the segments of the input string, using the segmenter's locale and granularity.

Examples

\n
\n

js

\n
// Create a locale-specific word segmenter\nconst segmenter = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\n\n// Use it to get an iterator over the segments of a string\nconst input = \"Moi ? N'est-ce pas ?\";\nconst segments = segmenter.segment(input);\n\n// Use that for segmentation\nfor (const { segment, index, isWordLike } of segments) {\n  console.log(\n    \"segment at code units [%d, %d]: «%s»%s\",\n    index,\n    index + segment.length,\n    segment,\n    isWordLike ? \" (word-like)\" : \"\",\n  );\n}\n// segment at code units [0, 3]: «Moi» (word-like)\n// segment at code units [3, 4]: « »\n// segment at code units [4, 5]: «?»\n// segment at code units [5, 6]: « »\n// segment at code units [6, 11]: «N'est» (word-like)\n// segment at code units [11, 12]: «-»\n// segment at code units [12, 14]: «ce» (word-like)\n// segment at code units [14, 15]: « »\n// segment at code units [15, 18]: «pas» (word-like)\n// segment at code units [18, 19]: « »\n// segment at code units [19, 20]: «?»\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.segmenter.prototype.segment
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
segment8787NoNo7314.18787No6214.514.01.816.0.0
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment\n

\n
\n", + "global_objects/iterator/filter": "

Iterator.prototype.filter()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The filter() method of Iterator instances returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns true.

\n
\n

Syntax

\n
\n

js

\n
filter(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. It should return a truthy value to make the element yielded by the iterator helper, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

A new iterator helper. Each time the iterator helper's next() method is called, it returns the next element in the iterator for which the callback function returns true. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).

Description

\n

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, filter() allows you to iterate over only those elements that satisfy a given condition.

Examples

\n

Using filter()

\n
\n

The following example creates an iterator that yields terms in the Fibonacci sequence, and then reads the first few terms that are even:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst seq = fibonacci().filter((x) => x % 2 === 0);\nconsole.log(seq.next().value); // 2\nconsole.log(seq.next().value); // 8\nconsole.log(seq.next().value); // 34\n
\n
\n

Using filter() with a for...of loop

\n
\n

filter() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of loop:

\n

js

\n
for (const n of fibonacci().filter((x) => x % 2 === 0)) {\n  console.log(n);\n  if (n > 30) {\n    break;\n  }\n}\n\n// Logs:\n// 2\n// 8\n// 34\n
\n

This is equivalent to:

\n

js

\n
for (const n of fibonacci()) {\n  if (n % 2 !== 0) {\n    continue;\n  }\n  console.log(n);\n  if (n > 30) {\n    break;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.filter
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
filter117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/filter\n

\n
\n", + "global_objects/iterator/map": "

Iterator.prototype.map()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The map() method of Iterator instances returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function.

\n
\n

Syntax

\n
\n

js

\n
map(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. Its return value is yielded by the iterator helper. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

A new iterator helper. Each time the iterator helper's next() method is called, it gets the next element from the underlying iterator, applies callbackFn, and yields the return value. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).

Description

\n

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, map() allows you to create a new iterator that, when iterated, produces transformed elements.

Examples

\n

Using map()

\n
\n

The following example creates an iterator that yields terms in the Fibonacci sequence, transforms it into a new sequence with each term squared, and then reads the first few terms:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst seq = fibonacci().map((x) => x ** 2);\nconsole.log(seq.next().value); // 1\nconsole.log(seq.next().value); // 1\nconsole.log(seq.next().value); // 4\n
\n
\n

Using map() with a for...of loop

\n
\n

map() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of loop:

\n

js

\n
for (const n of fibonacci().map((x) => x ** 2)) {\n  console.log(n);\n  if (n > 30) {\n    break;\n  }\n}\n\n// Logs:\n// 1\n// 1\n// 4\n// 9\n// 25\n// 64\n
\n

This is equivalent to:

\n

js

\n
for (const n of fibonacci()) {\n  const n2 = n ** 2;\n  console.log(n2);\n  if (n2 > 30) {\n    break;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.map
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
map117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/map\n

\n
\n", + "global_objects/iterator/every": "

Iterator.prototype.every()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The every() method of Iterator instances is similar to Array.prototype.every(): it tests whether all elements produced by the iterator pass the test implemented by the provided function. It returns a boolean value.

\n
\n

Syntax

\n
\n

js

\n
every(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

true if callbackFn returns a truthy value for every element. Otherwise, false.

Description

\n
\n

every() iterates the iterator and invokes the callbackFn function once for each element. It returns false immediately if the callback function returns a falsy value. Otherwise, it iterates until the end of the iterator and returns true. If every() returns false, the underlying iterator is closed by calling its return() method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, every() returns false as soon as the first falsy value is found. If the callbackFn always returns a truthy value, the method never returns.

\n

Examples

\n

Using every()

\n
\n
\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst isEven = (x) => x % 2 === 0;\nconsole.log(fibonacci().every(isEven)); // false\n\nconst isPositive = (x) => x > 0;\nconsole.log(fibonacci().take(10).every(isPositive)); // true\nconsole.log(fibonacci().every(isPositive)); // Never completes\n
\n

Calling every() always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

\n

js

\n
const seq = fibonacci();\nconsole.log(seq.every(isEven)); // false\nconsole.log(seq.next()); // { value: undefined, done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.every
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
every117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/every\n

\n
\n", + "global_objects/iterator/find": "

Iterator.prototype.find()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The find() method of Iterator instances is similar to Array.prototype.find(): it returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

\n
\n

Syntax

\n
\n

js

\n
find(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

The first element produced by the iterator that satisfies the provided testing function. Otherwise, undefined is returned.

Description

\n
\n

find() iterates the iterator and invokes the callbackFn function once for each element. It returns the element immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns undefined. If find() returns an element, the underlying iterator is closed by calling its return() method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, find() returns the first satisfying element as soon as it is found. If the callbackFn always returns a falsy value, the method never returns.

\n

Examples

\n

Using find()

\n
\n
\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst isEven = (x) => x % 2 === 0;\nconsole.log(fibonacci().find(isEven)); // 2\n\nconst isNegative = (x) => x < 0;\nconsole.log(fibonacci().take(10).find(isNegative)); // undefined\nconsole.log(fibonacci().find(isNegative)); // Never completes\n
\n

Calling find() always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

\n

js

\n
const seq = fibonacci();\nconsole.log(seq.find(isEven)); // 2\nconsole.log(seq.next()); // { value: undefined, done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.find
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
find117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/find\n

\n
\n", + "global_objects/iterator/flatmap": "

Iterator.prototype.flatMap()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The flatMap() method of Iterator instances returns a new iterator helper that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).

\n
\n

Syntax

\n
\n

js

\n
flatMap(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. It should return an iterator or iterable that yields elements to be yielded by flatMap(), or a single non-iterator/iterable value to be yielded. The function is called with the following arguments:

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

Return value

\n

A new iterator helper. The first time the iterator helper's next() method is called, it calls callbackFn on the first element produced by the underlying iterator, and the return value, which should be an iterator or iterable, is yielded one-by-one by the iterator helper (like yield*). The next element is fetched from the underlying iterator when the previous one returned by callbackFn is completed. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).

Exceptions

\n
TypeError

Thrown if callbackFn returns a non-iterator/iterable value or a string primitive.

Description

\n
\n

flatMap accepts two kinds of return values from callbackFn: an iterator or iterable. They are handled in the same way as Iterator.from(): if the return value is iterable, the @@iterator method is called and the return value is used; otherwise, the return value is treated as an iterator and its next() method is called.

\n

js

\n
[1, 2, 3]\n  .values()\n  .flatMap((x) => {\n    let itDone = false;\n    const it = {\n      next() {\n        if (itDone) {\n          return { value: undefined, done: true };\n        }\n        itDone = true;\n        return { value: x, done: false };\n      },\n    };\n    switch (x) {\n      case 1:\n        // An iterable that's not an iterator\n        return { [Symbol.iterator]: () => it };\n      case 2:\n        // An iterator that's not an iterable\n        return it;\n      case 3:\n        // An iterable iterator is treated as an iterable\n        return {\n          ...it,\n          [Symbol.iterator]() {\n            console.log(\"@@iterator called\");\n            return it;\n          },\n        };\n    }\n  })\n  .toArray();\n// Logs \"@@iterator called\"\n// Returns [1, 2, 3]\n
\n
\n

Examples

\n

Merging maps

\n
\n

The following example merges two Map objects into one:

\n

js

\n
const map1 = new Map([\n  [\"a\", 1],\n  [\"b\", 2],\n  [\"c\", 3],\n]);\nconst map2 = new Map([\n  [\"d\", 4],\n  [\"e\", 5],\n  [\"f\", 6],\n]);\n\nconst merged = new Map([map1, map2].values().flatMap((x) => x));\nconsole.log(merged.get(\"a\")); // 1\nconsole.log(merged.get(\"e\")); // 5\n
\n

This avoids creating any temporary copies of the map's content. Note that the array [map1, map2] must first be converted to an iterator (using Array.prototype.values()), because Array.prototype.flatMap() only flattens arrays, not iterables.

\n

js

\n
new Map([map1, map2].flatMap((x) => x)); // Map(1) {undefined => undefined}\n
\n
\n

Returning strings

\n
\n

Strings are iterable, but flatMap() specifically rejects string primitives returned from callbackFn, this is because the behavior of iterating by code points is often not what you want.

\n

js

\n
[1, 2, 3]\n  .values()\n  .flatMap((x) => String(x))\n  .toArray(); // TypeError: Iterator.prototype.flatMap called on non-object\n
\n

You may want to wrap it in an array instead so the entire string is yielded as one:

\n

js

\n
[1, 2, 3]\n  .values()\n  .flatMap((x) => [String(x)])\n  .toArray(); // ['1', '2', '3']\n
\n

Or, if the behavior of iterating by code points is intended, you can use Iterator.from() to convert it to a proper iterator:

\n

js

\n
[1, 2, 3]\n  .values()\n  .flatMap((x) => Iterator.from(String(x * 10)))\n  .toArray();\n// ['1', '0', '2', '0', '3', '0']\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.flatmap
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
flatMap117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/flatMap\n

\n
\n", + "global_objects/iterator/foreach": "

Iterator.prototype.forEach()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The forEach() method of Iterator instances is similar to Array.prototype.forEach(): it executes a provided function once for each element produced by the iterator.

\n
\n

Syntax

\n
\n

js

\n
forEach(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. Its return value is discarded. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

undefined.

Description

\n

forEach() iterates the iterator and invokes the callbackFn function once for each element. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.

Examples

\n

Using forEach()

\n
\n
\n

js

\n
new Set([1, 2, 3]).values().forEach((v) => console.log(v));\n\n// Logs:\n// 1\n// 2\n// 3\n
\n

This is equivalent to:

\n

js

\n
for (const v of new Set([1, 2, 3]).values()) {\n  console.log(v);\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.foreach
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
forEach117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/forEach\n

\n
\n", + "global_objects/iterator/reduce": "

Iterator.prototype.reduce()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The reduce() method of Iterator instances is similar to Array.prototype.reduce: it executes a user-supplied \"reducer\" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

\n
\n

Syntax

\n
\n

js

\n
reduce(callbackFn)\nreduce(callbackFn, initialValue)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:

accumulator

The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is the first element of the iterator.

currentValue

The value of the current element. On the first call, its value is the first element of the iterator if initialValue is specified; otherwise its value is the second element.

currentIndex

The index position of currentValue. On the first call, its value is 0 if initialValue is specified, otherwise 1.

\ninitialValue Optional\n

A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first element as currentValue. If initialValue is not specified, accumulator is initialized to the first element, and callbackFn starts executing with the second element as currentValue. In this case, if the iterator is empty (so that there's no first value to return as accumulator), an error is thrown.

Return value

\n

The value that results from running the \"reducer\" callback function to completion over the entire iterator.

Exceptions

\n
TypeError

Thrown if the iterator contains no elements and initialValue is not provided.

Description

\n

See Array.prototype.reduce() for details about how reduce() works. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.

Examples

\n

Using reduce()

\n
\n

The following example creates an iterator that yields terms in the Fibonacci sequence, and then sums the first ten terms:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconsole.log(\n  fibonacci()\n    .take(10)\n    .reduce((a, b) => a + b),\n); // 143\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.reduce
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reduce117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/reduce\n

\n
\n", + "global_objects/iterator/some": "

Iterator.prototype.some()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The some() method of Iterator instances is similar to Array.prototype.some(): it tests whether at least one element in the array passes the test implemented by the provided function. It returns a boolean value.

\n
\n

Syntax

\n
\n

js

\n
some(callbackFn)\n
\n

Parameters

\n
callbackFn

A function to execute for each element produced by the iterator. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed.

index

The index of the current element being processed.

Return value

\n

true if the callback function returns a truthy value for at least one element. Otherwise, false.

Description

\n
\n

some() iterates the iterator and invokes the callbackFn function once for each element. It returns true immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns false. If some() returns true, the underlying iterator is closed by calling its return() method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, some() returns true as soon as the first truthy value is found. If the callbackFn always returns a falsy value, the method never returns.

\n

Examples

\n

Using some()

\n
\n
\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst isEven = (x) => x % 2 === 0;\nconsole.log(fibonacci().some(isEven)); // true\n\nconst isNegative = (x) => x < 0;\nconst isPositive = (x) => x > 0;\nconsole.log(fibonacci().take(10).some(isPositive)); // false\nconsole.log(fibonacci().some(isNegative)); // Never completes\n
\n

Calling some() always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

\n

js

\n
const seq = fibonacci();\nconsole.log(seq.some(isEven)); // true\nconsole.log(seq.next()); // { value: undefined, done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.some
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
some117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/some\n

\n
\n", + "global_objects/iterator/drop": "

Iterator.prototype.drop()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The drop() method of Iterator instances returns a new iterator helper that skips the given number of elements at the start of this iterator.

\n
\n

Syntax

\n
\n

js

\n
drop(limit)\n
\n

Parameters

\n
limit

The number of elements to drop from the start of the iteration.

Return value

\n

A new iterator helper. The first time the returned iterator helper's next() method is called, the current iterator is immediately advanced by limit elements, and then the next element (the limit+1-th element) is yielded. The iterator helper then yields the remaining elements one-by-one. If the current iterator has fewer than limit elements, the new iterator helper will be immediately completed the first time next() is called.

Exceptions

\n
RangeError

Thrown if limit becomes NaN or negative when converted to an integer.

Examples

\n

Using drop()

\n
\n

The following example creates an iterator that yields terms in the Fibonacci sequence, starting from the 3rd term by dropping the first two terms:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst seq = fibonacci().drop(2);\nconsole.log(seq.next().value); // 2\nconsole.log(seq.next().value); // 3\n
\n

This is equivalent to:

\n

js

\n
const seq = fibonacci();\nseq.next();\nseq.next();\n
\n
\n

Using drop() with a for...of loop

\n
\n

drop() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of loop:

\n

js

\n
for (const n of fibonacci().drop(2)) {\n  console.log(n);\n  if (n > 30) {\n    break;\n  }\n}\n\n// Logs:\n// 2\n// 3\n// 5\n// 8\n// 13\n// 21\n// 34\n
\n
\n

Combining drop() with take()

\n
\n

You can combine drop() with Iterator.prototype.take() to get a slice of an iterator:

\n

js

\n
for (const n of fibonacci().drop(2).take(5)) {\n  // Drops the first two elements, then takes the next five\n  console.log(n);\n}\n// Logs:\n// 2\n// 3\n// 5\n// 8\n// 13\n\nfor (const n of fibonacci().take(5).drop(2)) {\n  // Takes the first five elements, then drops the first two\n  console.log(n);\n}\n// Logs:\n// 2\n// 3\n// 5\n
\n
\n

Lower and upper bounds of drop count

\n
\n

When the limit is negative or NaN, a RangeError is thrown:

\n

js

\n
fibonacci().drop(-1); // RangeError: -1 must be positive\nfibonacci().drop(undefined); // RangeError: undefined must be positive\n
\n

When the limit is larger than the total number of elements the iterator can produce (such as Infinity), the returned iterator helper will instantly drop all elements and then be completed the first time next() is called. If the current iterator is infinite, the returned iterator helper will never complete.

\n

js

\n
fibonacci().drop(Infinity).next(); // Never ends\nnew Set([1, 2, 3]).values().drop(Infinity).next(); // { value: undefined, done: true }\nnew Set([1, 2, 3]).values().drop(4).next(); // { value: undefined, done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.drop
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
drop117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/drop\n

\n
\n", + "global_objects/iterator/take": "

Iterator.prototype.take()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The take() method of Iterator instances returns a new iterator helper that yields the given number of elements in this iterator and then terminates.

\n
\n

Syntax

\n
\n

js

\n
take(limit)\n
\n

Parameters

\n
limit

The number of elements to take from the start of the iteration.

Return value

\n

A new iterator helper. The returned iterator helper yields the elements in the original iterator one-by-one, and then completes (the next() method produces { value: undefined, done: true }) once limit elements have been yielded, or when the original iterator is exhausted, whichever comes first.

Exceptions

\n
RangeError

Thrown if limit becomes NaN or negative when converted to an integer.

Examples

\n

Using take()

\n
\n

The following example creates an iterator that yields terms in the Fibonacci sequence, and then logs the first three terms:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst seq = fibonacci().take(3);\nconsole.log(seq.next().value); // 1\nconsole.log(seq.next().value); // 1\nconsole.log(seq.next().value); // 2\nconsole.log(seq.next().value); // undefined\n
\n
\n

Using take() with a for...of loop

\n
\n

take() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of loop:

\n

js

\n
for (const n of fibonacci().take(5)) {\n  console.log(n);\n}\n\n// Logs:\n// 1\n// 1\n// 2\n// 3\n// 5\n
\n

Because fibonacci() is an infinite iterator, you can't use a for loop to iterate it directly.

\n

Combining drop() with take()

\n
\n

You can combine drop() with Iterator.prototype.take() to get a slice of an iterator:

\n

js

\n
for (const n of fibonacci().drop(2).take(5)) {\n  // Drops the first two elements, then takes the next five\n  console.log(n);\n}\n// Logs:\n// 2\n// 3\n// 5\n// 8\n// 13\n\nfor (const n of fibonacci().take(5).drop(2)) {\n  // Takes the first five elements, then drops the first two\n  console.log(n);\n}\n// Logs:\n// 2\n// 3\n// 5\n
\n
\n

Lower and upper bounds of take count

\n
\n

When the limit is negative or NaN, a RangeError is thrown:

\n

js

\n
fibonacci().take(-1); // RangeError: -1 must be positive\nfibonacci().take(undefined); // RangeError: undefined must be positive\n
\n

When the limit is larger than the total number of elements the iterator can produce (such as Infinity), the returned iterator helper has essentially the same behavior as the original iterator:

\n

js

\n
for (const n of new Set([1, 2, 3]).values().take(Infinity)) {\n  console.log(n);\n}\n\n// Logs:\n// 1\n// 2\n// 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.take
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
take117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/take\n

\n
\n", + "global_objects/iterator/iterator": "

Iterator() constructor

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Iterator() constructor is intended to be used as the superclass of other classes that create iterators. It throws an error when constructed by itself.

\n
\n

Syntax

\n
\n
\n

js

\n
new Iterator()\n
\n

Note: Iterator() can only be constructed with new. Attempting to call it without new throws a TypeError. In addition, Iterator() cannot actually be constructed itself — it's usually implicitly constructed through super() calls inside the constructor of a subclass.

\n

Parameters

\n

None.

Return value

\n

A new Iterator object.

Exceptions

\n
TypeError

When new.target is the Iterator function itself, i.e. when the Iterator constructor itself is constructed.

Description

\n
\n

Iterator represents an abstract class — a class that provides common utilities for its subclasses, but is not intended to be instantiated itself. It is the superclass of all other iterator classes, and is used to create subclasses that implement specific iteration algorithms — namely, all subclasses of Iterator must implement a next() method as required by the iterator protocol. Because Iterator doesn't actually provide the next() method, it doesn't make sense to construct an Iterator directly.

You can also use Iterator.from() to create an Iterator instance from an existing iterable or iterator object.

\n

Examples

\n

Subclassing Iterator

\n
\n

The following example defines a custom data structure, Range, which allows iteration. The simplest way to make an object iterable is to provide an [@@iterator]() method in the form of a generator function:

\n

js

\n
class Range {\n  #start;\n  #end;\n  #step;\n\n  constructor(start, end, step = 1) {\n    this.#start = start;\n    this.#end = end;\n    this.#step = step;\n  }\n\n  *[Symbol.iterator]() {\n    for (let value = this.#start; value <= this.#end; value += this.#step) {\n      yield value;\n    }\n  }\n}\n\nconst range = new Range(1, 5);\nfor (const num of range) {\n  console.log(num);\n}\n
\n

This works, but it isn't as nice as how built-in iterators work. There are two problems:

We can mimic the implementation of built-in iterators, such as map iterators, by subclassing Iterator. This enables us to define extra properties, such as @@toStringTag, while making the iterator helper methods available on the returned iterator.

\n

js

\n
class Range {\n  #start;\n  #end;\n  #step;\n\n  constructor(start, end, step = 1) {\n    this.#start = start;\n    this.#end = end;\n    this.#step = step;\n  }\n\n  static #RangeIterator = class extends Iterator {\n    #cur;\n    #s;\n    #e;\n    constructor(range) {\n      super();\n      this.#cur = range.#start;\n      this.#s = range.#step;\n      this.#e = range.#end;\n    }\n    static {\n      Object.defineProperty(this.prototype, Symbol.toStringTag, {\n        value: \"Range Iterator\",\n        configurable: true,\n        enumerable: false,\n        writable: false,\n      });\n\n      // Avoid #RangeIterator from being accessible outside\n      delete this.prototype.constructor;\n    }\n    next() {\n      if (this.#cur > this.#e) {\n        return { value: undefined, done: true };\n      }\n      const res = { value: this.#cur, done: false };\n      this.#cur += this.#s;\n      return res;\n    }\n  };\n\n  [Symbol.iterator]() {\n    return new Range.#RangeIterator(this);\n  }\n}\n\nconst range = new Range(1, 5);\nfor (const num of range) {\n  console.log(num);\n}\n
\n

The subclassing pattern is useful if you want to create many custom iterators. If you have an existing iterable or iterator object which doesn't inherit from Iterator, and you just want to call iterator helper methods on it, you can use Iterator.from() to create a one-time Iterator instance.

\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iterator-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Iterator117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/Iterator\n

\n
\n", + "global_objects/iterator/from": "

Iterator.from()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Iterator.from() static method creates a new Iterator object from an iterator or iterable object.

\n
\n

Syntax

\n
\n

js

\n
from(object)\n
\n

Parameters

\n
object

An object that implements the iterable protocol or the iterator protocol.

Return value

\n

If object is an iterable, its @@iterator method is called to obtain the iterator. Otherwise, object is assumed to be an iterator. If the iterator is already instanceof Iterator (which means it has Iterator.prototype in its prototype chain), it is returned directly. Otherwise, a new Iterator object is created that wraps the original iterator.

Description

\n
\n

This method exists to convert custom iterators, probably exported by libraries, to proper iterators. All iterator objects returned by Iterator.from() inherit from a common prototype object, which has the following methods:

next()

Calls the underlying iterator's next() method and returns the result.

return()

Calls the underlying iterator's return() method and returns the result, or returns { value: undefined, done: true } if the underlying iterator doesn't have a return() method.

\n

Examples

\n

Converting an iterable to a proper iterator

\n
\n

Because obj is already an iterable that returns a proper iterator when its @@iterator method is called, Iterator.from(obj) returns the same iterator.

\n

js

\n
const iterator = (function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n})();\n\nconst obj = {\n  [Symbol.iterator]() {\n    return iterator;\n  },\n};\n\nconst iterator2 = Iterator.from(obj);\nconsole.log(iterator2 === iterator); // true\n
\n

Because obj2 is an iterable that returns a non-proper iterator when its @@iterator method is called, Iterator.from(obj2) returns a new iterator that wraps the original iterator.

\n

js

\n
const iterator = {\n  current: 0,\n  next() {\n    return { value: this.current++, done: false };\n  },\n};\n\nconst obj2 = {\n  [Symbol.iterator]() {\n    return iterator;\n  },\n};\n\nconst iterator2 = Iterator.from(obj2);\nconsole.log(iterator2 === iterator); // false\nconsole.log(iterator2.next()); // { value: 0, done: false }\nconsole.log(iterator.next()); // { value: 1, done: false }\n
\n
\n

Converting an iterator to a proper iterator

\n
\n

Because obj is already a proper iterator, Iterator.from(obj) returns itself.

\n

js

\n
const obj = (function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n})();\n\nconst iterator = Iterator.from(obj);\nconsole.log(iterator === obj); // true\n
\n

Because obj2 is a non-proper iterator, Iterator.from(obj2) returns a new iterator that wraps the original iterator.

\n

js

\n
const obj2 = {\n  current: 0,\n  next() {\n    return { value: this.current++, done: false };\n  },\n};\n\nconst iterator = Iterator.from(obj2);\nconsole.log(iterator === obj2); // false\nconsole.log(iterator.next()); // { value: 0, done: false }\nconsole.log(obj2.next()); // { value: 1, done: false }\n
\n
\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iterator.from
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
from117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/from\n

\n
\n", + "global_objects/iterator/toarray": "

Iterator.prototype.toArray()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The toArray() method of Iterator instances creates a new Array instance populated with the elements yielded from the iterator.

\n
\n

Syntax

\n
\n

js

\n
toArray()\n
\n

Parameters

\n

None.

Return value

\n

A new Array instance containing the elements from the iterator in the order they were produced.

Examples

\n

Using toArray()

\n
\n

iterator.toArray() is equivalent to Array.from(iterator) and [...iterator], except that it's easier to chain when multiple iterator helper methods are involved. The following example creates an iterator that yields terms in the Fibonacci sequence, takes the first 10 terms, filters out the odd numbers, and converts the result to an array:

\n

js

\n
function* fibonacci() {\n  let current = 1;\n  let next = 1;\n  while (true) {\n    yield current;\n    [current, next] = [next, current + next];\n  }\n}\n\nconst array = fibonacci()\n  .take(10)\n  .filter((x) => x % 2 === 0)\n  .toArray();\n\nconsole.log(array); // [2, 8, 34]\n
\n

Note that it's a good idea to call toArray() as a last step of your processing. For example, fibonacci().take(10).toArray().filter(...) is less efficient, because iterator helpers are lazy and avoids creating a temporary array.

\n

Specifications

\n
\n\n\n
Specification
Iterator Helpers
# sec-iteratorprototype.toarray
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toArray117117NoNo103No117117NoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/toArray\n

\n
\n", + "global_objects/asynciterator/@@asynciterator": "

AsyncIterator.prototype[@@asyncIterator]()

The [@@asyncIterator]() method of AsyncIterator instances implements the async iterable protocol and allows built-in async iterators to be consumed by most syntaxes expecting async iterables, such as for await...of loops. It returns the value of this, which is the async iterator object itself.

\n

Try it

\n

Syntax

\n
\n

js

\n
asyncIterator[Symbol.asyncIterator]()\n
\n

Parameters

\n

None.

Return value

\n

The value of this, which is the async iterator object itself.

Examples

\n

Iteration using for await...of loop

\n
\n

Note that you seldom need to call this method directly. The existence of the @@asyncIterator method makes all built-in async iterators async iterable, and iterating syntaxes like the for await...of loop automatically calls this method to obtain the async iterator to loop over.

\n

js

\n
const asyncIterator = (async function* () {\n  yield 1;\n  yield 2;\n  yield 3;\n})();\n(async () => {\n  for await (const value of asyncIterator) {\n    console.log(value);\n  }\n})();\n// Logs: 1, 2, 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asynciteratorprototype-asynciterator
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@asyncIterator637957No5011.16363574611.38.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator/@@asyncIterator\n

\n
\n", + "global_objects/promise/then": "

Promise.prototype.then()

The then() method of Promise instances takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise. It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods.

\n

Try it

\n

Syntax

\n
\n

js

\n
then(onFulfilled)\nthen(onFulfilled, onRejected)\n
\n

Parameters

\n
onFulfilled

A function to asynchronously execute when this promise becomes fulfilled. Its return value becomes the fulfillment value of the promise returned by then(). The function is called with the following arguments:

value

The value that the promise was fulfilled with.

If it is not a function, it is internally replaced with an identity function ((x) => x) which simply passes the fulfillment value forward.

\nonRejected Optional\n

A function to asynchronously execute when this promise becomes rejected. Its return value becomes the fulfillment value of the promise returned by then(). The function is called with the following arguments:

reason

The value that the promise was rejected with.

If it is not a function, it is internally replaced with a thrower function ((x) => { throw x; }) which throws the rejection reason it received.

Return value

\n
\n

Returns a new Promise immediately. This new promise is always pending when returned, regardless of the current promise's status.

One of the onFulfilled and onRejected handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it p) depends on the handler's execution result, following a specific set of rules. If the handler function:

\n

Description

\n
\n

The then() method schedules callback functions for the eventual completion of a Promise — either fulfillment or rejection. It is the primitive method of promises: the thenable protocol expects all promise-like objects to expose a then() method, and the catch() and finally() methods both work by invoking the object's then() method.

For more information about the onRejected handler, see the catch() reference.

then() returns a new promise object. If you call the then() method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of then() start separate chains and do not wait for each other's settlement.

Thenable objects that arise along the then() chain are always resolved — the onFulfilled handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the resolve and reject functions passed by the executor are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the resolver function passed by the Promise() constructor.

then() supports subclassing, which means it can be called on instances of subclasses of Promise, and the result will be a promise of the subclass type. You can customize the type of the return value through the @@species property.

\n

Examples

\n

Using the then() method

\n
\n

js

\n
const p1 = new Promise((resolve, reject) => {\n  resolve(\"Success!\");\n  // or\n  // reject(new Error(\"Error!\"));\n});\n\np1.then(\n  (value) => {\n    console.log(value); // Success!\n  },\n  (reason) => {\n    console.error(reason); // Error!\n  },\n);\n
\n

Having a non-function as either parameter

\n
\n

js

\n
Promise.resolve(1).then(2).then(console.log); // 1\nPromise.reject(1).then(2, 2).then(console.log, console.log); // 1\n
\n

Chaining

\n
\n

The then method returns a new Promise, which allows for method chaining.

If the function passed as handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain. The below snippet simulates asynchronous code with the setTimeout function.

\n

js

\n
Promise.resolve(\"foo\")\n  // 1. Receive \"foo\", concatenate \"bar\" to it, and resolve that to the next then\n  .then(\n    (string) =>\n      new Promise((resolve, reject) => {\n        setTimeout(() => {\n          string += \"bar\";\n          resolve(string);\n        }, 1);\n      }),\n  )\n  // 2. receive \"foobar\", register a callback function to work on that string\n  // and print it to the console, but not before returning the unworked on\n  // string to the next then\n  .then((string) => {\n    setTimeout(() => {\n      string += \"baz\";\n      console.log(string); // foobarbaz\n    }, 1);\n    return string;\n  })\n  // 3. print helpful messages about how the code in this section will be run\n  // before the string is actually processed by the mocked asynchronous code in the\n  // previous then block.\n  .then((string) => {\n    console.log(\n      \"Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising\",\n    );\n\n    // Note that `string` will not have the 'baz' bit of it at this point. This\n    // is because we mocked that to happen asynchronously with a setTimeout function\n    console.log(string); // foobar\n  });\n\n// Logs, in order:\n// Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising\n// foobar\n// foobarbaz\n
\n

The value returned from then() is resolved in the same way as Promise.resolve(). This means thenable objects are supported, and if the return value is not a promise, it's implicitly wrapped in a Promise and then resolved.

\n

js

\n
const p2 = new Promise((resolve, reject) => {\n  resolve(1);\n});\n\np2.then((value) => {\n  console.log(value); // 1\n  return value + 1;\n}).then((value) => {\n  console.log(value, \"- A synchronous value works\"); // 2 - A synchronous value works\n});\n\np2.then((value) => {\n  console.log(value); // 1\n});\n
\n

A then call returns a promise that eventually rejects if the function throws an error or returns a rejected Promise.

\n

js

\n
Promise.resolve()\n  .then(() => {\n    // Makes .then() return a rejected promise\n    throw new Error(\"Oh no!\");\n  })\n  .then(\n    () => {\n      console.log(\"Not called.\");\n    },\n    (error) => {\n      console.error(`onRejected function called: ${error.message}`);\n    },\n  );\n
\n

In practice, it is often desirable to catch() rejected promises rather than then()'s two-case syntax, as demonstrated below.

\n

js

\n
Promise.resolve()\n  .then(() => {\n    // Makes .then() return a rejected promise\n    throw new Error(\"Oh no!\");\n  })\n  .catch((error) => {\n    console.error(`onRejected function called: ${error.message}`);\n  })\n  .then(() => {\n    console.log(\"I am always called even if the prior then's promise rejects\");\n  });\n
\n

In all other cases, the returned promise eventually fulfills. In the following example, the first then() returns 42 wrapped in a fulfilled Promise, even though the previous Promise in the chain was rejected.

\n

js

\n
Promise.reject()\n  .then(\n    () => 99,\n    () => 42,\n  ) // onRejected returns 42 which is wrapped in a fulfilled Promise\n  .then((solution) => console.log(`Resolved with ${solution}`)); // Fulfilled with 42\n
\n

If onFulfilled returns a promise, the return value of then will be fulfilled/rejected based on the eventual state of that promise.

\n

js

\n
function resolveLater(resolve, reject) {\n  setTimeout(() => {\n    resolve(10);\n  }, 1000);\n}\nfunction rejectLater(resolve, reject) {\n  setTimeout(() => {\n    reject(new Error(\"Error\"));\n  }, 1000);\n}\n\nconst p1 = Promise.resolve(\"foo\");\nconst p2 = p1.then(() => {\n  // Return promise here, that will be resolved to 10 after 1 second\n  return new Promise(resolveLater);\n});\np2.then(\n  (v) => {\n    console.log(\"resolved\", v); // \"resolved\", 10\n  },\n  (e) => {\n    // not called\n    console.error(\"rejected\", e);\n  },\n);\n\nconst p3 = p1.then(() => {\n  // Return promise here, that will be rejected with 'Error' after 1 second\n  return new Promise(rejectLater);\n});\np3.then(\n  (v) => {\n    // not called\n    console.log(\"resolved\", v);\n  },\n  (e) => {\n    console.error(\"rejected\", e); // \"rejected\", 'Error'\n  },\n);\n
\n

You can use chaining to implement one function with a Promise-based API on top of another such function.

\n

js

\n
function fetchCurrentData() {\n  // The fetch() API returns a Promise. This function\n  // exposes a similar API, except the fulfillment\n  // value of this function's Promise has had more\n  // work done on it.\n  return fetch(\"current-data.json\").then((response) => {\n    if (response.headers.get(\"content-type\") !== \"application/json\") {\n      throw new TypeError();\n    }\n    const j = response.json();\n    // maybe do something with j\n\n    // fulfillment value given to user of\n    // fetchCurrentData().then()\n    return j;\n  });\n}\n
\n
\n

Asynchronicity of then()

\n
\n

The following is an example to demonstrate the asynchronicity of the then method.

\n

js

\n
// Using a resolved promise 'resolvedProm' for example,\n// the function call 'resolvedProm.then(...)' returns a new promise immediately,\n// but its handler '(value) => {...}' will get called asynchronously as demonstrated by the console.logs.\n// the new promise is assigned to 'thenProm',\n// and thenProm will be resolved with the value returned by handler\nconst resolvedProm = Promise.resolve(33);\nconsole.log(resolvedProm);\n\nconst thenProm = resolvedProm.then((value) => {\n  console.log(\n    `this gets called after the end of the main stack. the value received is: ${value}, the value returned is: ${\n      value + 1\n    }`,\n  );\n  return value + 1;\n});\nconsole.log(thenProm);\n\n// Using setTimeout, we can postpone the execution of a function to the moment the stack is empty\nsetTimeout(() => {\n  console.log(thenProm);\n});\n\n// Logs, in order:\n// Promise {[[PromiseStatus]]: \"resolved\", [[PromiseResult]]: 33}\n// Promise {[[PromiseStatus]]: \"pending\", [[PromiseResult]]: undefined}\n// \"this gets called after the end of the main stack. the value received is: 33, the value returned is: 34\"\n// Promise {[[PromiseStatus]]: \"resolved\", [[PromiseResult]]: 34}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.prototype.then
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
then321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then\n

\n
\n", + "global_objects/promise/catch": "

Promise.prototype.catch()

The catch() method of Promise instances schedules a function to be called when the promise is rejected. It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods. It is a shortcut for Promise.prototype.then(undefined, onRejected).

\n

Try it

\n

Syntax

\n
\n

js

\n
promiseInstance.catch(onRejected)\n
\n

Parameters

\n
onRejected

A function to asynchronously execute when this promise becomes rejected. Its return value becomes the fulfillment value of the promise returned by catch(). The function is called with the following arguments:

reason

The value that the promise was rejected with.

Return value

\n

Returns a new Promise. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled.

Description

\n
\n

The catch method is used for error handling in promise composition. Since it returns a Promise, it can be chained in the same way as its sister method, then().

If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of then(), catch(), or finally()), then the rejection event is surfaced by the host. In the browser, this results in an unhandledrejection event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another rejectionhandled event is fired.

catch() internally calls then() on the object upon which it was called, passing undefined and onRejected as arguments. The value of that call is directly returned. This is observable if you wrap the methods.

\n

js

\n
// overriding original Promise.prototype.then/catch just to add some logs\n((Promise) => {\n  const originalThen = Promise.prototype.then;\n  const originalCatch = Promise.prototype.catch;\n\n  Promise.prototype.then = function (...args) {\n    console.log(\"Called .then on %o with arguments: %o\", this, args);\n    return originalThen.apply(this, args);\n  };\n  Promise.prototype.catch = function (...args) {\n    console.error(\"Called .catch on %o with arguments: %o\", this, args);\n    return originalCatch.apply(this, args);\n  };\n})(Promise);\n\n// calling catch on an already resolved promise\nPromise.resolve().catch(function XXX() {});\n\n// Logs:\n// Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()]\n// Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()]\n
\n

This means that passing undefined still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected.

Because catch() just calls then(), it supports subclassing.

Note: The examples below are throwing instances of Error. As with synchronous throw statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces.

\n

Examples

\n

Using and chaining the catch() method

\n
\n

js

\n
const p1 = new Promise((resolve, reject) => {\n  resolve(\"Success\");\n});\n\np1.then((value) => {\n  console.log(value); // \"Success!\"\n  throw new Error(\"oh, no!\");\n})\n  .catch((e) => {\n    console.error(e.message); // \"oh, no!\"\n  })\n  .then(\n    () => console.log(\"after a catch the chain is restored\"), // \"after a catch the chain is restored\"\n    () => console.log(\"Not fired due to the catch\"),\n  );\n\n// The following behaves the same as above\np1.then((value) => {\n  console.log(value); // \"Success!\"\n  return Promise.reject(\"oh, no!\");\n})\n  .catch((e) => {\n    console.error(e); // \"oh, no!\"\n  })\n  .then(\n    () => console.log(\"after a catch the chain is restored\"), // \"after a catch the chain is restored\"\n    () => console.log(\"Not fired due to the catch\"),\n  );\n
\n

Gotchas when throwing errors

\n
\n

Throwing an error will call the catch() method most of the time:

\n

js

\n
const p1 = new Promise((resolve, reject) => {\n  throw new Error(\"Uh-oh!\");\n});\n\np1.catch((e) => {\n  console.error(e); // \"Uh-oh!\"\n});\n
\n

Errors thrown inside asynchronous functions will act like uncaught errors:

\n

js

\n
const p2 = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    throw new Error(\"Uncaught Exception!\");\n  }, 1000);\n});\n\np2.catch((e) => {\n  console.error(e); // This is never called\n});\n
\n

Errors thrown after resolve is called will be silenced:

\n

js

\n
const p3 = new Promise((resolve, reject) => {\n  resolve();\n  throw new Error(\"Silenced Exception!\");\n});\n\np3.catch((e) => {\n  console.error(e); // This is never called\n});\n
\n
\n

catch() is not called if the promise is fulfilled

\n
\n

js

\n
// Create a promise which would not call onReject\nconst p1 = Promise.resolve(\"calling next\");\n\nconst p2 = p1.catch((reason) => {\n  // This is never called\n  console.error(\"catch p1!\");\n  console.error(reason);\n});\n\np2.then(\n  (value) => {\n    console.log(\"next promise's onFulfilled\");\n    console.log(value); // calling next\n  },\n  (reason) => {\n    console.log(\"next promise's onRejected\");\n    console.log(reason);\n  },\n);\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.prototype.catch
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
catch321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch\n

\n
\n", + "global_objects/promise/finally": "

Promise.prototype.finally()

\n

The finally() method of Promise instances schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods.

This lets you avoid duplicating code in both the promise's then() and catch() handlers.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
promiseInstance.finally(onFinally)\n
\n

Parameters

\n
onFinally

A function to asynchronously execute when this promise becomes settled. Its return value is ignored unless the returned value is a rejected promise. The function is called with no arguments.

Return value

\n

Returns an equivalent Promise. If the handler throws an error or returns a rejected promise, the promise returned by finally() will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise.

Description

\n
\n

The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

The finally() method is very similar to calling then(onFinally, onFinally). However, there are a couple of differences:

Note: A throw (or returning a rejected promise) in the finally callback still rejects the returned promise. For example, both Promise.reject(3).finally(() => { throw 99; }) and Promise.reject(3).finally(() => Promise.reject(99)) reject the returned promise with the reason 99.

Like catch(), finally() internally calls the then method on the object upon which it was called. If onFinally is not a function, then() is called with onFinally as both arguments — which, for Promise.prototype.then(), means that no useful handler is attached. Otherwise, then() is called with two internally created functions, which behave like the following:

Warning: This is only for demonstration purposes and is not a polyfill.

\n

js

\n
promise.then(\n  (value) => Promise.resolve(onFinally()).then(() => value),\n  (reason) =>\n    Promise.resolve(onFinally()).then(() => {\n      throw reason;\n    }),\n);\n
\n

Because finally() calls then(), it supports subclassing. Moreover, notice the Promise.resolve() call above — in reality, onFinally()'s return value is resolved using the same algorithm as Promise.resolve(), but the actual constructor used to construct the resolved promise will be the subclass. finally() gets this constructor through promise.constructor[@@species].

\n

Examples

\n

Using finally()

\n
\n

js

\n
let isLoading = true;\n\nfetch(myRequest)\n  .then((response) => {\n    const contentType = response.headers.get(\"content-type\");\n    if (contentType && contentType.includes(\"application/json\")) {\n      return response.json();\n    }\n    throw new TypeError(\"Oops, we haven't got JSON!\");\n  })\n  .then((json) => {\n    /* process your JSON further */\n  })\n  .catch((error) => {\n    console.error(error); // this line can also throw, e.g. when console = {}\n  })\n  .finally(() => {\n    isLoading = false;\n  });\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.prototype.finally
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
finally631858No5011.16363584611.38.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally\n

\n
\n", + "global_objects/promise/resolve": "

Promise.resolve()

\n

The Promise.resolve() static method \"resolves\" a given value to a Promise. If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.resolve(value)\n
\n

Parameters

\n
value

Argument to be resolved by this Promise. Can also be a Promise or a thenable to resolve.

Return value

\n

A Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states — fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise.

Description

\n
\n

Promise.resolve() resolves a promise, which is not the same as fulfilling or rejecting the promise. See Promise description for definitions of the terminology. In brief, Promise.resolve() returns a promise whose eventual state depends on another promise, thenable object, or other value.

Promise.resolve() is generic and supports subclassing, which means it can be called on subclasses of Promise, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the Promise() constructor — accepting a single executor function that can be called with the resolve and reject callbacks as parameters.

Promise.resolve() special-cases native Promise instances. If value belongs to Promise or a subclass, and value.constructor === Promise, then value is directly returned by Promise.resolve(), without creating a new Promise instance. Otherwise, Promise.resolve() is essentially a shorthand for new Promise((resolve) => resolve(value)).

The bulk of the resolving logic is actually implemented by the resolver function passed by the Promise() constructor. In summary:

\n

Examples

\n

Using the static Promise.resolve method

\n
\n

js

\n
Promise.resolve(\"Success\").then(\n  (value) => {\n    console.log(value); // \"Success\"\n  },\n  (reason) => {\n    // not called\n  },\n);\n
\n

Resolving an array

\n
\n

js

\n
const p = Promise.resolve([1, 2, 3]);\np.then((v) => {\n  console.log(v[0]); // 1\n});\n
\n

Resolving another Promise

\n
\n

Promise.resolve() reuses existing Promise instances. If it's resolving a native promise, it returns the same promise instance without creating a wrapper.

\n

js

\n
const original = Promise.resolve(33);\nconst cast = Promise.resolve(original);\ncast.then((value) => {\n  console.log(`value: ${value}`);\n});\nconsole.log(`original === cast ? ${original === cast}`);\n\n// Logs, in order:\n// original === cast ? true\n// value: 33\n
\n

The inverted order of the logs is due to the fact that the then handlers are called asynchronously. See the then() reference for more information.

\n

Resolving thenables and throwing Errors

\n
\n
\n

js

\n
// Resolving a thenable object\nconst p1 = Promise.resolve({\n  then(onFulfill, onReject) {\n    onFulfill(\"fulfilled!\");\n  },\n});\nconsole.log(p1 instanceof Promise); // true, object casted to a Promise\n\np1.then(\n  (v) => {\n    console.log(v); // \"fulfilled!\"\n  },\n  (e) => {\n    // not called\n  },\n);\n\n// Thenable throws\n// Promise rejects\nconst p2 = Promise.resolve({\n  then() {\n    throw new TypeError(\"Throwing\");\n  },\n});\np2.then(\n  (v) => {\n    // not called\n  },\n  (e) => {\n    console.error(e); // TypeError: Throwing\n  },\n);\n\n// Thenable throws after callback\n// Promise resolves\nconst p3 = Promise.resolve({\n  then(onFulfilled) {\n    onFulfilled(\"Resolving\");\n    throw new TypeError(\"Throwing\");\n  },\n});\np3.then(\n  (v) => {\n    console.log(v); // \"Resolving\"\n  },\n  (e) => {\n    // not called\n  },\n);\n
\n

Nested thenables will be \"deeply flattened\" to a single promise.

\n

js

\n
const thenable = {\n  then(onFulfilled, onRejected) {\n    onFulfilled({\n      // The thenable is fulfilled with another thenable\n      then(onFulfilled, onRejected) {\n        onFulfilled(42);\n      },\n    });\n  },\n};\n\nPromise.resolve(thenable).then((v) => {\n  console.log(v); // 42\n});\n
\n

Warning: Do not call Promise.resolve() on a thenable that resolves to itself. That leads to infinite recursion, because it attempts to flatten an infinitely-nested promise.

\n

js

\n
const thenable = {\n  then(onFulfilled, onRejected) {\n    onFulfilled(thenable);\n  },\n};\n\nPromise.resolve(thenable); // Will lead to infinite recursion.\n
\n
\n

Calling resolve() on a non-Promise constructor

\n
\n

Promise.resolve() is a generic method. It can be called on any constructor that implements the same signature as the Promise() constructor. For example, we can call it on a constructor that passes it console.log as resolve:

\n

js

\n
class NotPromise {\n  constructor(executor) {\n    // The \"resolve\" and \"reject\" functions behave nothing like the\n    // native promise's, but Promise.resolve() calls them in the same way.\n    executor(\n      (value) => console.log(\"Resolved\", value),\n      (reason) => console.log(\"Rejected\", reason),\n    );\n  }\n}\n\nPromise.resolve.call(NotPromise, \"foo\"); // Logs \"Resolved foo\"\n
\n

The ability to flatten nested thenables is implemented by the resolver function of the Promise() constructor, so if you call it on another constructor, nested thenables may not be flattened, depending on how that constructor implements its resolver.

\n

js

\n
const thenable = {\n  then(onFulfilled, onRejected) {\n    onFulfilled({\n      // The thenable is fulfilled with another thenable\n      then(onFulfilled, onRejected) {\n        onFulfilled(42);\n      },\n    });\n  },\n};\n\nPromise.resolve.call(NotPromise, thenable); // Logs \"Resolved { then: [Function: then] }\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.resolve
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolve321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve\n

\n
\n", + "global_objects/promise/all": "

Promise.all()

The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.

\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.all(iterable)\n
\n

Parameters

\n
iterable

An iterable (such as an Array) of promises.

Return value

\n
\n

A Promise that is:

\n

Description

\n
\n

The Promise.all() method is one of the promise concurrency methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues.

Promise.all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled() will wait for all input promises to complete, regardless of whether or not one rejects. Use allSettled() if you need the final result of every promise in the input iterable.

\n

Examples

\n

Using Promise.all()

\n
\n

Promise.all waits for all fulfillments (or the first rejection).

\n

js

\n
const p1 = Promise.resolve(3);\nconst p2 = 1337;\nconst p3 = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve(\"foo\");\n  }, 100);\n});\n\nPromise.all([p1, p2, p3]).then((values) => {\n  console.log(values); // [3, 1337, \"foo\"]\n});\n
\n

If the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):

\n

js

\n
// All values are non-promises, so the returned promise gets fulfilled\nconst p = Promise.all([1, 2, 3]);\n// The only input promise is already fulfilled,\n// so the returned promise gets fulfilled\nconst p2 = Promise.all([1, 2, 3, Promise.resolve(444)]);\n// One (and the only) input promise is rejected,\n// so the returned promise gets rejected\nconst p3 = Promise.all([1, 2, 3, Promise.reject(555)]);\n\n// Using setTimeout, we can execute code after the queue is empty\nsetTimeout(() => {\n  console.log(p);\n  console.log(p2);\n  console.log(p3);\n});\n\n// Logs:\n// Promise { <state>: \"fulfilled\", <value>: Array[3] }\n// Promise { <state>: \"fulfilled\", <value>: Array[4] }\n// Promise { <state>: \"rejected\", <reason>: 555 }\n
\n
\n

Asynchronicity or synchronicity of Promise.all

\n
\n

This following example demonstrates the asynchronicity of Promise.all when a non-empty iterable is passed:

\n

js

\n
// Passing an array of promises that are already resolved,\n// to trigger Promise.all as soon as possible\nconst resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];\n\nconst p = Promise.all(resolvedPromisesArray);\n// Immediately logging the value of p\nconsole.log(p);\n\n// Using setTimeout, we can execute code after the queue is empty\nsetTimeout(() => {\n  console.log(\"the queue is now empty\");\n  console.log(p);\n});\n\n// Logs, in order:\n// Promise { <state>: \"pending\" }\n// the queue is now empty\n// Promise { <state>: \"fulfilled\", <value>: Array[2] }\n
\n

The same thing happens if Promise.all rejects:

\n

js

\n
const mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];\nconst p = Promise.all(mixedPromisesArray);\nconsole.log(p);\nsetTimeout(() => {\n  console.log(\"the queue is now empty\");\n  console.log(p);\n});\n\n// Logs:\n// Promise { <state>: \"pending\" }\n// the queue is now empty\n// Promise { <state>: \"rejected\", <reason>: 44 }\n
\n

Promise.all resolves synchronously if and only if the iterable passed is empty:

\n

js

\n
const p = Promise.all([]); // Will be immediately resolved\nconst p2 = Promise.all([1337, \"hi\"]); // Non-promise values are ignored, but the evaluation is done asynchronously\nconsole.log(p);\nconsole.log(p2);\nsetTimeout(() => {\n  console.log(\"the queue is now empty\");\n  console.log(p2);\n});\n\n// Logs:\n// Promise { <state>: \"fulfilled\", <value>: Array[0] }\n// Promise { <state>: \"pending\" }\n// the queue is now empty\n// Promise { <state>: \"fulfilled\", <value>: Array[2] }\n
\n
\n

Using Promise.all() with async functions

\n
\n

Within async functions, it's very common to \"over-await\" your code. For example, given the following functions:

\n

js

\n
function promptForDishChoice() {\n  return new Promise((resolve, reject) => {\n    const dialog = document.createElement(\"dialog\");\n    dialog.innerHTML = `\n<form method=\"dialog\">\n  <p>What would you like to eat?</p>\n  <select>\n    <option value=\"pizza\">Pizza</option>\n    <option value=\"pasta\">Pasta</option>\n    <option value=\"salad\">Salad</option>\n  </select>\n  <menu>\n    <li><button value=\"cancel\">Cancel</button></li>\n    <li><button type=\"submit\" value=\"ok\">OK</button></li>\n  </menu>\n</form>\n    `;\n    dialog.addEventListener(\"close\", () => {\n      if (dialog.returnValue === \"ok\") {\n        resolve(dialog.querySelector(\"select\").value);\n      } else {\n        reject(new Error(\"User cancelled dialog\"));\n      }\n    });\n    document.body.appendChild(dialog);\n    dialog.showModal();\n  });\n}\n\nasync function fetchPrices() {\n  const response = await fetch(\"/prices\");\n  return await response.json();\n}\n
\n

You may write a function like this:

\n

js

\n
async function getPrice() {\n  const choice = await promptForDishChoice();\n  const prices = await fetchPrices();\n  return prices[choice];\n}\n
\n

However, note that the execution of promptForDishChoice and fetchPrices don't depend on the result of each other. While the user is choosing their dish, it's fine for the prices to be fetched in the background, but in the code above, the await operator causes the async function to pause until the choice is made, and then again until the prices are fetched. We can use Promise.all to run them concurrently, so that the user doesn't have to wait for the prices to be fetched before the result is given:

\n

js

\n
async function getPrice() {\n  const [choice, prices] = await Promise.all([\n    promptForDishChoice(),\n    fetchPrices(),\n  ]);\n  return prices[choice];\n}\n
\n

Promise.all is the best choice of concurrency method here, because error handling is intuitive — if any of the promises reject, the result is no longer available, so the whole await expression throws.

Promise.all accepts an iterable of promises, so if you are using it to run several async functions concurrently, you need to call the async functions and use the returned promises. Directly passing the functions to Promise.all does not work, since they are not promises.

\n

js

\n
async function getPrice() {\n  const [choice, prices] = await Promise.all([\n    promptForDishChoice,\n    fetchPrices,\n  ]);\n  // `choice` and `prices` are still the original async functions;\n  // Promise.all() does nothing to non-promises\n}\n
\n
\n

Promise.all fail-fast behavior

\n
\n

Promise.all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

\n

js

\n
const p1 = new Promise((resolve, reject) => {\n  setTimeout(() => resolve(\"one\"), 1000);\n});\nconst p2 = new Promise((resolve, reject) => {\n  setTimeout(() => resolve(\"two\"), 2000);\n});\nconst p3 = new Promise((resolve, reject) => {\n  setTimeout(() => resolve(\"three\"), 3000);\n});\nconst p4 = new Promise((resolve, reject) => {\n  setTimeout(() => resolve(\"four\"), 4000);\n});\nconst p5 = new Promise((resolve, reject) => {\n  reject(new Error(\"reject\"));\n});\n\n// Using .catch:\nPromise.all([p1, p2, p3, p4, p5])\n  .then((values) => {\n    console.log(values);\n  })\n  .catch((error) => {\n    console.error(error.message);\n  });\n\n// Logs:\n// \"reject\"\n
\n

It is possible to change this behavior by handling possible rejections:

\n

js

\n
const p1 = new Promise((resolve, reject) => {\n  setTimeout(() => resolve(\"p1_delayed_resolution\"), 1000);\n});\n\nconst p2 = new Promise((resolve, reject) => {\n  reject(new Error(\"p2_immediate_rejection\"));\n});\n\nPromise.all([p1.catch((error) => error), p2.catch((error) => error)]).then(\n  (values) => {\n    console.log(values[0]); // \"p1_delayed_resolution\"\n    console.error(values[1]); // \"Error: p2_immediate_rejection\"\n  },\n);\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.all
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
all321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\n

\n
\n", + "global_objects/promise/allsettled": "

Promise.allSettled()

The Promise.allSettled() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.allSettled(iterable)\n
\n

Parameters

\n
iterable

An iterable (such as an Array) of promises.

Return value

\n
\n

A Promise that is:

\n

Description

\n
\n

The Promise.allSettled() method is one of the promise concurrency methods. Promise.allSettled() is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.

In comparison, the Promise returned by Promise.all() may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting.

\n

Examples

\n

Using Promise.allSettled()

\n
\n

js

\n
Promise.allSettled([\n  Promise.resolve(33),\n  new Promise((resolve) => setTimeout(() => resolve(66), 0)),\n  99,\n  Promise.reject(new Error(\"an error\")),\n]).then((values) => console.log(values));\n\n// [\n//   { status: 'fulfilled', value: 33 },\n//   { status: 'fulfilled', value: 66 },\n//   { status: 'fulfilled', value: 99 },\n//   { status: 'rejected', reason: Error: an error }\n// ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.allsettled
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
allSettled767971No6313767679541312.01.012.9.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled\n

\n
\n", + "global_objects/promise/race": "

Promise.race()

The Promise.race() static method takes an iterable of promises as input and returns a single Promise. This returned promise settles with the eventual state of the first promise that settles.

\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.race(iterable)\n
\n

Parameters

\n
iterable

An iterable (such as an Array) of promises.

Return value

\n

A Promise that asynchronously settles with the eventual state of the first promise in the iterable to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the iterable passed is empty. If the iterable passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled.

Description

\n
\n

The Promise.race() method is one of the promise concurrency methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail).

If the iterable contains one or more non-promise values and/or an already settled promise, then Promise.race() will settle to the first of these values found in the iterable.

\n

Examples

\n

Using Promise.race()

\n
\n

This example shows how Promise.race() can be used to race several timers implemented with setTimeout(). The timer with the shortest time always wins the race and becomes the resulting promise's state.

\n

js

\n
function sleep(time, value, state) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      if (state === \"fulfill\") {\n        return resolve(value);\n      } else {\n        return reject(new Error(value));\n      }\n    }, time);\n  });\n}\n\nconst p1 = sleep(500, \"one\", \"fulfill\");\nconst p2 = sleep(100, \"two\", \"fulfill\");\n\nPromise.race([p1, p2]).then((value) => {\n  console.log(value); // \"two\"\n  // Both fulfill, but p2 is faster\n});\n\nconst p3 = sleep(100, \"three\", \"fulfill\");\nconst p4 = sleep(500, \"four\", \"reject\");\n\nPromise.race([p3, p4]).then(\n  (value) => {\n    console.log(value); // \"three\"\n    // p3 is faster, so it fulfills\n  },\n  (error) => {\n    // Not called\n  },\n);\n\nconst p5 = sleep(500, \"five\", \"fulfill\");\nconst p6 = sleep(100, \"six\", \"reject\");\n\nPromise.race([p5, p6]).then(\n  (value) => {\n    // Not called\n  },\n  (error) => {\n    console.error(error.message); // \"six\"\n    // p6 is faster, so it rejects\n  },\n);\n
\n
\n

Asynchronicity of Promise.race

\n
\n

This following example demonstrates the asynchronicity of Promise.race. Unlike other promise concurrency methods, Promise.race is always asynchronous: it never settles synchronously, even when the iterable is empty.

\n

js

\n
// Passing an array of promises that are already resolved,\n// to trigger Promise.race as soon as possible\nconst resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];\n\nconst p = Promise.race(resolvedPromisesArray);\n// Immediately logging the value of p\nconsole.log(p);\n\n// Using setTimeout, we can execute code after the stack is empty\nsetTimeout(() => {\n  console.log(\"the stack is now empty\");\n  console.log(p);\n});\n\n// Logs, in order:\n// Promise { <state>: \"pending\" }\n// the stack is now empty\n// Promise { <state>: \"fulfilled\", <value>: 33 }\n
\n

An empty iterable causes the returned promise to be forever pending:

\n

js

\n
const foreverPendingPromise = Promise.race([]);\nconsole.log(foreverPendingPromise);\nsetTimeout(() => {\n  console.log(\"the stack is now empty\");\n  console.log(foreverPendingPromise);\n});\n\n// Logs, in order:\n// Promise { <state>: \"pending\" }\n// the stack is now empty\n// Promise { <state>: \"pending\" }\n
\n

If the iterable contains one or more non-promise value and/or an already settled promise, then Promise.race will settle to the first of these values found in the array:

\n

js

\n
const foreverPendingPromise = Promise.race([]);\nconst alreadyFulfilledProm = Promise.resolve(100);\n\nconst arr = [foreverPendingPromise, alreadyFulfilledProm, \"non-Promise value\"];\nconst arr2 = [foreverPendingPromise, \"non-Promise value\", Promise.resolve(100)];\nconst p = Promise.race(arr);\nconst p2 = Promise.race(arr2);\n\nconsole.log(p);\nconsole.log(p2);\nsetTimeout(() => {\n  console.log(\"the stack is now empty\");\n  console.log(p);\n  console.log(p2);\n});\n\n// Logs, in order:\n// Promise { <state>: \"pending\" }\n// Promise { <state>: \"pending\" }\n// the stack is now empty\n// Promise { <state>: \"fulfilled\", <value>: 100 }\n// Promise { <state>: \"fulfilled\", <value>: \"non-Promise value\" }\n
\n
\n

Using Promise.race() to implement request timeout

\n
\n

You can race a potentially long-lasting request with a timer that rejects, so that when the time limit has elapsed, the resulting promise automatically rejects.

\n

js

\n
const data = Promise.race([\n  fetch(\"/api\"),\n  new Promise((resolve, reject) => {\n    // Reject after 5 seconds\n    setTimeout(() => reject(new Error(\"Request timed out\")), 5000);\n  }),\n])\n  .then((res) => res.json())\n  .catch((err) => displayError(err));\n
\n

If the data promise fulfills, it will contain the data fetched from /api; otherwise, it will reject if fetch remains pending for 5 seconds and loses the race with the setTimeout timer.

\n

Using Promise.race() to detect the status of a promise

\n
\n

Because Promise.race() resolves to the first non-pending promise in the iterable, we can check a promise's state, including if it's pending. This example is adapted from promise-status-async.

\n

js

\n
function promiseState(promise) {\n  const pendingState = { status: \"pending\" };\n\n  return Promise.race([promise, pendingState]).then(\n    (value) =>\n      value === pendingState ? value : { status: \"fulfilled\", value },\n    (reason) => ({ status: \"rejected\", reason }),\n  );\n}\n
\n

In this function, if promise is pending, the second value, pendingState, which is a non-promise, becomes the result of the race; otherwise, if promise is already settled, we may know its state through the onFulfilled and onRejected handlers. For example:

\n

js

\n
const p1 = new Promise((res) => setTimeout(() => res(100), 100));\nconst p2 = new Promise((res) => setTimeout(() => res(200), 200));\nconst p3 = new Promise((res, rej) => setTimeout(() => rej(300), 100));\n\nasync function getStates() {\n  console.log(await promiseState(p1));\n  console.log(await promiseState(p2));\n  console.log(await promiseState(p3));\n}\n\nconsole.log(\"Immediately after initiation:\");\ngetStates();\nsetTimeout(() => {\n  console.log(\"After waiting for 100ms:\");\n  getStates();\n}, 100);\n\n// Logs:\n// Immediately after initiation:\n// { status: 'pending' }\n// { status: 'pending' }\n// { status: 'pending' }\n// After waiting for 100ms:\n// { status: 'fulfilled', value: 100 }\n// { status: 'pending' }\n// { status: 'rejected', reason: 300 }\n
\n

Note: The promiseState function still runs asynchronously, because there is no way to synchronously get a promise's value (i.e. without then() or await), even when it is already settled. However, promiseState() always fulfills within one tick and never actually waits for any promise's settlement.

\n

Comparison with Promise.any()

\n
\n

Promise.race takes the first settled Promise.

\n

js

\n
const promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 500, \"one\");\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(reject, 100, \"two\");\n});\n\nPromise.race([promise1, promise2])\n  .then((value) => {\n    console.log(\"succeeded with value:\", value);\n  })\n  .catch((reason) => {\n    // Only promise1 is fulfilled, but promise2 is faster\n    console.error(\"failed with reason:\", reason);\n  });\n// failed with reason: two\n
\n

Promise.any takes the first fulfilled Promise.

\n

js

\n
const promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 500, \"one\");\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(reject, 100, \"two\");\n});\n\nPromise.any([promise1, promise2])\n  .then((value) => {\n    // Only promise1 is fulfilled, even though promise2 settled sooner\n    console.log(\"succeeded with value:\", value);\n  })\n  .catch((reason) => {\n    console.error(\"failed with reason:\", reason);\n  });\n// succeeded with value: one\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.race
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
race321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race\n

\n
\n", + "global_objects/promise/promise": "

Promise() constructor

The Promise() constructor creates Promise objects. It is primarily used to wrap callback-based APIs that do not already support promises.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Promise(executor)\n
\n

Note: Promise() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
executor

A function to be executed by the constructor. It receives two functions as parameters: resolveFunc and rejectFunc. Any errors thrown in the executor will cause the promise to be rejected, and the return value will be neglected. The semantics of executor are detailed below.

Return value

\n

When called via new, the Promise constructor returns a promise object. The promise object will become resolved when either of the functions resolveFunc or rejectFunc are invoked. Note that if you call resolveFunc or rejectFunc and pass another Promise object as an argument, it can be said to be \"resolved\", but still not \"settled\". See the Promise description for more explanation.

Description

\n
\n

Traditionally (before promises), asynchronous tasks were designed as callbacks.

\n

js

\n
readFile(\"./data.txt\", (error, result) => {\n  // This callback will be called when the task is done, with the\n  // final `error` or `result`. Any operation dependent on the\n  // result must be defined within this callback.\n});\n// Code here is immediately executed after the `readFile` request\n// is fired. It does not wait for the callback to be called, hence\n// making `readFile` \"asynchronous\".\n
\n

To take advantage of the readability improvement and language features offered by promises, the Promise() constructor allows one to transform the callback-based API to a promise-based one.

Note: If your task is already promise-based, you likely do not need the Promise() constructor.

The executor is custom code that ties an outcome in a callback to a promise. You, the programmer, write the executor. Its signature is expected to be:

\n

js

\n
function executor(resolveFunc, rejectFunc) {\n  // Typically, some asynchronous operation that accepts a callback,\n  // like the `readFile` function above\n}\n
\n

resolveFunc and rejectFunc are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type.

\n

js

\n
resolveFunc(value); // call on resolved\nrejectFunc(reason); // call on rejected\n
\n

The value parameter passed to resolveFunc can be another promise object, in which case the newly constructed promise's state will be \"locked in\" to the promise passed (as part of the resolution promise). The rejectFunc has semantics close to the throw statement, so reason is typically an Error instance. If either value or reason is omitted, the promise is fulfilled/rejected with undefined.

The executor's completion state has limited effect on the promise's state:

Note: The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending).

Here's a summary of the typical flow:

  1. At the time when the constructor generates the new Promise object, it also generates a corresponding pair of functions for resolveFunc and rejectFunc; these are \"tethered\" to the Promise object.
  2. \nexecutor typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the executor code, so it has access to the resolveFunc and rejectFunc.
  3. The executor is called synchronously (as soon as the Promise is constructed) with the resolveFunc and rejectFunc functions as arguments.
  4. The code within the executor has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by resolveFunc or rejectFunc. The side effect is that the Promise object becomes \"resolved\".
    • If resolveFunc is called first, the value passed will be resolved. The promise may stay pending (in case another thenable is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value).
    • If rejectFunc is called first, the promise instantly becomes rejected.
    • Once one of the resolving functions (resolveFunc or rejectFunc) is called, the promise stays resolved. Only the first call to resolveFunc or rejectFunc affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from \"fulfilled\" to \"rejected\" or opposite.
    • If executor exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved).
    • Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable.
  5. Once the promise settles, it (asynchronously) invokes any further handlers associated through then(), catch(), or finally(). The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see Chained Promises).

For example, the callback-based readFile API above can be transformed into a promise-based one.

\n

js

\n
const readFilePromise = (path) =>\n  new Promise((resolve, reject) => {\n    readFile(path, (error, result) => {\n      if (error) {\n        reject(error);\n      } else {\n        resolve(result);\n      }\n    });\n  });\n\nreadFilePromise(\"./data.txt\")\n  .then((result) => console.log(result))\n  .catch((error) => console.error(\"Failed to read data\"));\n
\n
\n

Resolver function

\n
\n

The resolver function resolveFunc has the following behaviors:

In the last case, it means code like:

\n

js

\n
new Promise((resolve, reject) => {\n  resolve(thenable);\n});\n
\n

Is roughly equivalent to:

\n

js

\n
new Promise((resolve, reject) => {\n  try {\n    thenable.then(\n      (value) => resolve(value),\n      (reason) => reject(reason),\n    );\n  } catch (e) {\n    reject(e);\n  }\n});\n
\n

Except that in the resolve(thenable) case:

  1. \nresolve is called synchronously, so that calling resolve or reject again has no effect, even when the handlers attached through anotherPromise.then() are not called yet.
  2. The then method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed.

Because resolve is called again with whatever thenable.then() passes to it as value, the resolver function is able to flatten nested thenables, where a thenable calls its onFulfilled handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value.

\n

Examples

\n

Turning a callback-based API into a promise-based one

\n
\n

To provide a function with promise functionality, have it return a promise by calling the resolve and reject functions at the correct times.

\n

js

\n
function myAsyncFunction(url) {\n  return new Promise((resolve, reject) => {\n    const xhr = new XMLHttpRequest();\n    xhr.open(\"GET\", url);\n    xhr.onload = () => resolve(xhr.responseText);\n    xhr.onerror = () => reject(xhr.statusText);\n    xhr.send();\n  });\n}\n
\n
\n

Effect of calling resolveFunc

\n
\n

Calling resolveFunc causes the promise to become resolved, so that calling resolveFunc or rejectFunc again has no effect. However, the promise may be in any of the states: pending, fulfilled, or rejected.

This pendingResolved promise is resolved the time it's created, because it has already been \"locked in\" to match the eventual state of the inner promise, and calling resolveOuter or rejectOuter or throwing an error later in the executor has no effect on its eventual state. However, the inner promise is still pending until 100ms later, so the outer promise is also pending:

\n

js

\n
const pendingResolved = new Promise((resolveOuter, rejectOuter) => {\n  resolveOuter(\n    new Promise((resolveInner) => {\n      setTimeout(() => {\n        resolveInner(\"inner\");\n      }, 100);\n    }),\n  );\n});\n
\n

This fulfilledResolved promise becomes fulfilled the moment it's resolved, because it's resolved with a non-thenable value. However, when it's created, it's unresolved, because neither resolve nor reject has been called yet. An unresolved promise is necessarily pending:

\n

js

\n
const fulfilledResolved = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve(\"outer\");\n  }, 100);\n});\n
\n

Calling rejectFunc obviously causes the promise to reject. However, there are also two ways to cause the promise to instantly become rejected even when the resolveFunc callback is called.

\n

js

\n
// 1. Resolving with the promise itself\nconst rejectedResolved1 = new Promise((resolve) => {\n  // Note: resolve has to be called asynchronously,\n  // so that the rejectedResolved1 variable is initialized\n  setTimeout(() => resolve(rejectedResolved1)); // TypeError: Chaining cycle detected for promise #<Promise>\n});\n\n// 2. Resolving with an object which throws when accessing the `then` property\nconst rejectedResolved2 = new Promise((resolve) => {\n  resolve({\n    get then() {\n      throw new Error(\"Can't get then property\");\n    },\n  });\n});\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Promise3212
29Constructor requires a new operator since version 37.
No19
8Constructor requires a new operator since version 10.
4.4.332
29Constructor requires a new operator since version 37.
19
8Constructor requires a new operator since version 10.
2.01.0
0.12.0Constructor requires a new operator since version 4.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise\n

\n
\n", + "global_objects/promise/@@species": "

Promise[@@species]

\n

The Promise[@@species] static accessor property returns the constructor used to construct return values from promise methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Syntax

\n
\n

js

\n
Promise[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct return values from promise chaining methods that create new promises.

Description

\n
\n

The @@species accessor property returns the default constructor for Promise objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass Promise {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubPromise extends Promise {}\nSubPromise[Symbol.species] === SubPromise; // true\n
\n

Promise chaining methods — then(), catch(), and finally() — return new promise objects. They get the constructor to construct the new promise through this.constructor[@@species]. If this.constructor is undefined, or if this.constructor[@@species] is undefined or null, the default Promise() constructor is used. Otherwise, the constructor returned by this.constructor[@@species] is used to construct the new promise object.

\n

Examples

\n

Species in ordinary objects

\n
\n

The Symbol.species property returns the default constructor function, which is the Promise constructor for Promise.

\n

js

\n
Promise[Symbol.species]; // [Function: Promise]\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom Promise subclass, such as MyPromise, the MyPromise species is the MyPromise constructor. However, you might want to override this, in order to return parent Promise objects in your derived class methods.

\n

js

\n
class MyPromise extends Promise {\n  // Override MyPromise species to the parent Promise constructor\n  static get [Symbol.species]() {\n    return Promise;\n  }\n}\n
\n

By default, promise methods would return promises with the type of the subclass.

\n

js

\n
class MyPromise extends Promise {\n  someValue = 1;\n}\n\nconsole.log(MyPromise.resolve(1).then(() => {}).someValue); // 1\n
\n

By overriding @@species, the promise methods will return the base Promise type.

\n

js

\n
class MyPromise extends Promise {\n  someValue = 1;\n  static get [Symbol.species]() {\n    return Promise;\n  }\n}\n\nconsole.log(MyPromise.resolve(1).then(() => {}).someValue); // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-promise-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species517948No381051514841105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/@@species\n

\n
\n", + "global_objects/promise/reject": "

Promise.reject()

The Promise.reject() static method returns a Promise object that is rejected with a given reason.

\n

Try it

\n

Syntax

\n
\n

js

\n
Promise.reject(reason)\n
\n

Parameters

\n
reason

Reason why this Promise rejected.

Return value

\n

A Promise that is rejected with the given reason.

Description

\n
\n

The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.

Promise.reject() is generic and supports subclassing, which means it can be called on subclasses of Promise, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the Promise() constructor — accepting a single executor function that can be called with the resolve and reject callbacks as parameters. Promise.reject() is essentially a shorthand for new Promise((resolve, reject) => reject(reason)).

Unlike Promise.resolve(), Promise.reject() always wraps reason in a new Promise object, even when reason is already a Promise.

\n

Examples

\n

Using the static Promise.reject() method

\n
\n

js

\n
Promise.reject(new Error(\"fail\")).then(\n  () => {\n    // not called\n  },\n  (error) => {\n    console.error(error); // Stacktrace\n  },\n);\n
\n

Rejecting with a promise

\n
\n

Unlike Promise.resolve, the Promise.reject method does not reuse existing Promise instances. It always returns a new Promise instance that wraps reason.

\n

js

\n
const p = Promise.resolve(1);\nconst rejected = Promise.reject(p);\nconsole.log(rejected === p); // false\nrejected.catch((v) => {\n  console.log(v === p); // true\n});\n
\n
\n

Calling reject() on a non-Promise constructor

\n
\n

Promise.reject() is a generic method. It can be called on any constructor that implements the same signature as the Promise() constructor. For example, we can call it on a constructor that passes it console.log as reject:

\n

js

\n
class NotPromise {\n  constructor(executor) {\n    // The \"resolve\" and \"reject\" functions behave nothing like the\n    // native promise's, but Promise.reject() calls them in the same way.\n    executor(\n      (value) => console.log(\"Resolved\", value),\n      (reason) => console.log(\"Rejected\", reason),\n    );\n  }\n}\n\nPromise.reject.call(NotPromise, \"foo\"); // Logs \"Rejected foo\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-promise.reject
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reject321229No1984.4.332291982.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject\n

\n
\n", + "global_objects/generatorfunction/generatorfunction": "

GeneratorFunction() constructor

\n

The GeneratorFunction() constructor creates GeneratorFunction objects.

Note that GeneratorFunction is not a global object. It can be obtained with the following code:

\n

js

\n
const GeneratorFunction = function* () {}.constructor;\n
\n

The GeneratorFunction() constructor is not intended to be used directly, and all caveats mentioned in the Function() description apply to GeneratorFunction().

\n
\n

Syntax

\n
\n
\n

js

\n
new GeneratorFunction(functionBody)\nnew GeneratorFunction(arg1, functionBody)\nnew GeneratorFunction(arg1, arg2, functionBody)\nnew GeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)\n\nGeneratorFunction(functionBody)\nGeneratorFunction(arg1, functionBody)\nGeneratorFunction(arg1, arg2, functionBody)\nGeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)\n
\n

Note: GeneratorFunction() can be called with or without new. Both create a new GeneratorFunction instance.

\n

Parameters

\n

See Function().

Examples

\n

Creating and using a GeneratorFunction() constructor

\n
\n

js

\n
const GeneratorFunction = function* () {}.constructor;\nconst g = new GeneratorFunction(\"a\", \"yield a * 2\");\nconst iterator = g(10);\nconsole.log(iterator.next().value); // 20\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generatorfunction-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
GeneratorFunction391326No261039392626104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction/GeneratorFunction\n

\n
\n", + "global_objects/asyncgeneratorfunction/asyncgeneratorfunction": "

AsyncGeneratorFunction() constructor

\n

The AsyncGeneratorFunction() constructor creates AsyncGeneratorFunction objects.

Note that AsyncGeneratorFunction is not a global object. It could be obtained by evaluating the following code.

\n

js

\n
const AsyncGeneratorFunction = async function* () {}.constructor;\n
\n

The AsyncGeneratorFunction() constructor is not intended to be used directly, and all caveats mentioned in the Function() description apply to AsyncGeneratorFunction().

\n
\n

Syntax

\n
\n
\n

js

\n
new AsyncGeneratorFunction(functionBody)\nnew AsyncGeneratorFunction(arg1, functionBody)\nnew AsyncGeneratorFunction(arg1, arg2, functionBody)\nnew AsyncGeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)\n\nAsyncGeneratorFunction(functionBody)\nAsyncGeneratorFunction(arg1, functionBody)\nAsyncGeneratorFunction(arg1, arg2, functionBody)\nAsyncGeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)\n
\n

Note: AsyncGeneratorFunction() can be called with or without new. Both create a new AsyncGeneratorFunction instance.

\n

Parameters

\n

See Function().

Examples

\n

Using the constructor

\n
\n

The following example uses the AsyncGeneratorFunction constructor to create an async generator function.

\n

js

\n
const AsyncGeneratorFunction = async function* () {}.constructor;\nconst createAsyncGenerator = new AsyncGeneratorFunction(\"a\", \"yield a * 2\");\nconst asyncGen = createAsyncGenerator(10);\nasyncGen.next().then((res) => console.log(res.value)); // 20\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgeneratorfunction-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AsyncGeneratorFunction637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction/AsyncGeneratorFunction\n

\n
\n", + "global_objects/generator/next": "

Generator.prototype.next()

The next() method of Generator instances returns an object with two properties done and value. You can also provide a parameter to the next method to send a value to the generator.

\n

Syntax

\n
\n

js

\n
next()\nnext(value)\n
\n

Parameters

\n
\nvalue Optional\n

The value to send to the generator.

The value will be assigned as a result of a yield expression. For example, in variable = yield expression, the value passed to the .next() function will be assigned to variable.

Return value

\n
\n

An Object with two properties:

done

A boolean value:

  • \ntrue if the generator is past the end of its control flow. In this case value specifies the return value of the generator (which may be undefined).
  • \nfalse if the generator is able to produce more values.
value

Any JavaScript value yielded or returned by the generator.

\n

Examples

\n

Using next()

\n
\n

The following example shows a simple generator and the object that the next method returns:

\n

js

\n
function* gen() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst g = gen(); // Generator { }\ng.next(); // { value: 1, done: false }\ng.next(); // { value: 2, done: false }\ng.next(); // { value: 3, done: false }\ng.next(); // { value: undefined, done: true }\n
\n
\n

Using next() with a list

\n
\n

In this example, getPage takes a list and \"paginates\" it into chunks of size pageSize. Each call to next will yield one such chunk.

\n

js

\n
function* getPage(list, pageSize = 1) {\n  for (let index = 0; index < list.length; index += pageSize) {\n    yield list.slice(index, index + pageSize);\n  }\n}\n\nconst list = [1, 2, 3, 4, 5, 6, 7, 8];\nconst page = getPage(list, 3); // Generator { }\n\npage.next(); // { value: [1, 2, 3], done: false }\npage.next(); // { value: [4, 5, 6], done: false }\npage.next(); // { value: [7, 8], done: false }\npage.next(); // { value: undefined, done: true }\n
\n
\n

Sending values to the generator

\n
\n

In this example, next is called with a value.

Note: The first call does not log anything, because the generator was not yielding anything initially.

\n

js

\n
function* gen() {\n  while (true) {\n    const value = yield;\n    console.log(value);\n  }\n}\n\nconst g = gen();\ng.next(1); // Returns { value: undefined, done: false }\n// No log at this step: the first value sent through `next` is lost\ng.next(2); // Returns { value: undefined, done: false }\n// Logs 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator.prototype.next
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
next391326No261039392626104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next\n

\n
\n", + "global_objects/generator/return": "

Generator.prototype.return()

The return() method of Generator instances acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.

\n

Syntax

\n
\n

js

\n
generatorInstance.return()\ngeneratorInstance.return(value)\n
\n
\n

Parameters

\n
\nvalue Optional\n

The value to return.

Return value

\n
\n

An Object with two properties:

done

A boolean value:

  • \ntrue if the generator function's control flow has reached the end.
  • \nfalse if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the return is captured in a try...finally and there are more yield expressions in the finally block.
value

The value that is given as an argument, or, if the yield expression is wrapped in a try...finally, the value yielded/returned from the finally block.

\n

Description

\n

The return() method, when called, can be seen as if a return value; statement is inserted in the generator's body at the current suspended position, where value is the value passed to the return() method. Therefore, in a typical flow, calling return(value) will return { done: true, value: value }. However, if the yield expression is wrapped in a try...finally block, the control flow doesn't exit the function body, but proceeds to the finally block instead. In this case, the value returned may be different, and done may even be false, if there are more yield expressions within the finally block.

Examples

\n

Using return()

\n
\n

The following example shows a simple generator and the return method.

\n

js

\n
function* gen() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst g = gen();\n\ng.next(); // { value: 1, done: false }\ng.return(\"foo\"); // { value: \"foo\", done: true }\ng.next(); // { value: undefined, done: true }\n
\n

If return(value) is called on a generator that is already in \"completed\" state, the generator will remain in \"completed\" state.

If no argument is provided, the value property of the returned object will be undefined. If an argument is provided, it will become the value of the value property of the returned object, unless the yield expression is wrapped in a try...finally.

\n

js

\n
function* gen() {\n  yield 1;\n  yield 2;\n  yield 3;\n}\n\nconst g = gen();\ng.next(); // { value: 1, done: false }\ng.next(); // { value: 2, done: false }\ng.next(); // { value: 3, done: false }\ng.next(); // { value: undefined, done: true }\ng.return(); // { value: undefined, done: true }\ng.return(1); // { value: 1, done: true }\n
\n
\n

Using return() with try...finally

\n
\n

The fact that the return method has been called can only be made known to the generator itself if the yield expression is wrapped in a try...finally block.

When the return method is called on a generator that is suspended within a try block, execution in the generator proceeds to the finally block — since the finally block of try...finally statements always executes.

\n

js

\n
function* gen() {\n  yield 1;\n  try {\n    yield 2;\n    yield 3;\n  } finally {\n    yield \"cleanup\";\n  }\n}\n\nconst g1 = gen();\ng1.next(); // { value: 1, done: false }\n\n// Execution is suspended before the try...finally.\ng1.return(\"early return\"); // { value: 'early return', done: true }\n\nconst g2 = gen();\ng2.next(); // { value: 1, done: false }\ng2.next(); // { value: 2, done: false }\n\n// Execution is suspended within the try...finally.\ng2.return(\"early return\"); // { value: 'cleanup', done: false }\n\n// The completion value is preserved\ng2.next(); // { value: 'early return', done: true }\n\n// Generator is in the completed state\ng2.return(\"not so early return\"); // { value: 'not so early return', done: true }\n
\n

The return value of the finally block can also become the value of the result returned from the return call.

\n

js

\n
function* gen() {\n  try {\n    yield 1;\n  } finally {\n    return \"cleanup\";\n  }\n}\n\nconst g1 = gen();\ng1.next(); // { value: 1, done: false }\ng1.return(\"early return\"); // { value: 'cleanup', done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator.prototype.return
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
return501338No371050503837105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return\n

\n
\n", + "global_objects/generator/throw": "

Generator.prototype.throw()

The throw() method of Generator instances acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

\n

Syntax

\n
\n

js

\n
generatorInstance.throw(exception)\n
\n
\n

Parameters

\n
exception

The exception to throw. For debugging purposes, it is useful to make it an instanceof Error.

Return value

\n
\n

If the thrown exception is caught by a try...catch and the generator resumes to yield more values, it will return an Object with two properties:

done

A boolean value:

  • \ntrue if the generator function's control flow has reached the end.
  • \nfalse if the generator function is able to produce more values.
value

The value yielded from the next yield expression.

\n

Exceptions

\n

If the thrown exception is not caught by a try...catch, the exception passed to throw() will be thrown out from the generator function.

Description

\n

The throw() method, when called, can be seen as if a throw exception; statement is inserted in the generator's body at the current suspended position, where exception is the exception passed to the throw() method. Therefore, in a typical flow, calling throw(exception) will cause the generator to throw. However, if the yield expression is wrapped in a try...catch block, the error may be caught and control flow can either resume after error handling, or exit gracefully.

Examples

\n

Using throw()

\n
\n

The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual.

\n

js

\n
function* gen() {\n  while (true) {\n    try {\n      yield 42;\n    } catch (e) {\n      console.log(\"Error caught!\");\n    }\n  }\n}\n\nconst g = gen();\ng.next();\n// { value: 42, done: false }\ng.throw(new Error(\"Something went wrong\"));\n// \"Error caught!\"\n// { value: 42, done: false }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-generator.prototype.throw
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
throw391326No261039392626104.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/throw\n

\n
\n", + "global_objects/asyncgenerator/next": "

AsyncGenerator.prototype.next()

The next() method of AsyncGenerator instances returns the next value in the sequence.

\n

Syntax

\n
\n

js

\n
next()\nnext(value)\n
\n

Parameters

\n
\nvalue Optional\n

An optional value used to modify the internal state of the generator. A value passed to the next() method will be received by yield

Return value

\n
\n

A Promise which when resolved returns an Object with two properties:

done

A boolean value:

  • \ntrue if the generator is past the end of its control flow. In this case value specifies the return value of the generator (which may be undefined).
  • \nfalse if the generator is able to produce more values.
value

Any JavaScript value yielded or returned by the generator.

\n

Examples

\n

Using next()

\n
\n

The following example shows a simple generator and the object that the next method returns:

\n

js

\n
// An async task. Pretend it's doing something more useful\n// in practice.\nfunction delayedValue(time, value) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => resolve(value), time);\n  });\n}\n\nasync function* createAsyncGenerator() {\n  yield delayedValue(500, 1);\n  yield delayedValue(500, 2);\n  yield delayedValue(500, 3);\n}\n\nconst asyncGen = createAsyncGenerator();\nasyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }\nasyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }\nasyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }\nasyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }\n
\n
\n

Sending values to the generator

\n
\n

In this example, next is called with a value.

Note: The first call does not log anything, because the generator was not yielding anything initially.

\n

js

\n
// An async task. Pretend it's doing something more useful\n// in practice.\nfunction sleep(time) {\n  return new Promise((resolve, reject) => {\n    setTimeout(resolve, time);\n  });\n}\n\nasync function* createAsyncGenerator() {\n  while (true) {\n    await sleep(500);\n    const value = yield;\n    console.log(value);\n  }\n}\n\nasync function main() {\n  const asyncGen = createAsyncGenerator();\n  // No log at this step: the first value sent through `next` is lost\n  console.log(await asyncGen.next(1)); // { value: undefined, done: false }\n  // Logs 2: the value sent through `next`\n  console.log(await asyncGen.next(2)); // { value: undefined, done: false }\n}\n\nmain();\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgenerator-prototype-next
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
next637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator/next\n

\n
\n", + "global_objects/asyncgenerator/return": "

AsyncGenerator.prototype.return()

The return() method of AsyncGenerator instances acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.

\n

Syntax

\n
\n

js

\n
asyncGeneratorInstance.return()\nasyncGeneratorInstance.return(value)\n
\n

Parameters

\n
\nvalue Optional\n

The value to return.

Return value

\n
\n

A Promise which resolves with an Object with two properties:

done

A boolean value:

  • \ntrue if the generator function's control flow has reached the end.
  • \nfalse if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the return is captured in a try...finally and there are more yield expressions in the finally block.
value

The value that is given as an argument, or, if the yield expression is wrapped in a try...finally, the value yielded/returned from the finally block.

\n

Description

\n

The return() method, when called, can be seen as if a return value; statement is inserted in the generator's body at the current suspended position, where value is the value passed to the return() method. Therefore, in a typical flow, calling return(value) will return { done: true, value: value }. However, if the yield expression is wrapped in a try...finally block, the control flow doesn't exit the function body, but proceeds to the finally block instead. In this case, the value returned may be different, and done may even be false, if there are more yield expressions within the finally block.

Examples

\n

Using return()

\n
\n

The following example shows a simple async generator and the return method.

\n

js

\n
// An async task. Pretend it's doing something more useful\n// in practice.\nfunction delayedValue(time, value) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => resolve(value), time);\n  });\n}\n\nasync function* createAsyncGenerator() {\n  yield delayedValue(500, 1);\n  yield delayedValue(500, 2);\n  yield delayedValue(500, 3);\n}\n\nconst asyncGen = createAsyncGenerator();\nasyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }\nasyncGen.return(\"foo\").then((res) => console.log(res)); // { value: \"foo\", done: true }\nasyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }\n
\n
\n

Using return() once a generator is complete

\n
\n

If no value argument is passed into the return() method, the promise will resolve as if the next() method has been called. In this example the generator has completed, so the value returned is undefined.

return() can still be called after the generator is in a \"completed\" state, however the generator will stay in this state.

\n

js

\n
async function* createAsyncGenerator() {\n  yield await Promise.resolve(1);\n  yield await Promise.resolve(2);\n  yield await Promise.resolve(3);\n}\nconst asyncGen = createAsyncGenerator();\nasyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }\nasyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }\nasyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }\n// value is returned undefined, as no value is passed and generator is 'done'\nasyncGen.return().then((res) => console.log(res)); // { value: undefined, done: true }\n// we can still return a value once the generator is complete\nasyncGen.return(1).then((res) => console.log(res)); // { value: 1, done: true }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgenerator-prototype-return
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
return637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator/return\n

\n
\n", + "global_objects/asyncgenerator/throw": "

AsyncGenerator.prototype.throw()

The throw() method of AsyncGenerator instances acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

\n

Syntax

\n
\n

js

\n
asyncGeneratorInstance.throw(exception)\n
\n

Parameters

\n
exception

The exception to throw. For debugging purposes, it is useful to make it an instanceof Error.

Return value

\n
\n

If the thrown error is not caught, it will return a Promise which rejects with the exception passed in.

If the exception is caught by a try...catch and the generator resumes to yield more values, it will return a Promise which resolves with an Object with two properties:

done

A boolean value:

  • \ntrue if the generator function's control flow has reached the end.
  • \nfalse if the generator function is able to produce more values.
value

The value yielded from the next yield expression.

\n

Examples

\n

Using throw()

\n
\n

The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual.

\n

js

\n
// An async task. Pretend it's doing something more useful\n// in practice.\nfunction sleep(time) {\n  return new Promise((resolve, reject) => {\n    setTimeout(resolve, time);\n  });\n}\n\nasync function* createAsyncGenerator() {\n  while (true) {\n    try {\n      await sleep(500);\n      yield 42;\n    } catch (e) {\n      console.error(e);\n    }\n  }\n}\n\nconst asyncGen = createAsyncGenerator();\nasyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }\nasyncGen\n  .throw(new Error(\"Something went wrong\")) // Error: Something went wrong\n  .then((res) => console.log(res)); // { value: 42, done: false }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-asyncgenerator-prototype-throw
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
throw637955No501263635546128.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator/throw\n

\n
\n", + "global_objects/asyncfunction/asyncfunction": "

AsyncFunction() constructor

\n

The AsyncFunction() constructor creates AsyncFunction objects.

Note that AsyncFunction is not a global object. It can be obtained with the following code:

\n

js

\n
const AsyncFunction = async function () {}.constructor;\n
\n

The AsyncFunction() constructor is not intended to be used directly, and all caveats mentioned in the Function() description apply to AsyncFunction().

\n
\n

Syntax

\n
\n
\n

js

\n
new AsyncFunction(functionBody)\nnew AsyncFunction(arg1, functionBody)\nnew AsyncFunction(arg1, arg2, functionBody)\nnew AsyncFunction(arg1, arg2, /* …, */ argN, functionBody)\n\nAsyncFunction(functionBody)\nAsyncFunction(arg1, functionBody)\nAsyncFunction(arg1, arg2, functionBody)\nAsyncFunction(arg1, arg2, /* …, */ argN, functionBody)\n
\n

Note: AsyncFunction() can be called with or without new. Both create a new AsyncFunction instance.

\n

Parameters

\n

See Function().

Examples

\n

Creating an async function from an AsyncFunction() constructor

\n
\n

js

\n
function resolveAfter2Seconds(x) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve(x);\n    }, 2000);\n  });\n}\n\nconst AsyncFunction = async function () {}.constructor;\n\nconst fn = new AsyncFunction(\n  \"a\",\n  \"b\",\n  \"return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);\",\n);\n\nfn(10, 20).then((v) => {\n  console.log(v); // prints 30 after 4 seconds\n});\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-async-function-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
AsyncFunction551552No4210.15555524210.36.01.07.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/AsyncFunction\n

\n
\n", + "global_objects/proxy/proxy": "

Proxy() constructor

The Proxy() constructor creates Proxy objects.

\n

Syntax

\n
\n
\n

js

\n
new Proxy(target, handler)\n
\n

Note: Proxy() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
target

A target object to wrap with Proxy. It can be any sort of object, including a native array, a function, or even another proxy.

handler

An object whose properties are functions that define the behavior of the proxy when an operation is performed on it.

Description

\n
\n

Use the Proxy() constructor to create a new Proxy object. This constructor takes two mandatory arguments:

An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the handler object, you can customize specific aspects of the proxy's behavior. For example, by defining get() you can provide a customized version of the target's property accessor.

\n

Handler functions

\n
\n

This section lists all the handler functions you can define. Handler functions are sometimes called traps, because they trap calls to the underlying target object.

handler.apply()

A trap for a function call.

handler.construct()

A trap for the new operator.

handler.defineProperty()

A trap for Object.defineProperty.

handler.deleteProperty()

A trap for the delete operator.

handler.get()

A trap for getting property values.

handler.getOwnPropertyDescriptor()

A trap for Object.getOwnPropertyDescriptor.

handler.getPrototypeOf()

A trap for Object.getPrototypeOf.

handler.has()

A trap for the in operator.

handler.isExtensible()

A trap for Object.isExtensible.

handler.ownKeys()

A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.

handler.preventExtensions()

A trap for Object.preventExtensions.

handler.set()

A trap for setting property values.

handler.setPrototypeOf()

A trap for Object.setPrototypeOf.

\n

Examples

\n

Selectively proxy property accessors

\n
\n

In this example the target has two properties, notProxied and proxied. We define a handler that returns a different value for proxied, and lets any other accesses through to the target.

\n

js

\n
const target = {\n  notProxied: \"original value\",\n  proxied: \"original value\",\n};\n\nconst handler = {\n  get(target, prop, receiver) {\n    if (prop === \"proxied\") {\n      return \"replaced value\";\n    }\n    return Reflect.get(...arguments);\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.notProxied); // \"original value\"\nconsole.log(proxy.proxied); // \"replaced value\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Proxy491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy\n

\n
\n", + "global_objects/proxy/proxy/deleteproperty": "

handler.deleteProperty()

The handler.deleteProperty() method is a trap for the [[Delete]] object internal method, which is used by operations such as the delete operator.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  deleteProperty(target, property) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the deleteProperty() method. this is bound to the handler.

target

The target object.

property

The name or Symbol of the property to delete.

\n

Return value

\n

The deleteProperty() method must return a boolean value indicating whether or not the property has been successfully deleted.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[Delete]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping the delete operator

\n
\n

The following code traps the delete operator.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    deleteProperty(target, prop) {\n      if (!(prop in target)) {\n        console.log(`property not found: ${prop}`);\n        return false;\n      }\n      delete target[prop];\n      console.log(`property removed: ${prop}`);\n      return true;\n    },\n  },\n);\n\np.a = 10;\nconsole.log(\"a\" in p); // true\n\nconst result1 = delete p.a; // \"property removed: a\"\nconsole.log(result1); // true\nconsole.log(\"a\" in p); // false\n\nconst result2 = delete p.a; // \"property not found: a\"\nconsole.log(result2); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-delete-p
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
deleteProperty491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty\n

\n
\n", + "global_objects/reflect/get": "

Reflect.get()

The Reflect.get() static method is like the property accessor syntax, but as a function.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.get(target, propertyKey)\nReflect.get(target, propertyKey, receiver)\n
\n

Parameters

\n
target

The target object on which to get the property.

propertyKey

The name of the property to get.

\nreceiver Optional\n

The value of this provided for the call to target if a getter is encountered.

Return value

\n

The value of the property.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.get() provides the reflective semantic of a property access. That is, Reflect.get(target, propertyKey, receiver) is semantically equivalent to:

\n

js

\n
target[propertyKey];\n
\n

Note that in a normal property access, target and receiver would observably be the same object.

Reflect.get() invokes the [[Get]] object internal method of target.

\n

Examples

\n

Using Reflect.get()

\n
\n

js

\n
// Object\nconst obj1 = { x: 1, y: 2 };\nReflect.get(obj1, \"x\"); // 1\n\n// Array\nReflect.get([\"zero\", \"one\"], 1); // \"one\"\n\n// Proxy with a get handler\nconst obj2 = new Proxy(\n  { p: 1 },\n  {\n    get(t, k, r) {\n      return k + \"bar\";\n    },\n  },\n);\nReflect.get(obj2, \"foo\"); // \"foobar\"\n\n// Proxy with get handler and receiver\nconst obj3 = new Proxy(\n  { p: 1, foo: 2 },\n  {\n    get(t, prop, receiver) {\n      return receiver[prop] + \"bar\";\n    },\n  },\n);\nReflect.get(obj3, \"foo\", { foo: 3 }); // \"3bar\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.get
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
get491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/get\n

\n
\n", + "global_objects/reflect/apply": "

Reflect.apply()

The Reflect.apply() static method calls a target function with arguments as specified.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.apply(target, thisArgument, argumentsList)\n
\n

Parameters

\n
target

The target function to call.

thisArgument

The value of this provided for the call to target.

argumentsList

An array-like object specifying the arguments with which target should be called.

Return value

\n

The result of calling the given target function with the specified this value and arguments.

Exceptions

\n
TypeError

Thrown if target is not a function or argumentsList is not an object.

Description

\n
\n

Reflect.apply() provides the reflective semantic of a function call. That is, Reflect.apply(target, thisArgument, argumentsList) is semantically equivalent to:

\n

js

\n
Math.floor.apply(null, [1.75]);\nReflect.apply(Math.floor, null, [1.75]);\n
\n

The only differences are:

Reflect.apply() invokes the [[Call]] object internal method of target.

\n

Examples

\n

Using Reflect.apply()

\n
\n

js

\n
Reflect.apply(Math.floor, undefined, [1.75]);\n// 1;\n\nReflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);\n// \"hello\"\n\nReflect.apply(RegExp.prototype.exec, /ab/, [\"confabulation\"]).index;\n// 4\n\nReflect.apply(\"\".charAt, \"ponies\", [3]);\n// \"i\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.apply
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
apply491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/apply\n

\n
\n", + "global_objects/reflect/defineproperty": "

Reflect.defineProperty()

The Reflect.defineProperty() static method is like Object.defineProperty() but returns a Boolean.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.defineProperty(target, propertyKey, attributes)\n
\n

Parameters

\n
target

The target object on which to define the property.

propertyKey

The name of the property to be defined or modified.

attributes

The attributes for the property being defined or modified.

Return value

\n

A boolean indicating whether or not the property was successfully defined.

Exceptions

\n
TypeError

Thrown if target or attributes is not an object.

Description

\n
\n

Reflect.defineProperty() provides the reflective semantic of defining an own property on an object. At the very low level, defining a property returns a boolean (as is the case with the proxy handler). Object.defineProperty() provides nearly the same semantic, but it throws a TypeError if the status is false (the operation was unsuccessful), while Reflect.defineProperty() directly returns the status.

Many built-in operations would also define own properties on objects. The most significant difference between defining properties and setting them is that setters aren't invoked. For example, class fields directly define properties on the instance without invoking setters.

\n

js

\n
class B extends class A {\n  set a(v) {\n    console.log(\"Setter called\");\n  }\n} {\n  a = 1; // Nothing logged\n}\n
\n

Reflect.defineProperty() invokes the [[DefineOwnProperty]] object internal method of target.

\n

Examples

\n

Using Reflect.defineProperty()

\n
\n

js

\n
const obj = {};\nReflect.defineProperty(obj, \"x\", { value: 7 }); // true\nconsole.log(obj.x); // 7\n
\n

Checking if property definition has been successful

\n
\n

With Object.defineProperty(), which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property.

Because Reflect.defineProperty() returns a Boolean success status, you can just use an if...else block here:

\n

js

\n
if (Reflect.defineProperty(target, property, attributes)) {\n  // success\n} else {\n  // failure\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.defineproperty
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
defineProperty491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty\n

\n
\n", + "global_objects/reflect/deleteproperty": "

Reflect.deleteProperty()

The Reflect.deleteProperty() static method is like the delete operator, but as a function. It deletes a property from an object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.deleteProperty(target, propertyKey)\n
\n

Parameters

\n
target

The target object on which to delete the property.

propertyKey

The name of the property to be deleted.

Return value

\n

A boolean indicating whether or not the property was successfully deleted.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.deleteProperty() provides the reflective semantic of the delete operator. That is, Reflect.deleteProperty(target, propertyKey) is semantically equivalent to:

\n

js

\n
delete target.propertyKey;\n
\n

At the very low level, deleting a property returns a boolean (as is the case with the proxy handler). Reflect.deleteProperty() directly returns the status, while delete would throw a TypeError in strict mode if the status is false. In non-strict mode, delete and Reflect.deleteProperty() have the same behavior.

Reflect.deleteProperty() invokes the [[Delete]] object internal method of target.

\n

Examples

\n

Using Reflect.deleteProperty()

\n
\n

js

\n
const obj = { x: 1, y: 2 };\nReflect.deleteProperty(obj, \"x\"); // true\nconsole.log(obj); // { y: 2 }\n\nconst arr = [1, 2, 3, 4, 5];\nReflect.deleteProperty(arr, \"3\"); // true\nconsole.log(arr); // [1, 2, 3, undefined, 5]\n\n// Returns true if no such property exists\nReflect.deleteProperty({}, \"foo\"); // true\n\n// Returns false if a property is unconfigurable\nReflect.deleteProperty(Object.freeze({ foo: 1 }), \"foo\"); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.deleteproperty
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
deleteProperty491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty\n

\n
\n", + "global_objects/reflect/getownpropertydescriptor": "

Reflect.getOwnPropertyDescriptor()

The Reflect.getOwnPropertyDescriptor() static method is like Object.getOwnPropertyDescriptor(). It returns a property descriptor of the given property if it exists on the object, undefined otherwise.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.getOwnPropertyDescriptor(target, propertyKey)\n
\n

Parameters

\n
target

The target object in which to look for the property.

propertyKey

The name of the property to get an own property descriptor for.

Return value

\n

A property descriptor object if the property exists as an own property of target; otherwise, undefined.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.getOwnPropertyDescriptor() provides the reflective semantic of retrieving the property descriptor of an object. The only difference with Object.getOwnPropertyDescriptor() is how non-object targets are handled. Reflect.getOwnPropertyDescriptor() throws a TypeError if the target is not an object, while Object.getOwnPropertyDescriptor() coerces it to an object.

Reflect.getOwnPropertyDescriptor() invokes the [[GetOwnProperty]] object internal method of target.

\n

Examples

\n

Using Reflect.getOwnPropertyDescriptor()

\n
\n

js

\n
Reflect.getOwnPropertyDescriptor({ x: \"hello\" }, \"x\");\n// {value: \"hello\", writable: true, enumerable: true, configurable: true}\n\nReflect.getOwnPropertyDescriptor({ x: \"hello\" }, \"y\");\n// undefined\n\nReflect.getOwnPropertyDescriptor([], \"length\");\n// {value: 0, writable: true, enumerable: false, configurable: false}\n
\n

Difference with Object.getOwnPropertyDescriptor()

\n
\n

If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.getOwnPropertyDescriptor, a non-object first argument will be coerced to an object at first.

\n

js

\n
Reflect.getOwnPropertyDescriptor(\"foo\", 0);\n// TypeError: \"foo\" is not non-null object\n\nObject.getOwnPropertyDescriptor(\"foo\", 0);\n// { value: \"f\", writable: false, enumerable: true, configurable: false }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.getownpropertydescriptor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertyDescriptor491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor\n

\n
\n", + "global_objects/reflect/getprototypeof": "

Reflect.getPrototypeOf()

The Reflect.getPrototypeOf() static method is like Object.getPrototypeOf(). It returns the prototype of the specified object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.getPrototypeOf(target)\n
\n

Parameters

\n
target

The target object of which to get the prototype.

Return value

\n

The prototype of the given object, which may be an object or null.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.getPrototypeOf() provides the reflective semantic of retrieving the prototype of an object. The only difference with Object.getPrototypeOf() is how non-object targets are handled. Reflect.getPrototypeOf() throws a TypeError if the target is not an object, while Object.getPrototypeOf() coerces it to an object.

Reflect.getPrototypeOf() invokes the [[GetPrototypeOf]] object internal method of target.

\n

Examples

\n

Using Reflect.getPrototypeOf()

\n
\n

js

\n
Reflect.getPrototypeOf({}); // Object.prototype\nReflect.getPrototypeOf(Object.prototype); // null\nReflect.getPrototypeOf(Object.create(null)); // null\n
\n

Difference with Object.getPrototypeOf()

\n
\n

js

\n
// Same result for Objects\nObject.getPrototypeOf({}); // Object.prototype\nReflect.getPrototypeOf({}); // Object.prototype\n\n// Both throw in ES5 for non-Objects\nObject.getPrototypeOf(\"foo\"); // Throws TypeError\nReflect.getPrototypeOf(\"foo\"); // Throws TypeError\n\n// In ES2015 only Reflect throws, Object coerces non-Objects\nObject.getPrototypeOf(\"foo\"); // String.prototype\nReflect.getPrototypeOf(\"foo\"); // Throws TypeError\n\n// To mimic the Object ES2015 behavior you need to coerce\nReflect.getPrototypeOf(Object(\"foo\")); // String.prototype\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.getprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getPrototypeOf491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf\n

\n
\n", + "global_objects/reflect/has": "

Reflect.has()

The Reflect.has() static method is like the in operator, but as a function.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.has(target, propertyKey)\n
\n

Parameters

\n
target

The target object in which to look for the property.

propertyKey

The name of the property to check.

Return value

\n

A Boolean indicating whether or not the target has the property.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.has() provides the reflective semantic of checking if a property is in an object. That is, Reflect.has(target, propertyKey) is semantically equivalent to:

\n

js

\n
propertyKey in target;\n
\n

Reflect.has() invokes the [[HasProperty]] object internal method of target.

\n

Examples

\n

Using Reflect.has()

\n
\n
\n

js

\n
Reflect.has({ x: 0 }, \"x\"); // true\nReflect.has({ x: 0 }, \"y\"); // false\n\n// returns true for properties in the prototype chain\nReflect.has({ x: 0 }, \"toString\");\n\n// Proxy with .has() handler method\nobj = new Proxy(\n  {},\n  {\n    has(t, k) {\n      return k.startsWith(\"door\");\n    },\n  },\n);\nReflect.has(obj, \"doorbell\"); // true\nReflect.has(obj, \"dormitory\"); // false\n
\n

Reflect.has returns true for any inherited properties, like the in operator:

\n

js

\n
const a = { foo: 123 };\nconst b = { __proto__: a };\nconst c = { __proto__: b };\n// The prototype chain is: c -> b -> a\nReflect.has(c, \"foo\"); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.has
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/has\n

\n
\n", + "global_objects/reflect/isextensible": "

Reflect.isExtensible()

The Reflect.isExtensible() static method is like Object.isExtensible(). It determines if an object is extensible (whether it can have new properties added to it).

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.isExtensible(target)\n
\n

Parameters

\n
target

The target object which to check if it is extensible.

Return value

\n

A Boolean indicating whether or not the target is extensible.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.isExtensible() provides the reflective semantic of checking if an object is extensible. The only difference with Object.isExtensible() is how non-object targets are handled. Reflect.isExtensible() throws a TypeError if the target is not an object, while Object.isExtensible() always returns false for non-object targets.

Reflect.isExtensible() invokes the [[IsExtensible]] object internal method of target.

\n

Examples

\n

Using Reflect.isExtensible()

\n
\n

See also Object.isExtensible().

\n

js

\n
// New objects are extensible.\nconst empty = {};\nReflect.isExtensible(empty); // true\n\n// ...but that can be changed.\nReflect.preventExtensions(empty);\nReflect.isExtensible(empty); // false\n\n// Sealed objects are by definition non-extensible.\nconst sealed = Object.seal({});\nReflect.isExtensible(sealed); // false\n\n// Frozen objects are also by definition non-extensible.\nconst frozen = Object.freeze({});\nReflect.isExtensible(frozen); // false\n
\n
\n

Difference with Object.isExtensible()

\n
\n

If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.isExtensible(), a non-object target will return false without any errors.

\n

js

\n
Reflect.isExtensible(1);\n// TypeError: 1 is not an object\n\nObject.isExtensible(1);\n// false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.isextensible
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isExtensible491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible\n

\n
\n", + "global_objects/reflect/ownkeys": "

Reflect.ownKeys()

The Reflect.ownKeys() static method returns an array of the target object's own property keys.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.ownKeys(target)\n
\n

Parameters

\n
target

The target object from which to get the own keys.

Return value

\n
\n

An Array of the target object's own property keys, including strings and symbols. For most objects, the array will be in the order of:

  1. Non-negative integer indexes in increasing numeric order (but as strings)
  2. Other string keys in the order of property creation
  3. Symbol keys in the order of property creation.
\n

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.ownKeys() provides the reflective semantic of retrieving all property keys of an object. It is the only way to get all own properties – enumerable and not enumerable, strings and symbols — in one call, without extra filtering logic. For example, Object.getOwnPropertyNames() takes the return value of Reflect.ownKeys() and filters to only string values, while Object.getOwnPropertySymbols() filters to only symbol values. Because normal objects implement [[OwnPropertyKeys]] to return all string keys before symbol keys, Reflect.ownKeys(target) is usually equivalent to Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)). However, if the object has a custom [[OwnPropertyKeys]] method (such as through a proxy's ownKeys handler), the order of the keys may be different.

Reflect.ownKeys() invokes the [[OwnPropertyKeys]] object internal method of target.

\n

Examples

\n

Using Reflect.ownKeys()

\n
\n

js

\n
Reflect.ownKeys({ z: 3, y: 2, x: 1 }); // [ \"z\", \"y\", \"x\" ]\nReflect.ownKeys([]); // [\"length\"]\n\nconst sym = Symbol.for(\"comet\");\nconst sym2 = Symbol.for(\"meteor\");\nconst obj = {\n  [sym]: 0,\n  str: 0,\n  773: 0,\n  0: 0,\n  [sym2]: 0,\n  \"-1\": 0,\n  8: 0,\n  \"second str\": 0,\n};\nReflect.ownKeys(obj);\n// [ \"0\", \"8\", \"773\", \"str\", \"-1\", \"second str\", Symbol(comet), Symbol(meteor) ]\n// Indexes in numeric order,\n// strings in insertion order,\n// symbols in insertion order\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.ownkeys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ownKeys491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys\n

\n
\n", + "global_objects/reflect/preventextensions": "

Reflect.preventExtensions()

The Reflect.preventExtensions() static method is like Object.preventExtensions(). It prevents new properties from ever being added to an object (i.e., prevents future extensions to the object).

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.preventExtensions(target)\n
\n

Parameters

\n
target

The target object on which to prevent extensions.

Return value

\n

A Boolean indicating whether or not the target was successfully set to prevent extensions.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.preventExtensions() provides the reflective semantic of preventing extensions of an object. The differences with Object.preventExtensions() are:

Reflect.preventExtensions() invokes the [[PreventExtensions]] object internal method of target.

\n

Examples

\n

Using Reflect.preventExtensions()

\n
\n

See also Object.preventExtensions().

\n

js

\n
// Objects are extensible by default.\nconst empty = {};\nReflect.isExtensible(empty); // true\n\n// ...but that can be changed.\nReflect.preventExtensions(empty);\nReflect.isExtensible(empty); // false\n
\n
\n

Difference with Object.preventExtensions()

\n
\n

If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.preventExtensions(), a non-object target will be returned as-is without any errors.

\n

js

\n
Reflect.preventExtensions(1);\n// TypeError: 1 is not an object\n\nObject.preventExtensions(1);\n// 1\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.preventextensions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
preventExtensions491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions\n

\n
\n", + "global_objects/reflect/set": "

Reflect.set()

The Reflect.set() static method is like the property accessor and assignment syntax, but as a function.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.set(target, propertyKey, value)\nReflect.set(target, propertyKey, value, receiver)\n
\n

Parameters

\n
target

The target object on which to set the property.

propertyKey

The name of the property to set.

value

The value to set.

\nreceiver Optional\n

The value of this provided for the call to the setter for propertyKey on target. If provided and target does not have a setter for propertyKey, the property will be set on receiver instead.

Return value

\n

A Boolean indicating whether or not setting the property was successful.

Exceptions

\n
TypeError

Thrown if target is not an object.

Description

\n
\n

Reflect.set() provides the reflective semantic of a property access. That is, Reflect.set(target, propertyKey, value, receiver) is semantically equivalent to:

\n

js

\n
target[propertyKey] = value;\n
\n

Note that in a normal property access, target and receiver would observably be the same object.

Reflect.set() invokes the [[Set]] object internal method of target.

\n

Examples

\n

Using Reflect.set()

\n
\n

js

\n
// Object\nconst obj = {};\nReflect.set(obj, \"prop\", \"value\"); // true\nobj.prop; // \"value\"\n\n// Array\nconst arr = [\"duck\", \"duck\", \"duck\"];\nReflect.set(arr, 2, \"goose\"); // true\narr[2]; // \"goose\"\n\n// It can truncate an array.\nReflect.set(arr, \"length\", 1); // true\narr; // [\"duck\"]\n\n// With just one argument, propertyKey and value are \"undefined\".\nReflect.set(obj); // true\nReflect.getOwnPropertyDescriptor(obj, \"undefined\");\n// { value: undefined, writable: true, enumerable: true, configurable: true }\n
\n

Different target and receiver

\n
\n

When the target and receiver are different, Reflect.set will use the property descriptor of target (to find the setter or determine if the property is writable), but set the property on receiver.

\n

js

\n
const target = {};\nconst receiver = {};\nReflect.set(target, \"a\", 2, receiver); // true\n// target is {}; receiver is { a: 2 }\n\nconst target = { a: 1 };\nconst receiver = {};\nReflect.set(target, \"a\", 2, receiver); // true\n// target is { a: 1 }; receiver is { a: 2 }\n\nconst target = {\n  set a(v) {\n    this.b = v;\n  },\n};\nconst receiver = {};\nReflect.set(target, \"a\", 2, receiver); // true\n// target is { a: [Setter] }; receiver is { b: 2 }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.set
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set\n

\n
\n", + "global_objects/reflect/setprototypeof": "

Reflect.setPrototypeOf()

The Reflect.setPrototypeOf() static method is like Object.setPrototypeOf() but returns a Boolean. It sets the prototype (i.e., the internal [[Prototype]] property) of a specified object.

\n

Try it

\n

Syntax

\n
\n

js

\n
Reflect.setPrototypeOf(target, prototype)\n
\n

Parameters

\n
target

The target object of which to set the prototype.

prototype

The object's new prototype (an object or null).

Return value

\n

A Boolean indicating whether or not the prototype was successfully set.

Exceptions

\n
TypeError

Thrown if target is not an object or if prototype is neither an object nor null.

Description

\n
\n

Reflect.setPrototypeOf() provides the reflective semantic of setting the prototype of an object. At the very low level, setting the prototype returns a boolean (as is the case with the proxy handler). Object.setPrototypeOf() provides nearly the same semantic, but it throws a TypeError if the status is false (the operation was unsuccessful), while Reflect.setPrototypeOf() directly returns the status.

Reflect.setPrototypeOf() invokes the [[SetPrototypeOf]] object internal method of target.

\n

Examples

\n

Using Reflect.setPrototypeOf()

\n
\n

js

\n
Reflect.setPrototypeOf({}, Object.prototype); // true\n\n// It can change an object's [[Prototype]] to null.\nReflect.setPrototypeOf({}, null); // true\n\n// Returns false if target is not extensible.\nReflect.setPrototypeOf(Object.freeze({}), null); // false\n\n// Returns false if it cause a prototype chain cycle.\nconst target = {};\nconst proto = Object.create(target);\nReflect.setPrototypeOf(target, proto); // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-reflect.setprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setPrototypeOf491242No361049494236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf\n

\n
\n", + "global_objects/proxy/proxy/get": "

handler.get()

The handler.get() method is a trap for the [[Get]] object internal method, which is used by operations such as property accessors.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  get(target, property, receiver) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the get() method. this is bound to the handler.

target

The target object.

property

The name or Symbol of the property to get.

receiver

Either the proxy or an object that inherits from the proxy.

\n

Return value

\n

The get() method can return any value.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[Get]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trap for getting a property value

\n
\n

The following code traps getting a property value.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    get(target, property, receiver) {\n      console.log(`called: ${property}`);\n      return 10;\n    },\n  },\n);\n\nconsole.log(p.a);\n// \"called: a\"\n// 10\n
\n

The following code violates an invariant.

\n

js

\n
const obj = {};\nObject.defineProperty(obj, \"a\", {\n  configurable: false,\n  enumerable: false,\n  value: 10,\n  writable: false,\n});\n\nconst p = new Proxy(obj, {\n  get(target, property) {\n    return 20;\n  },\n});\n\np.a; // TypeError is thrown\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
get491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/get\n

\n
\n", + "global_objects/proxy/proxy/getprototypeof": "

handler.getPrototypeOf()

The handler.getPrototypeOf() method is a trap for the [[GetPrototypeOf]] object internal method, which is used by operations such as Object.getPrototypeOf().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(obj, {\n  getPrototypeOf(target) {\n    // …\n  }\n});\n
\n

Parameters

\n
\n

The following parameter is passed to the getPrototypeOf() method. this is bound to the handler.

target

The target object.

\n

Return value

\n

The getPrototypeOf() method must return an object or null.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[GetPrototypeOf]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Basic usage

\n
\n

js

\n
const obj = {};\nconst proto = {};\nconst handler = {\n  getPrototypeOf(target) {\n    console.log(target === obj); // true\n    console.log(this === handler); // true\n    return proto;\n  },\n};\n\nconst p = new Proxy(obj, handler);\nconsole.log(Object.getPrototypeOf(p) === proto); // true\n
\n

Five ways to trigger the getPrototypeOf trap

\n
\n

js

\n
const obj = {};\nconst p = new Proxy(obj, {\n  getPrototypeOf(target) {\n    return Array.prototype;\n  },\n});\nconsole.log(\n  Object.getPrototypeOf(p) === Array.prototype, // true\n  Reflect.getPrototypeOf(p) === Array.prototype, // true\n  p.__proto__ === Array.prototype, // true\n  Array.prototype.isPrototypeOf(p), // true\n  p instanceof Array, // true\n);\n
\n

Two kinds of exceptions

\n
\n

js

\n
const obj = {};\nconst p = new Proxy(obj, {\n  getPrototypeOf(target) {\n    return \"foo\";\n  },\n});\nObject.getPrototypeOf(p); // TypeError: \"foo\" is not an object or null\n\nconst obj2 = Object.preventExtensions({});\nconst p2 = new Proxy(obj2, {\n  getPrototypeOf(target) {\n    return {};\n  },\n});\nObject.getPrototypeOf(p2); // TypeError: expected same prototype value\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-getprototypeof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getPrototypeOf497949No361049494936105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getPrototypeOf\n

\n
\n", + "global_objects/proxy/proxy/setprototypeof": "

handler.setPrototypeOf()

The handler.setPrototypeOf() method is a trap for the [[SetPrototypeOf]] object internal method, which is used by operations such as Object.setPrototypeOf().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  setPrototypeOf(target, prototype) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the setPrototypeOf() method. this is bound to the handler.

target

The target object.

prototype

The object's new prototype or null.

\n

Return value

\n

The setPrototypeOf() method returns true if the [[Prototype]] was successfully changed, otherwise false.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[SetPrototypeOf]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

If you want to disallow setting a new prototype for your object, your handler's setPrototypeOf() method can either return false, or it can throw an exception.

Approach 1: Returning false

\n
\n

This approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself.

For example, Object.setPrototypeOf() will create and throw a TypeError itself. If the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as Reflect.setPrototypeOf(), no exception will be thrown.

\n

js

\n
const handlerReturnsFalse = {\n  setPrototypeOf(target, newProto) {\n    return false;\n  },\n};\n\nconst newProto = {},\n  target = {};\n\nconst p1 = new Proxy(target, handlerReturnsFalse);\nObject.setPrototypeOf(p1, newProto); // throws a TypeError\nReflect.setPrototypeOf(p1, newProto); // returns false\n
\n
\n

Approach 2: Throwing an Exception

\n
\n

The latter approach will cause any operation that attempts to mutate, to throw. This approach is best if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value.

\n

js

\n
const handlerThrows = {\n  setPrototypeOf(target, newProto) {\n    throw new Error(\"custom error\");\n  },\n};\n\nconst newProto = {},\n  target = {};\n\nconst p2 = new Proxy(target, handlerThrows);\nObject.setPrototypeOf(p2, newProto); // throws new Error(\"custom error\")\nReflect.setPrototypeOf(p2, newProto); // throws new Error(\"custom error\")\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
setPrototypeOf491249No361049494936105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf\n

\n
\n", + "global_objects/proxy/proxy/isextensible": "

handler.isExtensible()

The handler.isExtensible() method is a trap for the [[IsExtensible]] object internal method, which is used by operations such as Object.isExtensible().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  isExtensible(target) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameter is passed to the isExtensible() method. this is bound to the handler.

target

The target object.

\n

Return value

\n

The isExtensible() method must return a boolean value.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[IsExtensible]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping of isExtensible

\n
\n

The following code traps Object.isExtensible().

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    isExtensible(target) {\n      console.log(\"called\");\n      return true;\n    },\n  },\n);\n\nconsole.log(Object.isExtensible(p));\n// \"called\"\n// true\n
\n

The following code violates the invariant.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    isExtensible(target) {\n      return false;\n    },\n  },\n);\n\nObject.isExtensible(p); // TypeError is thrown\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-isextensible
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
isExtensible491231No361049493136105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/isExtensible\n

\n
\n", + "global_objects/proxy/proxy/preventextensions": "

handler.preventExtensions()

The handler.preventExtensions() method is a trap for the [[PreventExtensions]] object internal method, which is used by operations such as Object.preventExtensions().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  preventExtensions(target) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameter is passed to the preventExtensions() method. this is bound to the handler.

target

The target object.

\n

Return value

\n

The preventExtensions() method must return a boolean value.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[PreventExtensions]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping of preventExtensions

\n
\n

The following code traps Object.preventExtensions().

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    preventExtensions(target) {\n      console.log(\"called\");\n      Object.preventExtensions(target);\n      return true;\n    },\n  },\n);\n\nconsole.log(Object.preventExtensions(p));\n// \"called\"\n// false\n
\n

The following code violates the invariant.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    preventExtensions(target) {\n      return true;\n    },\n  },\n);\n\nObject.preventExtensions(p); // TypeError is thrown\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-preventextensions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
preventExtensions491222No361049492236105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/preventExtensions\n

\n
\n", + "global_objects/proxy/proxy/getownpropertydescriptor": "

handler.getOwnPropertyDescriptor()

The handler.getOwnPropertyDescriptor() method is a trap for the [[GetOwnProperty]] object internal method, which is used by operations such as Object.getOwnPropertyDescriptor().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  getOwnPropertyDescriptor(target, prop) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the getOwnPropertyDescriptor() method. this is bound to the handler.

target

The target object.

prop

The name of the property whose description should be retrieved.

\n

Return value

\n

The getOwnPropertyDescriptor() method must return an object or undefined.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[GetOwnProperty]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping of getOwnPropertyDescriptor

\n
\n

The following code traps Object.getOwnPropertyDescriptor().

\n

js

\n
const p = new Proxy(\n  { a: 20 },\n  {\n    getOwnPropertyDescriptor(target, prop) {\n      console.log(`called: ${prop}`);\n      return { configurable: true, enumerable: true, value: 10 };\n    },\n  },\n);\n\nconsole.log(Object.getOwnPropertyDescriptor(p, \"a\").value);\n// \"called: a\"\n// 10\n
\n

The following code violates an invariant.

\n

js

\n
const obj = { a: 10 };\nObject.preventExtensions(obj);\nconst p = new Proxy(obj, {\n  getOwnPropertyDescriptor(target, prop) {\n    return undefined;\n  },\n});\n\nObject.getOwnPropertyDescriptor(p, \"a\"); // TypeError is thrown\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getOwnPropertyDescriptor491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor\n

\n
\n", + "global_objects/proxy/proxy/defineproperty": "

handler.defineProperty()

The handler.defineProperty() method is a trap for the [[DefineOwnProperty]] object internal method, which is used by operations such as Object.defineProperty().

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  defineProperty(target, property, descriptor) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the defineProperty() method. this is bound to the handler.

target

The target object.

property

The name or Symbol of the property whose description is to be retrieved.

descriptor

The descriptor for the property being defined or modified.

\n

Return value

\n

The defineProperty() method must return a Boolean indicating whether or not the property has been successfully defined.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[DefineOwnProperty]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping of defineProperty

\n
\n

The following code traps Object.defineProperty().

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    defineProperty(target, prop, descriptor) {\n      console.log(`called: ${prop}`);\n      return true;\n    },\n  },\n);\n\nconst desc = { configurable: true, enumerable: true, value: 10 };\nObject.defineProperty(p, \"a\", desc); // \"called: a\"\n
\n

When calling Object.defineProperty() or Reflect.defineProperty(), the descriptor passed to defineProperty() trap has one restriction—only following properties are usable (non-standard properties will be ignored):

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    defineProperty(target, prop, descriptor) {\n      console.log(descriptor);\n      return Reflect.defineProperty(target, prop, descriptor);\n    },\n  },\n);\n\nObject.defineProperty(p, \"name\", {\n  value: \"proxy\",\n  type: \"custom\",\n}); // { value: 'proxy' }\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
defineProperty491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty\n

\n
\n", + "global_objects/proxy/proxy/has": "

handler.has()

The handler.has() method is a trap for the [[HasProperty]] object internal method, which is used by operations such as the in operator.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  has(target, prop) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to has() method. this is bound to the handler.

target

The target object.

prop

The name or Symbol of the property to check for existence.

\n

Return value

\n

The has() method must return a boolean value.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[HasProperty]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping the in operator

\n
\n

The following code traps the in operator.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    has(target, prop) {\n      console.log(`called: ${prop}`);\n      return true;\n    },\n  },\n);\n\nconsole.log(\"a\" in p);\n// \"called: a\"\n// true\n
\n

The following code violates an invariant.

\n

js

\n
const obj = { a: 10 };\nObject.preventExtensions(obj);\n\nconst p = new Proxy(obj, {\n  has(target, prop) {\n    return false;\n  },\n});\n\n\"a\" in p; // TypeError is thrown\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
has491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/has\n

\n
\n", + "global_objects/proxy/proxy/set": "

handler.set()

The handler.set() method is a trap for the [[Set]] object internal method, which is used by operations such as using property accessors to set a property's value.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  set(target, property, value, receiver) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the set() method. this is bound to the handler.

target

The target object.

property

The name or Symbol of the property to set.

value

The new value of the property to set.

receiver

The object to which the assignment was originally directed. This is usually the proxy itself. But a set() handler can also be called indirectly, via the prototype chain or various other ways.

For example, suppose a script does obj.name = \"jen\", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. That proxy's set() handler will be called, and obj will be passed as the receiver.

\n

Return value

\n
\n

The set() method should return a boolean value.

\n

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[Set]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trap setting of a property value

\n
\n

The following code traps setting a property value.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    set(target, prop, value, receiver) {\n      target[prop] = value;\n      console.log(`property set: ${prop} = ${value}`);\n      return true;\n    },\n  },\n);\n\nconsole.log(\"a\" in p); // false\n\np.a = 10; // \"property set: a = 10\"\nconsole.log(\"a\" in p); // true\nconsole.log(p.a); // 10\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set\n

\n
\n", + "global_objects/proxy/proxy/ownkeys": "

handler.ownKeys()

The handler.ownKeys() method is a trap for the [[OwnPropertyKeys]] object internal method, which is used by operations such as Object.keys(), Reflect.ownKeys(), etc.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  ownKeys(target) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameter is passed to the ownKeys() method. this is bound to the handler.

target

The target object.

\n

Return value

\n

The ownKeys() method must return an enumerable object.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[OwnPropertyKeys]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping of getOwnPropertyNames

\n
\n

The following code traps Object.getOwnPropertyNames().

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    ownKeys(target) {\n      console.log(\"called\");\n      return [\"a\", \"b\", \"c\"];\n    },\n  },\n);\n\nconsole.log(Object.getOwnPropertyNames(p));\n// \"called\"\n// [ 'a', 'b', 'c' ]\n
\n

The following code violates an invariant.

\n

js

\n
const obj = {};\nObject.defineProperty(obj, \"a\", {\n  configurable: false,\n  enumerable: true,\n  value: 10,\n});\n\nconst p = new Proxy(obj, {\n  ownKeys(target) {\n    return [123, 12.5, true, false, undefined, null, {}, []];\n  },\n});\n\nconsole.log(Object.getOwnPropertyNames(p));\n\n// TypeError: proxy [[OwnPropertyKeys]] must return an array\n// with only string and symbol elements\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ownKeys4912
18In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore.
No36104949
18In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore.
36105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys\n

\n
\n", + "global_objects/proxy/proxy/apply": "

handler.apply()

The handler.apply() method is a trap for the [[Call]] object internal method, which is used by operations such as function calls.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  apply(target, thisArg, argumentsList) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the apply() method. this is bound to the handler.

target

The target callable object.

thisArg

The this argument for the call.

argumentsList

The list of arguments for the call.

\n

Return value

\n

The apply() method can return any value.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[Call]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping a function call

\n
\n

The following code traps a function call.

\n

js

\n
const p = new Proxy(function () {}, {\n  apply(target, thisArg, argumentsList) {\n    console.log(`called: ${argumentsList}`);\n    return argumentsList[0] + argumentsList[1] + argumentsList[2];\n  },\n});\n\nconsole.log(p(1, 2, 3)); // \"called: 1,2,3\"\n// 6\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
apply491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply\n

\n
\n", + "global_objects/proxy/proxy/construct": "

handler.construct()

The handler.construct() method is a trap for the [[Construct]] object internal method, which is used by operations such as the new operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself be a valid constructor.

\n

Try it

\n

Syntax

\n
\n

js

\n
new Proxy(target, {\n  construct(target, argumentsList, newTarget) {\n  }\n});\n
\n

Parameters

\n
\n

The following parameters are passed to the construct() method. this is bound to the handler.

target

The target object.

argumentsList

The list of arguments for the constructor.

newTarget

The constructor that was originally called.

\n

Return value

\n

The construct method must return an object.

Description

\n

Interceptions

\n
\n

This trap can intercept these operations:

Or any other operation that invokes the [[Construct]] internal method.

\n

Invariants

\n
\n

If the following invariants are violated, the trap throws a TypeError when invoked.

\n

Examples

\n

Trapping the new operator

\n
\n

The following code traps the new operator.

\n

js

\n
const p = new Proxy(function () {}, {\n  construct(target, argumentsList, newTarget) {\n    console.log(`called: ${argumentsList}`);\n    return { value: argumentsList[0] * 10 };\n  },\n});\n\nconsole.log(new p(1).value); // \"called: 1\"\n// 10\n
\n

The following code violates the invariant.

\n

js

\n
const p = new Proxy(function () {}, {\n  construct(target, argumentsList, newTarget) {\n    return 1;\n  },\n});\n\nnew p(); // TypeError is thrown\n
\n

The following code improperly initializes the proxy. The target in Proxy initialization must itself be a valid constructor for the new operator.

\n

js

\n
const p = new Proxy(\n  {},\n  {\n    construct(target, argumentsList, newTarget) {\n      return {};\n    },\n  },\n);\n\nnew p(); // TypeError is thrown, \"p\" is not a constructor\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
construct491218No361049491836105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct\n

\n
\n", + "global_objects/proxy/revocable": "

Proxy.revocable()

The Proxy.revocable() static method creates a revocable Proxy object.

\n

Syntax

\n
\n

js

\n
Proxy.revocable(target, handler)\n
\n

Parameters

\n
target

A target object to wrap with Proxy. It can be any sort of object, including a native array, a function, or even another proxy.

handler

An object whose properties are functions defining the behavior of proxy when an operation is performed on it.

Return value

\n
\n

A plain object with the following two properties:

proxy

A Proxy object exactly the same as one created with a new Proxy(target, handler) call.

revoke

A function with no parameters to revoke (switch off) the proxy.

\n

Description

\n
\n

The Proxy.revocable() factory function is the same as the Proxy() constructor, except that in addition to creating a proxy object, it also creates a revoke function that can be called to disable the proxy. The proxy object and the revoke function are wrapped in a plain object.

The revoke function does not take any parameters, nor does it rely on the this value. The created proxy object is attached to the revoke function as a private property that the revoke function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The proxy object is not captured within the closure of the revoke function (which will make garbage collection of proxy impossible if revoke is still alive).

After the revoke() function gets called, the proxy becomes unusable: any trap to a handler throws a TypeError. Once a proxy is revoked, it remains revoked, and calling revoke() again has no effect — in fact, the call to revoke() detaches the proxy object from the revoke function, so the revoke function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The revoke function also detaches target and handler from the proxy, so if target is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object.

Letting users interact with an object through a revocable proxy allows you to control the lifetime of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy.

\n

Examples

\n

Using Proxy.revocable()

\n
\n

js

\n
const revocable = Proxy.revocable(\n  {},\n  {\n    get(target, name) {\n      return `[[${name}]]`;\n    },\n  },\n);\nconst proxy = revocable.proxy;\nconsole.log(proxy.foo); // \"[[foo]]\"\n\nrevocable.revoke();\n\nconsole.log(proxy.foo); // TypeError is thrown\nproxy.foo = 1; // TypeError again\ndelete proxy.foo; // still TypeError\ntypeof proxy; // \"object\", typeof doesn't trigger any trap\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-proxy.revocable
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
revocable631234No501063633446108.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/revocable\n

\n
\n", + "global_objects/intl/getcanonicallocales": "

Intl.getCanonicalLocales()

The Intl.getCanonicalLocales() static method returns an array containing the canonical locale names. Duplicates will be omitted and elements will be validated as structurally valid language tags.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.getCanonicalLocales(locales)\n
\n

Parameters

\n
locales

A list of String values for which to get the canonical locale names.

Return value

\n

An array containing the canonical locale names.

Examples

\n

Using getCanonicalLocales

\n
\n

js

\n
Intl.getCanonicalLocales(\"EN-US\"); // [\"en-US\"]\nIntl.getCanonicalLocales([\"EN-US\", \"Fr\"]); // [\"en-US\", \"fr\"]\n\nIntl.getCanonicalLocales(\"EN_US\");\n// RangeError:'EN_US' is not a structurally valid language tag\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.getcanonicallocales
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getCanonicalLocales541648No4110.15454564110.36.01.87.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales\n

\n
\n", + "global_objects/intl/supportedvaluesof": "

Intl.supportedValuesOf()

\n

The Intl.supportedValuesOf() static method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation.

Duplicates are omitted and the array is sorted in ascending lexicographical order (or more precisely, using Array.prototype.sort() with an undefined compare function).

The method can be used to feature-test whether values are supported in a particular implementation and download a polyfill only if necessary. It can also be used to build UIs that allow users to select their preferred localized values, for example when the UI is created from WebGL or server-side.

\n
\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.supportedValuesOf(key)\n
\n

Parameters

\n
key

A key string indicating the category of values to be returned. This is one of: \"calendar\", \"collation\", \"currency\", \"numberingSystem\", \"timeZone\", \"unit\".

Return value

\n

A sorted array of unique string values indicating the values supported by the implementation for the given key.

Exceptions

\n
RangeError

Thrown if an unsupported key was passed as a parameter.

Examples

\n

Feature testing

\n
\n

You can check that the method is supported by comparing to undefined:

\n

js

\n
if (typeof Intl.supportedValuesOf !== \"undefined\") {\n  // method is supported\n}\n
\n
\n

Get all values for key

\n
\n

To get the supported values for calendar you call the method with the key \"calendar\". You can then iterate through the returned array as shown below:

\n

js

\n
Intl.supportedValuesOf(\"calendar\").forEach((calendar) => {\n  // \"buddhist\", \"chinese\", \"coptic\", \"dangi\", etc.\n});\n
\n

Note: The array returned for calendar values will always include the value \"gregory\" (gregorian).

The other values are all obtained in the same way:

\n

js

\n
Intl.supportedValuesOf(\"collation\").forEach((collation) => {\n  // \"compat\", \"dict\", \"emoji\", etc.\n});\n\nIntl.supportedValuesOf(\"currency\").forEach((currency) => {\n  // \"ADP\", \"AED\", \"AFA\", \"AFN\", \"ALK\", \"ALL\", \"AMD\", etc.\n});\n\nIntl.supportedValuesOf(\"numberingSystem\").forEach((numberingSystem) => {\n  // \"adlm\", \"ahom\", \"arab\", \"arabext\", \"bali\", etc.\n});\n\nIntl.supportedValuesOf(\"timeZone\").forEach((timeZone) => {\n  // \"Africa/Abidjan\", \"Africa/Accra\", \"Africa/Addis_Ababa\", \"Africa/Algiers\", etc.\n});\n\nIntl.supportedValuesOf(\"unit\").forEach((unit) => {\n  // \"acre\", \"bit\", \"byte\", \"celsius\", \"centimeter\", etc.\n});\n
\n
\n

Invalid key throws RangeError

\n
\n

js

\n
try {\n  Intl.supportedValuesOf(\"someInvalidKey\");\n} catch (err) {\n  //Error: RangeError: invalid key: \"someInvalidKey\"\n}\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.supportedvaluesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedValuesOf999993No8515.49999936815.418.01.1918.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf\n

\n
\n", + "global_objects/intl/collator/supportedlocalesof": "

Intl.Collator.supportedLocalesOf()

The Intl.Collator.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.Collator.supportedLocalesOf(locales)\nIntl.Collator.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in collation, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is not used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.Collator.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.collator.supportedlocalesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/supportedLocalesOf\n

\n
\n", + "global_objects/intl/collator/compare": "

Intl.Collator.prototype.compare()

The compare() method of Intl.Collator instances compares two strings according to the sort order of this collator object.

\n

Try it

\n

Syntax

\n
\n

js

\n
compare(string1, string2)\n
\n

Parameters

\n
\nstring1, string2\n

The strings to compare against each other.

Return value

\n
\n

A number indicating how string1 and string2 compare to each other according to the sort order of this Intl.Collator object:

\n

Examples

\n

Using compare for array sort

\n
\n

Use the compare function for sorting arrays. Note that the function is bound to the collator from which it was obtained, so it can be passed directly to Array.prototype.sort().

\n

js

\n
const a = [\"Offenbach\", \"Österreich\", \"Odenwald\"];\nconst collator = new Intl.Collator(\"de-u-co-phonebk\");\na.sort(collator.compare);\nconsole.log(a.join(\", \")); // \"Odenwald, Österreich, Offenbach\"\n
\n
\n

Using compare for array search

\n
\n

Use the compare function for finding matching strings in arrays:

\n

js

\n
const a = [\"Congrès\", \"congres\", \"Assemblée\", \"poisson\"];\nconst collator = new Intl.Collator(\"fr\", {\n  usage: \"search\",\n  sensitivity: \"base\",\n});\nconst s = \"congres\";\nconst matches = a.filter((v) => collator.compare(v, s) === 0);\nconsole.log(matches.join(\", \")); // \"Congrès, congres\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.collator.prototype.compare
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
compare2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare\n

\n
\n", + "global_objects/intl/collator/resolvedoptions": "

Intl.Collator.prototype.resolvedOptions()

The resolvedOptions() method of Intl.Collator instances returns a new object with properties reflecting the locale and collation options computed during initialization of this collator object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

A new object with properties reflecting the locale and collation options computed during the initialization of the given Intl.Collator object.

Description

\n
\n

The resulting object has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

\nusage, sensitivity, ignorePunctuation\n

The values provided for these properties in the options argument or filled in as defaults.

collation

The value requested using the Unicode extension key \"co\", if it is supported for locale, or \"default\".

\nnumeric, caseFirst\n

The values requested for these properties in the options argument or using the Unicode extension keys \"kn\" and \"kf\" or filled in as defaults. If the implementation does not support these properties, they are omitted.

\n

Examples

\n

Using the resolvedOptions method

\n
\n

js

\n
const de = new Intl.Collator(\"de\", { sensitivity: \"base\" });\nconst usedOptions = de.resolvedOptions();\n\nusedOptions.locale; // \"de\"\nusedOptions.usage; // \"sort\"\nusedOptions.sensitivity; // \"base\"\nusedOptions.ignorePunctuation; // false\nusedOptions.collation; // \"default\"\nusedOptions.numeric; // false\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.collator.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the Collator() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/resolvedOptions\n

\n
\n", + "global_objects/intl/datetimeformat/datetimeformat": "

Intl.DateTimeFormat() constructor

The Intl.DateTimeFormat() constructor creates Intl.DateTimeFormat objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.DateTimeFormat()\nnew Intl.DateTimeFormat(locales)\nnew Intl.DateTimeFormat(locales, options)\n\nIntl.DateTimeFormat()\nIntl.DateTimeFormat(locales)\nIntl.DateTimeFormat(locales, options)\n
\n

Note: Intl.DateTimeFormat() can be called with or without new. Both create a new Intl.DateTimeFormat instance. However, there's a special behavior when it's called without new and the this value is another Intl.DateTimeFormat instance; see Return value.

\n

Parameters

\n
\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

The following Unicode extension key is allowed:

nu

See numberingSystem.

ca

See calendar.

hc

See hourCycle.

These keys can also be set with options (as listed below). When both are set, the options property takes precedence.

\noptions Optional\n

An object. For ease of reading, the property list is broken into sections based on their purposes, including locale options, date-time component options, and style shortcuts.

Locale options

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

calendar

The calendar to use, such as \"chinese\", \"gregory\", \"person\", and so on. For a list of supported calendar types, see Intl.Locale.prototype.getCalendars(). This option can also be set through the ca Unicode extension key; if both are provided, this options property takes precedence.

numberingSystem

The numbering system to use for number formatting, such as \"arab\", \"hans\", \"mathsans\", and so on. For a list of supported numbering system types, see Intl.Locale.prototype.getNumberingSystems(). This option can also be set through the nu Unicode extension key; if both are provided, this options property takes precedence.

hour12

Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent. This option overrides the hc locale extension tag and/or the hourCycle option in case both are present. It sets hourCycle to \"h11\" or \"h12\" when true, and \"h23\" or \"h24\" when false, the exact choice depending on the locale — for example, if the locale most prefers \"h23\" but hour12 is true, then the final hour cycle is \"h11\".

hourCycle

The hour cycle to use. Possible values are \"h11\", \"h12\", \"h23\", and \"h24\". This option can also be set through the hc Unicode extension key; if both are provided, this options property takes precedence.

timeZone

The time zone to use. The only value implementations must recognize is \"UTC\"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as \"Asia/Shanghai\", \"Asia/Kolkata\", \"America/New_York\".

Date-time component options

weekday

The representation of the weekday. Possible values are:

\"long\"

E.g., Thursday

\"short\"

E.g., Thu

\"narrow\"

E.g., T. Two weekdays may have the same narrow style for some locales (e.g. Tuesday's narrow style is also T).

era

The representation of the era. Possible values are:

\"long\"

E.g., Anno Domini

\"short\"

E.g., AD

\"narrow\"

E.g., A

year

The representation of the year. Possible values are \"numeric\" and \"2-digit\".

month

The representation of the month. Possible values are:

\"numeric\"

E.g., 3

\"2-digit\"

E.g., 03

\"long\"

E.g., March

\"short\"

E.g., Mar

\"narrow\"

E.g., M). Two months may have the same narrow style for some locales (e.g. May's narrow style is also M).

day

The representation of the day. Possible values are \"numeric\" and \"2-digit\".

dayPeriod

The formatting style used for day periods like \"in the morning\", \"am\", \"noon\", \"n\" etc. Possible values are \"narrow\", \"short\", and \"long\".

Note: This option only has an effect if a 12-hour clock (hourCycle: \"h12\" or hourCycle: \"h11\") is used. Many locales use the same string irrespective of the width specified.

hour

The representation of the hour. Possible values are \"numeric\" and \"2-digit\".

minute

The representation of the minute. Possible values are \"numeric\" and \"2-digit\".

second

The representation of the second. Possible values are \"numeric\" and \"2-digit\".

fractionalSecondDigits

The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from 1 to 3.

timeZoneName

The localized representation of the time zone name. Possible values are:

\"long\"

Long localized form (e.g., Pacific Standard Time, Nordamerikanische Westküsten-Normalzeit)

\"short\"

Short localized form (e.g.: PST, GMT-8)

\"shortOffset\"

Short localized GMT format (e.g., GMT-8)

\"longOffset\"

Long localized GMT format (e.g., GMT-08:00)

\"shortGeneric\"

Short generic non-location format (e.g.: PT, Los Angeles Zeit).

\"longGeneric\"

Long generic non-location format (e.g.: Pacific Time, Nordamerikanische Westküstenzeit)

Note: Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like \"Pacific Time\", but may fall back to a timezone like \"Los Angeles Time\".

The default value for each date-time component option is undefined, but if all component properties are undefined, then year, month, and day default to \"numeric\". If any of the date-time component options is specified, then dateStyle and timeStyle must be undefined.

formatMatcher

The format matching algorithm to use. Possible values are \"basic\" and \"best fit\"; the default is \"best fit\". Implementations are required to support displaying at least the following subsets of date-time components:

  • \nweekday, year, month, day, hour, minute, second\n
  • \nweekday, year, month, day\n
  • \nyear, month, day\n
  • \nyear, month\n
  • \nmonth, day\n
  • \nhour, minute, second\n
  • \nhour, minute\n

Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. The algorithm for \"best fit\" is implementation-defined, and \"basic\" is defined by the spec. This option is only used when both dateStyle and timeStyle are undefined (so that each date-time component's format is individually customizable).

Style shortcuts

dateStyle

The date formatting style to use when calling format(). Possible values are \"full\", \"long\", \"medium\", and \"short\".

timeStyle

The time formatting style to use when calling format(). Possible values are \"full\", \"long\", \"medium\", and \"short\".

Note: dateStyle and timeStyle can be used with each other, but not with other date-time component options (e.g. weekday, hour, month, etc.).

\n

Return value

\n
\n

A new Intl.DateTimeFormat object.

Note: The text below describes behavior that is marked by the specification as \"optional\". It may not work in all environments. Check the browser compatibility table.

Normally, Intl.DateTimeFormat() can be called with or without new, and a new Intl.DateTimeFormat instance is returned in both cases. However, if the this value is an object that is instanceof Intl.DateTimeFormat (doesn't necessarily mean it's created via new Intl.DateTimeFormat; just that it has Intl.DateTimeFormat.prototype in its prototype chain), then the value of this is returned instead, with the newly created Intl.DateTimeFormat object hidden in a [Symbol(IntlLegacyConstructedSymbol)] property (a unique symbol that's reused between instances).

\n

js

\n
const formatter = Intl.DateTimeFormat.call(\n  { __proto__: Intl.DateTimeFormat.prototype },\n  \"en-US\",\n  { dateStyle: \"full\" },\n);\nconsole.log(Object.getOwnPropertyDescriptors(formatter));\n// {\n//   [Symbol(IntlLegacyConstructedSymbol)]: {\n//     value: DateTimeFormat [Intl.DateTimeFormat] {},\n//     writable: false,\n//     enumerable: false,\n//     configurable: false\n//   }\n// }\n
\n

Note that there's only one actual Intl.DateTimeFormat instance here: the one hidden in [Symbol(IntlLegacyConstructedSymbol)]. Calling the format() and resolvedOptions() methods on formatter would correctly use the options stored in that instance, but calling all other methods (e.g. formatRange()) would fail: \"TypeError: formatRange method called on incompatible Object\", because those methods don't consult the hidden instance's options.

This behavior, called ChainDateTimeFormat, does not happen when Intl.DateTimeFormat() is called without new but with this set to anything else that's not an instanceof Intl.DateTimeFormat. If you call it directly as Intl.DateTimeFormat(), the this value is Intl, and a new Intl.DateTimeFormat instance is created normally.

\n

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Using DateTimeFormat

\n
\n

In basic use without specifying a locale, DateTimeFormat uses the default locale and default options.

\n

js

\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// toLocaleString without arguments depends on the implementation,\n// the default locale, and the default time zone\nconsole.log(new Intl.DateTimeFormat().format(date));\n// \"12/19/2012\" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)\n
\n
\n

Using timeStyle and dateStyle

\n
\n

js

\n
const shortTime = new Intl.DateTimeFormat(\"en\", {\n  timeStyle: \"short\",\n});\nconsole.log(shortTime.format(Date.now())); // \"1:31 PM\"\n\nconst shortDate = new Intl.DateTimeFormat(\"en\", {\n  dateStyle: \"short\",\n});\nconsole.log(shortDate.format(Date.now())); // \"07/07/20\"\n\nconst mediumTime = new Intl.DateTimeFormat(\"en\", {\n  timeStyle: \"medium\",\n  dateStyle: \"short\",\n});\nconsole.log(mediumTime.format(Date.now())); // \"07/07/20, 1:31:55 PM\"\n
\n

Using dayPeriod

\n
\n

Use the dayPeriod option to output a string for the times of day (\"in the morning\", \"at night\", \"noon\", etc.). Note, that this only works when formatting for a 12 hour clock (hourCycle: 'h12' or hourCycle: 'h11') and that for many locales the strings are the same irrespective of the value passed for the dayPeriod.

\n

js

\n
const date = Date.UTC(2012, 11, 17, 4, 0, 42);\n\nconsole.log(\n  new Intl.DateTimeFormat(\"en-GB\", {\n    hour: \"numeric\",\n    hourCycle: \"h12\",\n    dayPeriod: \"short\",\n    timeZone: \"UTC\",\n  }).format(date),\n);\n// 4 at night\"  (same formatting in en-GB for all dayPeriod values)\n\nconsole.log(\n  new Intl.DateTimeFormat(\"fr\", {\n    hour: \"numeric\",\n    hourCycle: \"h12\",\n    dayPeriod: \"narrow\",\n    timeZone: \"UTC\",\n  }).format(date),\n);\n// \"4 mat.\"  (same output in French for both narrow/short dayPeriod)\n\nconsole.log(\n  new Intl.DateTimeFormat(\"fr\", {\n    hour: \"numeric\",\n    hourCycle: \"h12\",\n    dayPeriod: \"long\",\n    timeZone: \"UTC\",\n  }).format(date),\n);\n// \"4 du matin\"\n
\n
\n

Using timeZoneName

\n
\n

Use the timeZoneName option to output a string for the timezone (\"GMT\", \"Pacific Time\", etc.).

\n

js

\n
const date = Date.UTC(2021, 11, 17, 3, 0, 42);\nconst timezoneNames = [\n  \"short\",\n  \"long\",\n  \"shortOffset\",\n  \"longOffset\",\n  \"shortGeneric\",\n  \"longGeneric\",\n];\n\nfor (const zoneName of timezoneNames) {\n  // Do something with currentValue\n  const formatter = new Intl.DateTimeFormat(\"en-US\", {\n    timeZone: \"America/Los_Angeles\",\n    timeZoneName: zoneName,\n  });\n  console.log(`${zoneName}: ${formatter.format(date)}`);\n}\n\n// Logs:\n// short: 12/16/2021, PST\n// long: 12/16/2021, Pacific Standard Time\n// shortOffset: 12/16/2021, GMT-8\n// longOffset: 12/16/2021, GMT-08:00\n// shortGeneric: 12/16/2021, PT\n// longGeneric: 12/16/2021, Pacific Time\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-datetimeformat-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
IntlLegacyConstructedSymbol91
57The fallback symbol property has description IntlFallback.
\n
91
79The fallback symbol property has description IntlFallback.
\n
54No77
44The fallback symbol property has description IntlFallback.
\n
14.191
57The fallback symbol property has description IntlFallback.
\n
91
57The fallback symbol property has description IntlFallback.
\n
5664
43The fallback symbol property has description IntlFallback.
\n
14.516.0
7.0The fallback symbol property has description IntlFallback.
\n
?16.0.0
8.0.0The fallback symbol property has description IntlFallback.
\n
DateTimeFormat2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the DateTimeFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
locales_parameter2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the DateTimeFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options_parameter2412291115104.4255614101.51.80.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat\n

\n
\n", + "global_objects/intl/datetimeformat/supportedlocalesof": "

Intl.DateTimeFormat.supportedLocalesOf()

The Intl.DateTimeFormat.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.DateTimeFormat.supportedLocalesOf(locales)\nIntl.DateTimeFormat.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.DateTimeFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.supportedlocalesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/supportedLocalesOf\n

\n
\n", + "global_objects/intl/datetimeformat/format": "

Intl.DateTimeFormat.prototype.format()

The format() method of Intl.DateTimeFormat instances formats a date according to the locale and formatting options of this Intl.DateTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
format(date)\n
\n

Parameters

\n
date

The date to format.

Return value

\n

A string representing the given date formatted according to the locale and formatting options of this Intl.DateTimeFormat object.

Examples

\n

Using format

\n
\n

Use the format getter function for formatting a single date, here for Serbia:

\n

js

\n
const options = {\n  weekday: \"long\",\n  year: \"numeric\",\n  month: \"long\",\n  day: \"numeric\",\n};\nconst dateTimeFormat = new Intl.DateTimeFormat(\"sr-RS\", options);\nconsole.log(dateTimeFormat.format(new Date()));\n// \"недеља, 7. април 2013.\"\n
\n
\n

Using format with map

\n
\n

Use the format getter function for formatting all dates in an array. Note that the function is bound to the Intl.DateTimeFormat from which it was obtained, so it can be passed directly to Array.prototype.map().

\n

js

\n
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];\nconst options = { year: \"numeric\", month: \"long\" };\nconst dateTimeFormat = new Intl.DateTimeFormat(\"pt-BR\", options);\nconst formatted = a.map(dateTimeFormat.format);\nconsole.log(formatted.join(\"; \"));\n// \"setembro de 2012; dezembro de 2012; abril de 2012\"\n
\n
\n

Avoid comparing formatted date values to static values

\n
\n

Most of the time, the formatting returned by format() is consistent. However, this might change in the future and isn't guaranteed for all the languages — output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text.

For this reason you cannot expect to be able to compare the results of format() to a static value:

\n

js

\n
let d = new Date(\"2019-01-01T00:00:00.000000Z\");\nlet formattedDate = Intl.DateTimeFormat(undefined, {\n  year: \"numeric\",\n  month: \"numeric\",\n  day: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n}).format(d);\n\n\"1.1.2019, 01:00:00\" === formattedDate;\n// true in Firefox and others\n// false in IE and Edge\n
\n

Note: See also this StackOverflow thread for more details and examples.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.format
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
format2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format\n

\n
\n", + "global_objects/intl/datetimeformat/formatrange": "

Intl.DateTimeFormat.prototype.formatRange()

The formatRange() method of Intl.DateTimeFormat instances formats a date range in the most concise way based on the locales and options provided when instantiating this Intl.DateTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatRange(startDate, endDate)\n
\n

Parameters

\n
startDate

A Date object representing the start of the date range.

endDate

A Date object representing the end of the date range.

Return value

\n

A string representing the given date range formatted according to the locale and formatting options of this Intl.DateTimeFormat object.

Examples

\n

Basic formatRange usage

\n
\n

This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating Intl.DateTimeFormat.

\n

js

\n
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT\nconst date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT\nconst date3 = new Date(Date.UTC(1906, 0, 20, 10, 0, 0)); // Sat, 20 Jan 1906 10:00:00 GMT\n\nconst fmt1 = new Intl.DateTimeFormat(\"en\", {\n  year: \"2-digit\",\n  month: \"numeric\",\n  day: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n});\nconsole.log(fmt1.format(date1)); // '1/10/06, 10:00 AM'\nconsole.log(fmt1.formatRange(date1, date2)); // '1/10/06, 10:00 – 11:00 AM'\nconsole.log(fmt1.formatRange(date1, date3)); // '1/10/06, 10:00 AM – 1/20/07, 10:00 AM'\n\nconst fmt2 = new Intl.DateTimeFormat(\"en\", {\n  year: \"numeric\",\n  month: \"short\",\n  day: \"numeric\",\n});\nconsole.log(fmt2.format(date1)); // 'Jan 10, 1906'\nconsole.log(fmt2.formatRange(date1, date2)); // 'Jan 10, 1906'\nconsole.log(fmt2.formatRange(date1, date3)); // 'Jan 10 – 20, 1906'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.formatRange
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatRange767991No6314.17676915414.512.01.8
12.9.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatRange\n

\n
\n", + "global_objects/intl/datetimeformat/formatrangetoparts": "

Intl.DateTimeFormat.prototype.formatRangeToParts()

The formatRangeToParts() method of Intl.DateTimeFormat instances returns an array of locale-specific tokens representing each part of the formatted date range produced by this Intl.DateTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatRangeToParts(startDate, endDate)\n
\n

Examples

\n

Basic formatRangeToParts usage

\n
\n

This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.

Note: The return values shown in your locale may differ from those listed below.

\n

js

\n
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT\nconst date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT\n\nconst fmt = new Intl.DateTimeFormat(\"en\", {\n  hour: \"numeric\",\n  minute: \"numeric\",\n});\n\nconsole.log(fmt.formatRange(date1, date2)); // '10:00 – 11:00 AM'\n\nfmt.formatRangeToParts(date1, date2);\n// [\n//   { type: 'hour',      value: '10',  source: \"startRange\" },\n//   { type: 'literal',   value: ':',   source: \"startRange\" },\n//   { type: 'minute',    value: '00',  source: \"startRange\" },\n//   { type: 'literal',   value: ' – ', source: \"shared\"     },\n//   { type: 'hour',      value: '11',  source: \"endRange\"   },\n//   { type: 'literal',   value: ':',   source: \"endRange\"   },\n//   { type: 'minute',    value: '00',  source: \"endRange\"   },\n//   { type: 'literal',   value: ' ',   source: \"shared\"     },\n//   { type: 'dayPeriod', value: 'AM',  source: \"shared\"     }\n// ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.DateTimeFormat.prototype.formatRangeToParts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatRangeToParts767991No6314.17676915414.512.01.8
12.9.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatRangeToParts\n

\n
\n", + "global_objects/intl/datetimeformat/formattoparts": "

Intl.DateTimeFormat.prototype.formatToParts()

The formatToParts() method of Intl.DateTimeFormat instances allows locale-aware formatting of strings produced by this Intl.DateTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatToParts(date)\n
\n

Parameters

\n
\ndate Optional\n

The date to format.

Return value

\n

An Array of objects containing the formatted date in parts.

Description

\n
\n

The formatToParts() method is useful for custom formatting of date strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts() method returns, looks like this:

\n

js

\n
[\n  { type: \"day\", value: \"17\" },\n  { type: \"weekday\", value: \"Monday\" },\n];\n
\n

Possible types are the following:

day

The string used for the day, for example \"17\".

dayPeriod

The string used for the day period, for example, \"AM\", \"PM\", \"in the morning\", or \"noon\"

era

The string used for the era, for example \"BC\" or \"AD\".

fractionalSecond

The string used for the fractional seconds, for example \"0\" or \"00\" or \"000\".

hour

The string used for the hour, for example \"3\" or \"03\".

literal

The string used for separating date and time values, for example \"/\", \",\", \"o'clock\", \"de\", etc.

minute

The string used for the minute, for example \"00\".

month

The string used for the month, for example \"12\".

relatedYear

The string used for the related 4-digit Gregorian year, in the event that the calendar's representation would be a yearName instead of a year, for example \"2019\".

second

The string used for the second, for example \"07\" or \"42\".

timeZone

The string used for the name of the time zone, for example \"UTC\". Default is the timezone of the current environment.

weekday

The string used for the weekday, for example \"M\", \"Monday\", or \"Montag\".

year

The string used for the year, for example \"2012\" or \"96\".

yearName

The string used for the yearName in relevant contexts, for example \"geng-zi\"

\n

Examples

\n
\n

DateTimeFormat outputs localized, opaque strings that cannot be manipulated directly:

\n

js

\n
const date = Date.UTC(2012, 11, 17, 3, 0, 42);\n\nconst formatter = new Intl.DateTimeFormat(\"en-us\", {\n  weekday: \"long\",\n  year: \"numeric\",\n  month: \"numeric\",\n  day: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n  fractionalSecondDigits: 3,\n  hour12: true,\n  timeZone: \"UTC\",\n});\n\nformatter.format(date);\n// \"Monday, 12/17/2012, 3:00:42.000 AM\"\n
\n

However, in many User Interfaces there is a desire to customize the formatting of this string. The formatToParts method enables locale-aware formatting of strings produced by DateTimeFormat formatters by providing you the string in parts:

\n

js

\n
formatter.formatToParts(date);\n\n// return value:\n[\n  { type: \"weekday\", value: \"Monday\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"month\", value: \"12\" },\n  { type: \"literal\", value: \"/\" },\n  { type: \"day\", value: \"17\" },\n  { type: \"literal\", value: \"/\" },\n  { type: \"year\", value: \"2012\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"hour\", value: \"3\" },\n  { type: \"literal\", value: \":\" },\n  { type: \"minute\", value: \"00\" },\n  { type: \"literal\", value: \":\" },\n  { type: \"second\", value: \"42\" },\n  { type: \"fractionalSecond\", value: \"000\" },\n  { type: \"literal\", value: \" \" },\n  { type: \"dayPeriod\", value: \"AM\" },\n];\n
\n

Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map(), arrow functions, a switch statement, template literals, and Array.prototype.join().

\n

js

\n
const dateString = formatter\n  .formatToParts(date)\n  .map(({ type, value }) => {\n    switch (type) {\n      case \"dayPeriod\":\n        return `<em>${value}</em>`;\n      default:\n        return value;\n    }\n  })\n  .join(\"\");\n
\n

This will emphasize the day period when using the formatToParts() method.

\n

js

\n
console.log(formatter.format(date));\n// \"Monday, 12/17/2012, 3:00:42.000 AM\"\n\nconsole.log(dateString);\n// \"Monday, 12/17/2012, 3:00:42.000 <em>AM</em>\"\n
\n
\n

Named Years and Mixed calendars

\n
\n

In some cases, calendars use named years. Chinese and Tibetan calendars, for example, use a 60-year sexagenary cycle of named years. These years are disambiguated by relationship to corresponding years on the Gregorian calendar. When this is the case, the result of formatToParts() will contain an entry for relatedYear when a year would normally be present, containing the 4-digit Gregorian year, instead of an entry for year. Setting an entry in the bag for year (with any value) will yield both the and the yearName Gregorian relatedYear:

\n

js

\n
const opts = { year: \"numeric\", month: \"numeric\", day: \"numeric\" };\nconst df = new Intl.DateTimeFormat(\"zh-u-ca-chinese\", opts);\ndf.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));\n\n// return value\n[\n  { type: \"relatedYear\", value: \"2012\" },\n  { type: \"literal\", value: \"年\" },\n  { type: \"month\", value: \"十一月\" },\n  { type: \"day\", value: \"4\" },\n];\n
\n

If the year option is not set in the bag (to any value), the result will include only the relatedYear:

\n

js

\n
const df = new Intl.DateTimeFormat(\"zh-u-ca-chinese\");\ndf.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));\n\n// return value\n[\n  { type: \"relatedYear\", value: \"2012\" },\n  { type: \"literal\", value: \"年\" },\n  { type: \"month\", value: \"十一月\" },\n  { type: \"day\", value: \"4\" },\n];\n
\n

In cases where the year would be output, .format() may commonly present these side-by-side:

\n

js

\n
const df = new Intl.DateTimeFormat(\"zh-u-ca-chinese\", { year: \"numeric\" });\ndf.format(Date.UTC(2012, 11, 17, 3, 0, 42)); // 2012壬辰年\n
\n

This also makes it possible to mix locale and calendar in both format:

\n

js

\n
const df = new Intl.DateTimeFormat(\"en-u-ca-chinese\", { year: \"numeric\" });\nconst date = Date.UTC(2012, 11, 17, 3, 0, 42);\ndf.format(date); // 2012(ren-chen)\n
\n

And formatToParts:

\n

js

\n
const opts = { month: \"numeric\", day: \"numeric\", year: \"numeric\" };\nconst df = new Intl.DateTimeFormat(\"en-u-ca-chinese\", opts);\nconst date = Date.UTC(2012, 11, 17, 3);\ndf.formatToParts(date);\n// [\n//   { type: 'month', value: '11' },\n//   { type: 'literal', value: '/' },\n//   { type: 'day', value: '4' },\n//   { type: 'literal', value: '/' },\n//   { type: 'relatedYear', value: '2012' }\n// ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.DateTimeFormat.prototype.formatToParts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatToParts
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
1851No
44Before version 58, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 58 and later use the specification defined dayPeriod. See Chromium bug 865351.
11
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
57Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
56
43Before version 50, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 50 and later use the specification defined dayPeriod. See Chromium bug 865351.
11
7.0Before version 71, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 71 and later use the specification defined dayPeriod. See Chromium bug 865351.
1.8
8.0.0[\"Before version 12.0.0, formatToParts() returned an object with an incorrectly cased type key of dayperiod. Version 12.0.0 and later use the specification defined dayPeriod. See Chromium bug 865351.\", \"Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.\"]
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts\n

\n
\n", + "global_objects/intl/datetimeformat/resolvedoptions": "

Intl.DateTimeFormat.prototype.resolvedOptions()

The resolvedOptions() method of Intl.DateTimeFormat instances returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this Intl.DateTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

A new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given Intl.DateTimeFormat object.

Description

\n
\n

The resulting object has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

calendar

E.g. \"gregory\"

numberingSystem

The values requested using the Unicode extension keys \"ca\" and \"nu\" or filled in as default values.

timeZone

The value provided for this property in the options argument; defaults to the runtime's default time zone. Should never be undefined.

hour12

The value provided for this property in the options argument or filled in as a default.

\nweekday, era, year, month, day, hour, minute, second, timeZoneName\n

The values resulting from format matching between the corresponding properties in the options argument and the available combinations and representations for date-time formatting in the selected locale. Some of these properties may not be present, indicating that the corresponding components will not be represented in formatted output.

\n

Examples

\n

Using the resolvedOptions method

\n
\n

js

\n
const germanFakeRegion = new Intl.DateTimeFormat(\"de-XX\", { timeZone: \"UTC\" });\nconst usedOptions = germanFakeRegion.resolvedOptions();\n\nusedOptions.locale; // \"de\"\nusedOptions.calendar; // \"gregory\"\nusedOptions.numberingSystem; // \"latn\"\nusedOptions.timeZone; // \"UTC\"\nusedOptions.month; // \"numeric\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the DateTimeFormat() constructor for more details.
computed_timezone351453No301037355622103.01.88.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions\n

\n
\n", + "global_objects/intl/displaynames/displaynames": "

Intl.DisplayNames() constructor

The Intl.DisplayNames() constructor creates Intl.DisplayNames objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.DisplayNames(locales, options)\n
\n

Note: Intl.DisplayNames() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
locales

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

options

An object containing the following properties, in the order they are retrieved:

\nlocaleMatcher Optional\n

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

\nstyle Optional\n

The formatting style to use. Possible values are \"narrow\", \"short\", and \"long\"; the default is \"long\".

type

The type of display names to return from of(). Possible values are \"language\", \"region\", \"script\", \"currency\", \"calendar\", and \"dateTimeField\".

\nfallback Optional\n

What to return from of() if the input is structurally valid but there's no matching display name. Possible values are:

\n\"code\" (default)

Return the input code itself.

\"none\"

Return undefined.

\nlanguageDisplay Optional\n

How language names should be displayed. Only usable along with type: \"language\". Possible values are:

\n\"dialect\" (default)

Display special regional dialects using their own name. E.g. \"nl-BE\" will be displayed as \"Flemish\".

\"standard\"

Display all languages using standard format. E.g. \"nl-BE\" will be displayed as \"Dutch (Belgium)\".

Exceptions

\n
TypeError

Thrown if options.type is not provided.

RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Basic usage

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
console.log(new Intl.DisplayNames([], { type: \"language\" }).of(\"US\"));\n// 'us'\n
\n
\n

Using type dateTimeField\n

\n
\n

Example using dateTimeField as a type option, will return the localized date time names strings.

\n

js

\n
const dn = new Intl.DisplayNames(\"pt\", { type: \"dateTimeField\" });\nconsole.log(dn.of(\"era\")); // 'era'\nconsole.log(dn.of(\"year\")); // 'ano'\nconsole.log(dn.of(\"month\")); // 'mês'\nconsole.log(dn.of(\"quarter\")); // 'trimestre'\nconsole.log(dn.of(\"weekOfYear\")); // 'semana'\nconsole.log(dn.of(\"weekday\")); // 'dia da semana'\nconsole.log(dn.of(\"dayPeriod\")); // 'AM/PM'\nconsole.log(dn.of(\"day\")); // 'dia'\nconsole.log(dn.of(\"hour\")); // 'hora'\nconsole.log(dn.of(\"minute\")); // 'minuto'\nconsole.log(dn.of(\"second\")); // 'segundo'\n
\n
\n

Using type calendar\n

\n
\n

Example using calendar as a type option, will return the localized calendar names strings.

\n

js

\n
const dn = new Intl.DisplayNames(\"en\", { type: \"calendar\" });\nconsole.log(dn.of(\"roc\")); // 'Minguo Calendar'\nconsole.log(dn.of(\"gregory\")); // 'Gregorian Calendar'\nconsole.log(dn.of(\"chinese\")); // 'Chinese Calendar'\n
\n
\n

Using type language with languageDisplay\n

\n
\n

Example using language as a type with languageDisplay options.

\n

js

\n
// Using `dialect` option\nconst dnDialect = new Intl.DisplayNames(\"en\", {\n  type: \"language\",\n  languageDisplay: \"dialect\",\n});\nconsole.log(dnDialect.of(\"en-GB\")); // 'British English'\n\n// Using `standard` option\nconst dnStd = new Intl.DisplayNames(\"en\", {\n  type: \"language\",\n  languageDisplay: \"standard\",\n});\nconsole.log(dnStd.of(\"en-GB\")); // 'English (United Kingdom)'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-displaynames-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DisplayNames818186No6814.18181865814.513.01.814.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames\n

\n
\n", + "global_objects/intl/displaynames/supportedlocalesof": "

Intl.DisplayNames.supportedLocalesOf()

The Intl.DisplayNames.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.

\n

Syntax

\n
\n

js

\n
Intl.DisplayNames.supportedLocalesOf(locales)\nIntl.DisplayNames.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in display names, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to display names nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.DisplayNames.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.DisplayNames.supportedLocalesOf
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf818186No6814.18181865814.513.01.814.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf\n

\n
\n", + "global_objects/intl/displaynames/of": "

Intl.DisplayNames.prototype.of()

The of() method of Intl.DisplayNames instances receives a code and returns a string based on the locale and options provided when instantiating this Intl.DisplayNames object.

\n

Try it

\n

Syntax

\n
\n

js

\n
of(code)\n
\n

Parameters

\n
code

The code to provide depends on the type:

Return value

\n
\n

A language-specific formatted string, or undefined if there's no data for the input and fallback is \"none\".

Note: fallback is only used if code is structurally valid. See using fallback.

\n

Exceptions

\n
RangeError

Thrown if code is not structurally valid for the given type.

Examples

\n

Using the of method

\n
\n

js

\n
const regionNames = new Intl.DisplayNames(\"en\", { type: \"region\" });\nregionNames.of(\"419\"); // \"Latin America\"\n\nconst languageNames = new Intl.DisplayNames(\"en\", { type: \"language\" });\nlanguageNames.of(\"fr\"); // \"French\"\n\nconst currencyNames = new Intl.DisplayNames(\"en\", { type: \"currency\" });\ncurrencyNames.of(\"EUR\"); // \"Euro\"\n
\n

Using fallback

\n
\n

When the Intl.DisplayNames is constructed with fallback: \"code\", the of() method will return the code if the input looks structurally valid but there's no data for the input. If fallback is \"none\", undefined is returned.

\n

js

\n
console.log(\n  new Intl.DisplayNames(\"en\", { type: \"region\", fallback: \"code\" }).of(\"ZL\"),\n); // \"ZL\"\n\nconsole.log(\n  new Intl.DisplayNames(\"en\", { type: \"region\", fallback: \"none\" }).of(\"ZL\"),\n); // undefined\n
\n

However, this only applies if the code is structurally valid. For example, if type is \"region\" but code does not follow the unicode_region_subtag grammar (2 alphabetic characters or 3 numeric characters), a RangeError is directly thrown instead of using the fallback.

\n

js

\n
console.log(\n  new Intl.DisplayNames(\"en\", { type: \"region\", fallback: \"code\" }).of(\"ZLC\"),\n); // throws RangeError: invalid value \"ZLC\" for option region\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.DisplayNames.prototype.of
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
of818186No6814.18181865814.513.01.814.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of\n

\n
\n", + "global_objects/intl/displaynames/resolvedoptions": "

Intl.DisplayNames.prototype.resolvedOptions()

The resolvedOptions() method of Intl.DisplayNames instances returns a new object with properties reflecting the locale and style formatting options computed during the construction of this Intl.DisplayNames object.

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

An object with properties reflecting the locale and formatting options computed during the construction of the given Intl.DisplayNames object.

Description

\n
\n

The object returned by resolvedOptions() has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

style

The value provided for this property in the options argument of the constructor or the default value (\"long\"). Its value is either \"long\", \"short\", or \"narrow\".

type

The value provided for this property in the options argument of the constructor or the default value (\"language\"). Its value is either \"language\", \"region\", \"script\", or \"currency\".

fallback

The value provided for this property in the options argument of the constructor or the default value (\"code\"). Its value is either \"code\" or \"none\".

\n

Examples

\n

Using resolvedOptions

\n
\n

js

\n
const displayNames = new Intl.DisplayNames([\"de-DE\"], { type: \"region\" });\n\nconst usedOptions = displayNames.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.style); // \"long\"\nconsole.log(usedOptions.type); // \"region\"\nconsole.log(usedOptions.fallback); // \"code\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.DisplayNames.prototype.resolvedOptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions818186No6814.18181865814.513.01.814.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions\n

\n
\n", + "global_objects/intl/durationformat/durationformat": "

Intl.DurationFormat() constructor

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Intl.DurationFormat() constructor creates Intl.DurationFormat objects.

\n
\n

Syntax

\n
\n
\n

js

\n
new Intl.DurationFormat()\nnew Intl.DurationFormat(locales)\nnew Intl.DurationFormat(locales, options)\n
\n

Note: Intl.DurationFormat() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

The following Unicode extension key is allowed:

nu

See numberingSystem.

This key can also be set with options (as listed below). When both are set, the options property takes precedence.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

numberingSystem

The numbering system to use for number formatting, such as \"arab\", \"hans\", \"mathsans\", and so on. For a list of supported numbering system types, see Intl.Locale.prototype.getNumberingSystems(). This option can also be set through the nu Unicode extension key; if both are provided, this options property takes precedence.

style

The style of the formatted duration. Possible values are:

\"long\"

E.g., 1 hour and 50 minutes

\n\"short\" (default)

E.g., 1 hr, 50 min

\"narrow\"

E.g., 1h 50m

\"digital\"

E.g., 1:50:00

years

The style of the formatted years. Possible values are \"long\", \"short\", and \"narrow\"; the default is options.style if it's not \"digital\", and \"short\" otherwise.

yearsDisplay

Whether to always display years, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if years is unspecified, and \"always\" otherwise.

months

The style of the formatted months. Possible values are \"long\", \"short\", and \"narrow\"; the default is options.style if it's not \"digital\", and \"short\" otherwise.

monthsDisplay

Whether to always display months, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if months is unspecified, and \"always\" otherwise.

weeks

The style of the formatted weeks. Possible values are \"long\", \"short\", and \"narrow\"; the default is options.style if it's not \"digital\", and \"short\" otherwise.

weeksDisplay

Whether to always display weeks, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if weeks is unspecified, and \"always\" otherwise.

days

The style of the formatted days. Possible values are \"long\", \"short\", and \"narrow\"; the default is options.style if it's not \"digital\", and \"short\" otherwise.

daysDisplay

Whether to always display days, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if days is unspecified, and \"always\" otherwise.

hours

The style of the formatted hours. Possible values are \"long\", \"short\", \"narrow\", \"numeric\", and \"2-digit\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.

hoursDisplay

Whether to always display hours, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if hours is unspecified and options.style is not \"digital\", and \"always\" otherwise.

minutes

The style of the formatted minutes.

  • If hours is \"numeric\" or \"2-digit\", possible values are \"numeric\" and \"2-digit\", and \"numeric\" is normalized to \"2-digit\"; the default is \"numeric\".
  • Otherwise, possible values are \"long\", \"short\", \"narrow\", \"numeric\", and \"2-digit\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.
minutesDisplay

Whether to always display minutes, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if minutes is unspecified and options.style is not \"digital\", and \"always\" otherwise.

seconds

The style of the formatted seconds.

  • If minutes is \"numeric\" or \"2-digit\", possible values are \"numeric\" and \"2-digit\", and \"numeric\" is normalized to \"2-digit\"; the default is \"numeric\".
  • Otherwise, possible values are \"long\", \"short\", \"narrow\", \"numeric\", and \"2-digit\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.
secondsDisplay

Whether to always display seconds, or only if nonzero. Possible values are \"always\" and \"auto\"; the default is \"auto\" if seconds is unspecified and options.style is not \"digital\", and \"always\" otherwise.

milliseconds

The style of the formatted milliseconds.

  • If seconds is \"numeric\" or \"2-digit\", the only possible value is \"numeric\"; the default is \"numeric\".
  • Otherwise, possible values are \"long\", \"short\", \"narrow\", and \"numeric\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.
millisecondsDisplay

Whether to always display milliseconds, or only if nonzero.

  • If seconds is \"numeric\" or \"2-digit\", the only possible value is \"auto\"; the default is only \"auto\" when milliseconds is unspecified.
  • Otherwise, possible values are \"always\" and \"auto\"; the default is \"auto\" if milliseconds is unspecified, and \"always\" otherwise.
microseconds

The style of the formatted microseconds.

  • If milliseconds is \"numeric\", the only possible value is \"numeric\"; the default is \"numeric\".
  • Otherwise, possible values are \"long\", \"short\", \"narrow\", and \"numeric\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.
microsecondsDisplay

Whether to always display microseconds, or only if nonzero.

  • If milliseconds is \"numeric\", the only possible value is \"auto\"; the default is only \"auto\" when microseconds is unspecified.
  • Otherwise, possible values are \"always\" and \"auto\"; the default is \"auto\" if microseconds is unspecified, and \"always\" otherwise.
nanoseconds

The style of the formatted nanoseconds.

  • If microseconds is \"numeric\", the only possible value is \"numeric\"; the default is \"numeric\".
  • Otherwise, possible values are \"long\", \"short\", \"narrow\", and \"numeric\"; the default is options.style if it's not \"digital\", and \"numeric\" otherwise.
nanosecondsDisplay

Whether to always display nanoseconds, or only if nonzero.

  • If microseconds is \"numeric\", the only possible value is \"auto\"; the default is only \"auto\" when nanoseconds is unspecified.
  • Otherwise, possible values are \"always\" and \"auto\"; the default is \"auto\" if nanoseconds is unspecified, and \"always\" otherwise.
fractionalDigits

Number of how many fractional second digits to display in the output. Possible values are from 0 to 9; the default is undefined (include as many fractional digits as necessary).

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Description

\n
\n

For each time segment, an Intl.NumberFormat object is constructed under the hood. It uses the following options (see Intl.NumberFormat() for details):

When milliseconds, microseconds, or nanoseconds uses the \"numeric\" style, the following options are also used:

When the time segment uses the \"2-digit\" style, the following options are also used:

When the time segment uses the \"long\", \"short\", or \"narrow\" style, the following options are also used:

\n

Examples

\n

Using the Intl.DurationFormat() constructor

\n
\n

js

\n
const duration = {\n  hours: 2,\n  minutes: 20,\n  seconds: 35,\n};\n\nconsole.log(new Intl.DurationFormat(\"pt\", { style: \"long\" }).format(duration));\n// \"2 horas, 20 minutos e 35 segundos\"\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# sec-intl-durationformat-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
DurationFormatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/DurationFormat\n

\n
\n", + "global_objects/intl/durationformat/supportedlocalesof": "

Intl.DurationFormat.supportedLocalesOf()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Intl.DurationFormat.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in duration formatting without having to fall back to the runtime's default locale.

\n
\n

Syntax

\n
\n

js

\n
Intl.DurationFormat.supportedLocalesOf(locales)\nIntl.DurationFormat.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in duration formatting without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in duration formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to duration formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.DurationFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# sec-Intl.DurationFormat.supportedLocalesOf
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOfNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/supportedLocalesOf\n

\n
\n", + "global_objects/intl/durationformat/format": "

Intl.DurationFormat.prototype.format()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The format() method of Intl.DurationFormat instances formats a duration according to the locale and formatting options of this Intl.DurationFormat object.

\n
\n

Syntax

\n
\n

js

\n
format(duration)\n
\n

Parameters

\n
duration

The duration object to be formatted. It should include some or all of the following properties: months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds.

Return value

\n

A string representing the given duration formatted according to the locale and formatting options of this Intl.DurationFormat object.

Examples

\n

Using format()

\n
\n

The following example shows how to create a Duration formatter using the English language.

\n

js

\n
const duration = {\n  years: 1,\n  months: 2,\n  weeks: 3,\n  days: 3,\n  hours: 4,\n  minutes: 5,\n  seconds: 6,\n  milliseconds: 7,\n  microseconds: 8,\n  nanoseconds: 9,\n};\n\n// Without options, style defaults to \"short\"\nnew Intl.DurationFormat(\"en\").format(duration);\n// \"1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\"\n\n// With style set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).format(duration);\n// \"1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds\"\n\n// With style set to \"narrow\"\nnew Intl.DurationFormat(\"en\", { style: \"narrow\" }).format(duration);\n// \"1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\"\n
\n
\n

Using format() with different locales and styles

\n
\n

js

\n
const duration = {\n  hours: 1,\n  minutes: 46,\n  seconds: 40,\n};\n\n// With style set to \"long\" and locale \"fr-FR\"\nnew Intl.DurationFormat(\"fr-FR\", { style: \"long\" }).format(duration);\n// \"1 heure, 46 minutes et 40 secondes\"\n\n// With style set to \"short\" and locale set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"short\" }).format(duration);\n// \"1 hr, 46 min and 40 sec\"\n\n// With style set to \"short\" and locale set to \"pt\"\nnew Intl.DurationFormat(\"pt\", { style: \"narrow\" }).format(duration);\n// \"1h 46min 40s\"\n\n// With style set to \"digital\" and locale set to \"en\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"1:46:40\"\n\n// With style set to \"digital\", locale set to \"en\", and hours set to \"long\"\nnew Intl.DurationFormat(\"en\", { style: \"digital\", hours: \"long\" }).format(\n  duration,\n);\n// \"1 hour, 46:40\"\n
\n

Using format() with the fractionalDigits option

\n
\n

js

\n
const duration = {\n  hours: 11,\n  minutes: 30,\n  seconds: 12,\n  milliseconds: 345,\n  microseconds: 600,\n};\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\" }).format(duration);\n// \"11:30:12.3456\"\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 5 }).format(\n  duration,\n);\n// \"11:30:12.34560\"\n\nnew Intl.DurationFormat(\"en\", { style: \"digital\", fractionalDigits: 3 }).format(\n  duration,\n);\n// \"11:30:12.346\"\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# sec-Intl.DurationFormat.prototype.format
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format\n

\n
\n", + "global_objects/intl/durationformat/formattoparts": "

Intl.DurationFormat.prototype.formatToParts()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The formatToParts() method of Intl.DurationFormat instances allows locale-aware formatting of strings produced by Intl.DurationFormat formatters.

\n
\n

Syntax

\n
\n

js

\n
formatToParts(duration)\n
\n

Parameters

\n
\nduration Optional\n

The duration object to be formatted. It should include some or all of the following properties: \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\", \"microseconds\", \"nanoseconds\".

Return value

\n

An Array of objects containing the formatted duration in parts.

Description

\n
\n

The formatToParts() method is useful for custom formatting of duration objects. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts() method returns, looks like this:

\n

js

\n
[\n  { type: \"integer\", value: \"7\", unit: \"hour\" },\n  { type: \"literal\", value: \" \", unit: \"hour\" },\n  { type: \"unit\", value: \"hr\", unit: \"hour\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"integer\", value: \"8\", unit: \"minute\" },\n  { type: \"literal\", value: \" \", unit: \"minute\" },\n  { type: \"unit\", value: \"min\", unit: \"minute\" },\n];\n
\n
\n

Examples

\n
\n

The formatToParts method enables locale-aware formatting of strings produced by DurationFormat formatters by providing you the string in parts:

\n

js

\n
const duration = {\n  hours: 7,\n  minutes: 8,\n  seconds: 9,\n  milliseconds: 123,\n  microseconds: 456,\n  nanoseconds: 789,\n};\n\nnew Intl.DurationFormat(\"en\", { style: \"long\" }).formatToParts(duration);\n\n// Returned value:\n[\n  { type: \"integer\", value: \"7\", unit: \"hour\" },\n  { type: \"literal\", value: \" \", unit: \"hour\" },\n  { type: \"unit\", value: \"hours\", unit: \"hour\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"integer\", value: \"8\", unit: \"minute\" },\n  { type: \"literal\", value: \" \", unit: \"minute\" },\n  { type: \"unit\", value: \"minutes\", unit: \"minute\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"integer\", value: \"9\", unit: \"second\" },\n  { type: \"literal\", value: \" \", unit: \"second\" },\n  { type: \"unit\", value: \"seconds\", unit: \"second\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"integer\", value: \"123\", unit: \"millisecond\" },\n  { type: \"literal\", value: \" \", unit: \"millisecond\" },\n  { type: \"unit\", value: \"milliseconds\", unit: \"millisecond\" },\n  { type: \"literal\", value: \", \" },\n  { type: \"integer\", value: \"456\", unit: \"microsecond\" },\n  { type: \"literal\", value: \" \", unit: \"microsecond\" },\n  { type: \"unit\", value: \"microseconds\", unit: \"microsecond\" },\n  { type: \"literal\", value: \" and \" },\n  { type: \"integer\", value: \"789\", unit: \"nanosecond\" },\n  { type: \"literal\", value: \" \", unit: \"nanosecond\" },\n  { type: \"unit\", value: \"nanoseconds\", unit: \"nanosecond\" },\n];\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# sec-Intl.DurationFormat.prototype.formatToParts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatToPartsNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/formatToParts\n

\n
\n", + "global_objects/intl/durationformat/resolvedoptions": "

Intl.DurationFormat.prototype.resolvedOptions()

\n

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The resolvedOptions() method of Intl.DurationFormat instances returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this Intl.DurationFormat object.

\n
\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

A new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given Intl.DateTimeFormat object.

Description

\n
\n

The resulting object has the following properties:

locale

The BCP 47 language tag for the locale used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

style

One of the strings \"long\", \"short\", \"narrow\", or \"digital\" identifying the duration formatting style used.

years

One of the strings \"long\", \"short\", or \"narrow\" identifying the formatting style used for the years field.

yearsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the years field.

months

One of the strings \"long\", \"short\", and \"narrow\" identifying the formatting style used for the months field.

monthsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the months field.

weeks

One of the strings \"long\", \"short\", and \"narrow\" identifying the formatting style used for the weeks field.

weeksDisplay

One of the strings \"auto\" or \"always\" identifying when to display the weeks field.

days

One of the strings \"long\", \"short\", and \"narrow\" identifying the formatting style used for the days field.

daysDisplay

One of the strings \"auto\" or \"always\" identifying when to display the days field.

hours

One of the strings \"long\", \"short\", \"narrow\", \"2-digit\", or \"numeric\" identifying the formatting style used for the hours field.

hoursDisplay

One of the strings \"auto\" or \"always\" identifying when to display the hours field.

minutes

One of the strings \"long\", \"short\", \"narrow\", \"2-digit\", or \"numeric\" identifying the formatting style used for the minutes field.

minutesDisplay

One of the strings \"auto\" or \"always\" identifying when to display the minutes field.

seconds

One of the strings \"long\", \"short\", \"narrow\", \"2-digit\", or \"numeric\" identifying the formatting style used for the seconds field.

secondsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the seconds field.

milliseconds

One of the strings \"long\", \"short\", \"narrow\", or \"numeric\" identifying the formatting style used for the milliseconds field.

millisecondsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the millisecondsDisplay field.

microseconds

One of the strings \"long\", \"short\", \"narrow\", or \"numeric\" identifying the formatting style used for the microseconds field.

microsecondsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the microsecondsDisplay field.

nanoseconds

One of the strings \"long\", \"short\", \"narrow\", or \"numeric\" identifying the formatting style used for the nanoseconds field.

nanosecondsDisplay

One of the strings \"auto\" or \"always\" identifying when to display the nanosecondsDisplay field.

fractionalDigits

A number, identifying the number of fractional digits used with numeric styles.

numberingSystem

The value provided for this property in the options argument, if present, or the value requested using the Unicode extension key nu or filled in as a default.

\n

Examples

\n

Using the resolvedOptions method

\n
\n

js

\n
const duration = new Intl.DurationFormat(\"en\");\nconst usedOptions = duration.resolvedOptions();\n\nusedOptions.locale; // \"en\"\nusedOptions.numberingSystem; // \"latn\"\nusedOptions.years; // \"long\"\nusedOptions.yearsDisplay; // \"auto\"\nusedOptions.style; // \"long\"\n
\n

Specifications

\n
\n\n\n
Specification
Intl.DurationFormat
# sec-Intl.DurationFormat.prototype.resolvedOptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptionsNoNoNoNoNo16.4NoNoNoNo16.4NoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/resolvedOptions\n

\n
\n", + "global_objects/intl/listformat/listformat": "

Intl.ListFormat() constructor

The Intl.ListFormat() constructor creates Intl.ListFormat objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.ListFormat()\nnew Intl.ListFormat(locales)\nnew Intl.ListFormat(locales, options)\n
\n

Note: Intl.ListFormat() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

type

Indicates the type of grouping. Possible values are:

\n\"conjunction\" (default)

For \"and\"-based grouping of the list items: \"A, B, and C\"

\"disjunction\"

For \"or\"-based grouping of the list items: \"A, B, or C\"

\"unit\"

For grouping the list items as a unit (neither \"and\"-based nor \"or\"-based): \"A, B, C\"

style

The grouping style (for example, whether list separators and conjunctions are included). Possible values are:

\n\"long\" (default)

E.g. \"A, B, and C\"

\"short\"

E.g. \"A, B, C\"

\"narrow\"

E.g. \"A B C\"

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Using format

\n
\n

The following example shows how to create a List formatter using the English language.

\n

js

\n
const list = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(new Intl.ListFormat(\"en-GB\", { style: \"long\" }).format(list));\n// Motorcycle, Bus and Car\n\nconsole.log(new Intl.ListFormat(\"en-US\", { style: \"long\" }).format(list));\n// Motorcycle, Bus, and Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-US\", { style: \"short\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus, & Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus, Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"disjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"disjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(new Intl.ListFormat(\"en-US\", { style: \"narrow\" }).format(list));\n// Motorcycle, Bus, Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-US\", { style: \"long\" }).format([\n    \"30 degrees\",\n    \"15 minutes\",\n    \"50 seconds\",\n  ]),\n);\n// 30 degrees, 15 minutes, and 50 seconds\n\nconsole.log(\n  new Intl.ListFormat(\"en-US\", { style: \"narrow\" }).format([\n    \"30 degrees\",\n    \"15 minutes\",\n    \"50 seconds\",\n  ]),\n);\n// 30 degrees, 15 minutes, 50 seconds\n\nconsole.log(\n  new Intl.ListFormat(\"en-US\", { style: \"narrow\", type: \"unit\" }).format([\n    \"30°\",\n    \"15′\",\n    \"50″\",\n  ]),\n);\n// 30° 15′ 50″\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-listformat-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
ListFormat727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the ListFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat\n

\n
\n", + "global_objects/intl/listformat/supportedlocalesof": "

Intl.ListFormat.supportedLocalesOf()

The Intl.ListFormat.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in list formatting without having to fall back to the runtime's default locale.

\n

Syntax

\n
\n

js

\n
Intl.ListFormat.supportedLocalesOf(locales)\nIntl.ListFormat.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in list formatting without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in list formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to list formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.ListFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.ListFormat.supportedLocalesOf
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf\n

\n
\n", + "global_objects/intl/listformat/format": "

Intl.ListFormat.prototype.format()

The format() method of Intl.ListFormat instances returns a string with a language-specific representation of the list.

\n

Try it

\n

Syntax

\n
\n

js

\n
format()\nformat(list)\n
\n

Parameters

\n
list

An iterable object, such as an Array.

Return value

\n

A language-specific formatted string representing the elements of the list

Description

\n

The format() method returns a string that has been formatted based on parameters provided in the Intl.ListFormat object. The locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list.

Examples

\n

Using format

\n
\n

The following example shows how to create a List formatter using the English language.

\n

js

\n
const list = [\"Motorcycle\", \"Bus\", \"Car\"];\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"long\", type: \"conjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus and Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"short\", type: \"disjunction\" }).format(\n    list,\n  ),\n);\n// Motorcycle, Bus or Car\n\nconsole.log(\n  new Intl.ListFormat(\"en-GB\", { style: \"narrow\", type: \"unit\" }).format(list),\n);\n// Motorcycle Bus Car\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.ListFormat.prototype.format
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
format727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format\n

\n
\n", + "global_objects/intl/listformat/formattoparts": "

Intl.ListFormat.prototype.formatToParts()

The formatToParts() method of Intl.ListFormat instances returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatToParts(list)\n
\n

Parameters

\n
list

An iterable object, such as an Array, to be formatted according to a locale.

Return value

\n

An Array of components which contains the formatted parts from the list.

Description

\n
\n

Whereas Intl.ListFormat.prototype.format() returns a string being the formatted version of the list (according to the given locale and style options), formatToParts() returns an array of the different components of the formatted string.

Each element of the resulting array has two properties: type and value. The type property may be either \"element\", which refers to a value from the list, or \"literal\" which refers to a linguistic construct. The value property gives the content, as a string, of the token.

The locale and style options used for formatting are given when constructing the Intl.ListFormat instance.

\n

Examples

\n

Using formatToParts

\n
\n

js

\n
const fruits = [\"Apple\", \"Orange\", \"Pineapple\"];\nconst myListFormat = new Intl.ListFormat(\"en-GB\", {\n  style: \"long\",\n  type: \"conjunction\",\n});\n\nconsole.table(myListFormat.formatToParts(fruits));\n// [\n//  { \"type\": \"element\", \"value\": \"Apple\" },\n//  { \"type\": \"literal\", \"value\": \", \" },\n//  { \"type\": \"element\", \"value\": \"Orange\" },\n//  { \"type\": \"literal\", \"value\": \", and \" },\n//  { \"type\": \"element\", \"value\": \"Pineapple\" }\n// ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.ListFormat.prototype.formatToParts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatToParts727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts\n

\n
\n", + "global_objects/intl/listformat/resolvedoptions": "

Intl.ListFormat.prototype.resolvedOptions()

The resolvedOptions() method of Intl.ListFormat instances returns a new object with properties reflecting the locale and style formatting options computed during the construction of this Intl.ListFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

An object with properties reflecting the locale and formatting options computed during the construction of the given Intl.ListFormat object.

Description

\n
\n

The object returned by resolvedOptions() has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

style

The value provided for this property in the options argument of the constructor or the default value (\"long\"). Its value is either \"long\", \"short\", or \"narrow\".

type

The value provided for this property in the options argument of the constructor or the default value (\"conjunction\"). Its value is either \"conjunction\", \"disjunction\", or \"unit\".

\n

Examples

\n

Using resolvedOptions

\n
\n

js

\n
const deListFormatter = new Intl.ListFormat(\"de-DE\", { style: \"short\" });\n\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.style); // \"short\"\nconsole.log(usedOptions.type); // \"conjunction\" (the default value)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.ListFormat.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions727978No60
14.1Only available on macOS Big Sur (11) and above.
7272795114.511.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the ListFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions\n

\n
\n", + "global_objects/intl/locale/language": "

Intl.Locale.prototype.language

The language accessor property of Intl.Locale instances returns the language associated with this locale.

\n

Description

\n

Language is one of the core features of a locale. The Unicode specification treats the language identifier of a locale as the language and the region together (to make a distinction between dialects and variations, e.g. British English vs. American English). The language property of a Intl.Locale returns strictly the locale's language subtag.

Examples

\n

Setting the language in the locale identifier string argument

\n
\n

In order to be a valid Unicode locale identifier, a string must start with the language subtag. The main argument to the Intl.Locale() constructor must be a valid Unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\");\nconsole.log(locale.language); // Prints \"en\"\n
\n
\n

Overriding language via the configuration object

\n
\n

While the language subtag must be specified, the Intl.Locale() constructor takes a configuration object, which can override the language subtag.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\", { language: \"es\" });\nconsole.log(locale.language); // Prints \"es\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.language
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
language747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/language\n

\n
\n", + "global_objects/intl/locale/script": "

Intl.Locale.prototype.script

The script accessor property of Intl.Locale instances returns the script used for writing the particular language used in this locale.

\n

Description

\n

A script, sometimes called writing system, is one of the core attributes of a locale. It indicates the set of symbols, or glyphs, that are used to write a particular language. For instance, the script associated with English is Latin, whereas the script typically associated with Korean is Hangul. In many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. There are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete Unicode language identifier.

Examples

\n

Setting the script in the locale identifier string argument

\n
\n

The script is the second part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the Intl.Locale() constructor. Note that the script is not a required part of a locale identifier.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\");\nconsole.log(locale.script); // Prints \"Latn\"\n
\n
\n

Setting the script via the configuration object

\n
\n

The Intl.Locale() constructor takes a configuration object, which can be used to set the script subtag and property.

\n

js

\n
const locale = new Intl.Locale(\"fr-FR\", { script: \"Latn\" });\nconsole.log(locale.script); // Prints \"Latn\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.script
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
script747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/script\n

\n
\n", + "global_objects/intl/locale/region": "

Intl.Locale.prototype.region

The region accessor property of Intl.Locale instances returns the region of the world (usually a country) associated with this locale.

\n

Description

\n

The region is an essential part of the locale identifier, as it places the locale in a specific area of the world. Knowing the locale's region is vital to identifying differences between locales. For example, English is spoken in the United Kingdom and the United States of America, but there are differences in spelling and other language conventions between those two countries. Knowing the locale's region helps JavaScript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world.

Examples

\n

Setting the region in the locale identifier string argument

\n
\n

The region is the third part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the Intl.Locale() constructor. The region is a mandatory part of a

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\");\nconsole.log(locale.region); // Prints \"US\"\n
\n
\n

Setting the region via the configuration object

\n
\n

The Intl.Locale() constructor takes a configuration object, which can be used to set the region subtag and property.

\n

js

\n
const locale = new Intl.Locale(\"fr-Latn\", { region: \"FR\" });\nconsole.log(locale.region); // Prints \"FR\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.region
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
region747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/region\n

\n
\n", + "global_objects/intl/locale/calendar": "

Intl.Locale.prototype.calendar

The calendar accessor property of Intl.Locale instances returns the calendar type for this locale.

\n

Description

\n
\n

While most of the world uses the Gregorian calendar, there are several regional calendar eras used around the world. The calendar property's value is set at construction time, either through the ca key of the locale identifier or through the calendar option of the Intl.Locale() constructor. The latter takes priority if they are both present; and if neither is present, the property has value undefined.

For a list of supported calendar types, see Intl.Locale.prototype.getCalendars().

The set accessor of calendar is undefined. You cannot change this property directly.

\n

Examples

\n

Like other locale subtags, the calendar type can be added to the Intl.Locale object via the locale string, or a configuration object argument to the constructor.

Adding a calendar type via the locale string

\n
\n

In the Unicode locale string spec, calendar era types are locale key \"extension subtags\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension. Thus, the calendar era type can be added to the initial locale identifier string that is passed into the Intl.Locale() constructor. To add the calendar type, first add the -u extension to the string. Next, add the -ca extension to indicate that you are adding a calendar type. Finally, add the calendar era type to the string.

\n

js

\n
const locale = new Intl.Locale(\"fr-FR-u-ca-buddhist\");\nconsole.log(locale.calendar); // Prints \"buddhist\"\n
\n
\n

Adding a calendar type via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can contain any of several extension types, including calendars. Set the calendar property of the configuration object to your desired calendar era, and then pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"fr-FR\", { calendar: \"buddhist\" });\nconsole.log(locale.calendar); // \"buddhist\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.calendar
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
calendar747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar\n

\n
\n", + "global_objects/intl/locale/casefirst": "

Intl.Locale.prototype.caseFirst

The caseFirst accessor property of Intl.Locale instances returns whether case is taken into account for this locale's collation rules.

\n

Description

\n
\n

A locale's collation rules are used to determine how strings are ordered in that locale. Certain locales use a character's case (UPPERCASE or lowercase) in the collation process. This additional rule can be expressed in a Intl.Locale object's caseFirst property.

There are 3 values that the caseFirst property can have, outlined in the table below.

\n

\ncaseFirst values

\n
Value Description
upper Upper case to be sorted before lower case.
lower Lower case to be sorted before upper case.
false No special case ordering.

Examples

\n

Setting the caseFirst value via the locale string

\n
\n

In the Unicode locale string spec, the values that caseFirst represents correspond to the key kf. kf is treated as a locale string \"extension subtag\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key. Thus, the caseFirst value can be added to the initial locale identifier string that is passed into the Locale constructor. To add the caseFirst value, first add the -u extension key to the string. Next, add the -kf extension key to indicate that you are adding a value for caseFirst. Finally, add the caseFirst value to the string.

\n

js

\n
const locale = new Intl.Locale(\"fr-Latn-FR-u-kf-upper\");\nconsole.log(locale.caseFirst); // Prints \"upper\"\n
\n
\n

Setting the caseFirst value via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can be used to pass extension types. Set the caseFirst property of the configuration object to your desired caseFirst value, and then pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\", { caseFirst: \"lower\" });\nconsole.log(locale.caseFirst); // Prints \"lower\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.caseFirst
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
caseFirst747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/caseFirst\n

\n
\n", + "global_objects/intl/locale/collation": "

Intl.Locale.prototype.collation

The collation accessor property of Intl.Locale instances returns the collation type for this locale, which is used to order strings according to the locale's rules.

\n

Description

\n
\n

Collation is the process of ordering strings of characters. It is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. While the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. The collation property's value is set at construction time, either through the co key of the locale identifier or through the collation option of the Intl.Locale() constructor. The latter takes priority if they are both present; and if neither is present, the property has value undefined.

For a list of supported collation types, see Intl.Locale.prototype.getCollations().

The set accessor of collation is undefined. You cannot change this property directly.

\n

Examples

\n

Like other locale subtags, the collation type can be added to the Intl.Locale object via the locale string, or a configuration object argument to the constructor.

Adding a collation type via the locale string

\n
\n

In the Unicode locale string spec, collation types are locale key \"extension subtags\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension. Thus, the collation type can be added to the initial locale identifier string that is passed into the Intl.Locale() constructor. To add the collation type, first add the -u extension to the string. Next, add the -co extension to indicate that you are adding a collation type. Finally, add the collation type to the string.

\n

js

\n
const locale = new Intl.Locale(\"zh-Hant-u-co-zhuyin\");\nconsole.log(locale.collation); // \"zhuyin\"\n
\n
\n

Adding a collation type via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can contain any of several extension types, including collation types. Set the collation property of the configuration object to your desired collation type, and then pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"zh-Hant\", { collation: \"zhuyin\" });\nconsole.log(locale.collation); // \"zhuyin\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.collation
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
collation747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/collation\n

\n
\n", + "global_objects/intl/locale/hourcycle": "

Intl.Locale.prototype.hourCycle

The hourCycle accessor property of Intl.Locale instances returns the hour cycle type for this locale.

\n

Description

\n
\n

There are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. The hourCycle property's value is set at construction time, either through the hc key of the locale identifier or through the hourCycle option of the Intl.Locale() constructor. The latter takes priority if they are both present; and if neither is present, the property has value undefined.

For a list of supported hour cycle types, see Intl.Locale.prototype.getHourCycles().

The set accessor of hourCycle is undefined. You cannot change this property directly.

\n

Examples

\n

Like other locale subtags, the hour cycle type can be added to the Intl.Locale object via the locale string, or a configuration object argument to the constructor.

Adding an hour cycle via the locale string

\n
\n

In the Unicode locale string spec, hour cycle types are locale key \"extension subtags\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension. Thus, the hour cycle type can be added to the initial locale identifier string that is passed into the Intl.Locale() constructor. To add the hour cycle type, first add the -u extension key to the string. Next, add the -hc extension to indicate that you are adding an hour cycle. Finally, add the hour cycle type to the string.

\n

js

\n
const locale = new Intl.Locale(\"fr-FR-u-hc-h23\");\nconsole.log(locale.hourCycle); // \"h23\"\n
\n
\n

Adding an hour cycle via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types. Set the hourCycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"en-US\", { hourCycle: \"h12\" });\nconsole.log(locale.hourCycle); // \"h12\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.hourCycle
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
hourCycle747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle\n

\n
\n", + "global_objects/intl/locale/numberingsystem": "

Intl.Locale.prototype.numberingSystem

The numberingSystem accessor property of Intl.Locale instances returns the numeral system for this locale.

\n

Description

\n
\n

A numeral system is a system for expressing numbers. The numberingSystem property's value is set at construction time, either through the nu key of the locale identifier or through the numberingSystem option of the Intl.Locale() constructor. The latter takes priority if they are both present; and if neither is present, the property has value undefined.

For a list of supported numbering system types, see Intl.Locale.prototype.getNumberingSystems().

\n

Examples

\n

Like other locale subtags, the numbering system type can be added to the Intl.Locale object via the locale string, or a configuration object argument to the constructor.

Adding a numbering system via the locale string

\n
\n

In the Unicode locale string spec, numbering system types are locale key \"extension subtags\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension. Thus, the numbering system type can be added to the initial locale identifier string that is passed into the Intl.Locale() constructor. To add the numbering system type, first add the -u extension key to the string. Next, add the -nu extension to indicate that you are adding a numbering system. Finally, add the numbering system type to the string.

\n

js

\n
const locale = new Intl.Locale(\"fr-Latn-FR-u-nu-mong\");\nconsole.log(locale.numberingSystem); // \"mong\"\n
\n
\n

Adding a numbering system via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can contain any of several extension types, including numbering system types. Set the numberingSystem property of the configuration object to your desired numbering system type, and then pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\", { numberingSystem: \"latn\" });\nconsole.log(locale.numberingSystem); // \"latn\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.numberingSystem
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
numberingSystem747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem\n

\n
\n", + "global_objects/intl/locale/numeric": "

Intl.Locale.prototype.numeric

The numeric accessor property of Intl.Locale instances returns whether this locale has special collation handling for numeric characters.

\n

Description

\n

Like caseFirst, numeric represents a modification to the collation rules utilized by the locale. numeric is a boolean value, which means that it can be either true or false. If numeric is set to false, there will be no special handling of numeric values in strings. If numeric is set to true, then the locale will take numeric characters into account when collating strings. This special numeric handling means that sequences of decimal digits will be compared as numbers. For example, the string \"A-21\" will be considered less than \"A-123\".

Examples

\n

Setting the numeric value via the locale string

\n
\n

In the Unicode locale string spec, the values that numeric represents correspond to the key kn. kn is considered a locale string \"extension subtag\". These subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key. Thus, the numeric value can be added to the initial locale identifier string that is passed into the Intl.Locale() constructor. To set the numeric value, first add the -u extension key to the string. Next, add the -kn extension key to indicate that you are adding a value for numeric. Finally, add the numeric value to the string. If you want to set numeric to true, adding the kn key will suffice. To set the value to false, you must specify in by adding \"false\" after the kn key.

\n

js

\n
const locale = new Intl.Locale(\"fr-Latn-FR-u-kn-false\");\nconsole.log(locale.numeric); // Prints \"false\"\n
\n
\n

Setting the numeric value via the configuration object argument

\n
\n

The Intl.Locale() constructor has an optional configuration object argument, which can be used to pass extension types. Set the numeric property of the configuration object to your desired numeric value and pass it into the constructor.

\n

js

\n
const locale = new Intl.Locale(\"en-Latn-US\", { numeric: true });\nconsole.log(locale.numeric); // Prints \"true\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.numeric
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
numeric747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numeric\n

\n
\n", + "global_objects/intl/locale/locale": "

Intl.Locale() constructor

The Intl.Locale() constructor creates Intl.Locale objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.Locale(tag)\nnew Intl.Locale(tag, options)\n
\n

Note: Intl.Locale() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
tag

The Unicode locale identifier string. For the syntax of locale identifier strings, see the Intl main page. Note that the Intl.Locale constructor, unlike most other Intl constructors, does not accept an array of locales or undefined.

options

An object that contains configuration for the Locale. Option values here take priority over extension keys in the locale identifier. Possible properties are:

language

The language. Any syntactically valid string following the unicode_language_subtag grammar (2–3 or 5–8 letters) is accepted, but the implementation only recognizes certain kinds.

script

The script. Any syntactically valid string following the unicode_script_subtag grammar (4 letters) is accepted, but the implementation only recognizes certain kinds.

region

The region. Any syntactically valid string following the unicode_region_subtag grammar (either 2 letters or 3 digits) is accepted, but the implementation only recognizes certain kinds.

calendar

The calendar. Any syntactically valid string following the type grammar (one or more segments of 3–8 alphanumerals, joined by hyphens) is accepted, but the implementation only recognizes certain kinds, which are listed in Intl.Locale.prototype.getCalendars.

collation

The collation. Any syntactically valid string following the type grammar is accepted, but the implementation only recognizes certain kinds, which are listed in Intl.Locale.prototype.getCollations.

numberingSystem

The numbering system. Any syntactically valid string following the type grammar is accepted, but the implementation only recognizes certain kinds, which are listed in Intl.Locale.prototype.getNumberingSystems.

caseFirst

The case-first sort option. Possible values are \"upper\", \"lower\", or \"false\".

hourCycle

The hour cycle. Possible values are \"h23\", \"h12\", \"h11\", or the practically unused \"h24\", which are explained in Intl.Locale.prototype.getHourCycles

numeric

The numeric sort option. A boolean.

Examples

\n

Basic usage

\n
\n

At its very simplest, the Intl.Locale() constructor takes a locale identifier string as its argument:

\n

js

\n
const us = new Intl.Locale(\"en-US\");\n
\n
\n

Using the Locale constructor with an options object

\n
\n

The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the hourCycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor:

\n

js

\n
const locale = new Intl.Locale(\"en-US\", { hourCycle: \"h12\" });\nconsole.log(locale.hourCycle); // \"h12\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-locale-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Locale747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale\n

\n
\n", + "global_objects/intl/locale/basename": "

Intl.Locale.prototype.baseName

The baseName accessor property of Intl.Locale instances returns a substring of this locale's string representation, containing core information about this locale.

\n

Description

\n
\n

An Intl.Locale object represents a parsed local and options for that locale. The baseName property returns basic, core information about the Locale in the form of a substring of the complete data string. Specifically, the property returns the substring containing the language, and the script and region if available.

baseName returns the language [\"-\" script] [\"-\" region] *(\"-\" variant) subsequence of the unicode_language_id grammar.

\n

Examples

\n

Basic Example

\n
\n

js

\n
const myLoc = new Intl.Locale(\"fr-Latn-CA\"); // Sets locale to Canadian French\nconsole.log(myLoc.toString()); // Prints out \"fr-Latn-CA-u-ca-gregory\"\nconsole.log(myLoc.baseName); // Prints out \"fr-Latn-CA\"\n
\n

Example with options in the input string

\n
\n

js

\n
// Sets language to Japanese, region to Japan,\n\n// calendar to Gregorian, hour cycle to 24 hours\nconst japan = new Intl.Locale(\"ja-JP-u-ca-gregory-hc-24\");\nconsole.log(japan.toString()); // Prints out \"ja-JP-u-ca-gregory-hc-h24\"\nconsole.log(japan.baseName); // Prints out \"ja-JP\"\n
\n

Example with options that override input string

\n
\n

js

\n
// Input string indicates language as Dutch and region as Belgium,\n\n// but options object overrides the region and sets it to the Netherlands\nconst dutch = new Intl.Locale(\"nl-Latn-BE\", { region: \"NL\" });\n\nconsole.log(dutch.baseName); // Prints out \"nl-Latn-NL\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.baseName
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
baseName747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/baseName\n

\n
\n", + "global_objects/intl/locale/getcalendars": "

Intl.Locale.prototype.getCalendars()

\n

The getCalendars() method of Intl.Locale instances returns a list of one or more unique calendar identifiers for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called calendars. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of locale.calendars === locale.calendars returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getCalendars()\n
\n

Parameters

\n

None.

Return value

\n
\n

An array of strings representing all calendars commonly used for the Locale, sorted in descending preference. If the Locale already has a calendar, then the returned array contains that single value.

Below is a list of the supported calendar era types.

\n

Supported calendar types

\n
buddhist

Thai Buddhist calendar

chinese

Traditional Chinese calendar

coptic

Coptic calendar

dangi

Traditional Korean calendar

ethioaa

Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E)

ethiopic

Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.)

gregory

Gregorian calendar

hebrew

Traditional Hebrew calendar

indian

Indian calendar

islamic

Islamic calendar

islamic-umalqura

Islamic calendar, Umm al-Qura

islamic-tbla

Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch)

islamic-civil

Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch)

islamic-rgsa

Islamic calendar, Saudi Arabia sighting

iso8601

ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules)

japanese

Japanese Imperial calendar

persian

Persian calendar

roc

Civil (algorithmic) Arabic calendar

islamicc

Civil (algorithmic) Arabic calendar

Warning: The islamicc calendar key has been deprecated. Please use islamic-civil.

Examples

\n

Obtaining supported calendars

\n
\n

If the Locale object doesn't have a calendar already, getCalendars() lists all commonly-used calendars for the given Locale. For examples of explicitly setting a calendar, see calendar examples.

\n

js

\n
const arEG = new Intl.Locale(\"ar-EG\");\nconsole.log(arEG.getCalendars()); // [\"gregory\", \"coptic\", \"islamic\", \"islamic-civil\", \"islamic-tbla\"]\n
\n
\n

js

\n
const jaJP = new Intl.Locale(\"ja-JP\");\nconsole.log(jaJP.getCalendars()); // [\"gregory\", \"japanese\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getCalendars
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getCalendars
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars\n

\n
\n", + "global_objects/intl/locale/getcollations": "

Intl.Locale.prototype.getCollations()

\n

The getCollations() method of Intl.Locale instances returns a list of one or more collation types for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called collations. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of locale.collations === locale.collations returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getCollations()\n
\n

Parameters

\n

None.

Return value

\n
\n

An array of strings representing all collation types commonly used for the Locale, sorted in alphabetical order, with the standard and search values always excluded. If the Locale already has a collation, then the returned array contains that single value.

Below is a list of the supported collation types, adapted from the Unicode collation specification.

\n

Supported collation types

\n
big5han

Pinyin ordering for Latin, big5 charset ordering for CJK characters (for Chinese)

Warning: The big5han collation type is deprecated, not available in Firefox, Chrome or Edge.

compat

A previous version of the ordering, for compatibility (for Arabic)

dict

Dictionary style ordering (for Sinhala)

direct

Binary code point order

Warning: The direct collation type has been deprecated. Do not use.

ducet

The default Unicode collation element table order

Warning: The ducet collation type is not available to the Web. Use the und locale without a collation type specifier instead. und is the collation that is the closest to ducet.

emoji

Recommended ordering for emoji characters (for the und locale)

eor

European ordering rules (for the und locale)

gb2312

Pinyin ordering for Latin, gb2312han charset ordering for CJK characters (for Chinese)

Warning: The gb2312 collation type is deprecated, not available in Firefox, Chrome or Edge.

phonebk

Phonebook style ordering (for German)

phonetic

Phonetic ordering (sorting based on pronunciation; for Lingala)

pinyin

Pinyin ordering for Latin and for CJK characters (for Chinese)

reformed

Reformed ordering (formerly for Swedish)

Warning: Do not use explicitly. This is the old name for the default ordering for Swedish whose collation naming used to differ from other languages. Since this was the default, request sv instead of requesting sv-u-co-reformed.

search

Special collation type for string search

Warning: Do not use as a collation type, since in Intl.Collator, this collation is activated via the \"search\" value for the usage option. There is currently no API for substring search, so this is currently only good for filtering a list of strings by trying a full-string match of the key against each list item.

searchjl

Special collation type for Korean initial consonant search

Warning: This collation is not for sorting, even though it is made available through Intl.Collator instantiated with usage \"sort\" as opposed to usage \"search\".

standard

Default ordering for each language, except Chinese (and, previously, Swedish)

Warning: Do not use explicitly. In general, it's unnecessary to specify this explicitly and specifying this for Swedish is problematic due to the different meaning for Swedish in the past.

stroke

Pinyin ordering for Latin, stroke order for CJK characters (for Chinese)

trad

Traditional style ordering (such as in Spanish)

unihan

Radical-stroke ordering for Han characters (for Chinese, Japanese, and Korean). Pinyin ordering for Latin in the case of Chinese.

Note: The unihan collation type is not available in Chrome or Edge.

zhuyin

Pinyin ordering for Latin, zhuyin order for Bopomofo and CJK characters (for Chinese)

Examples

\n

Obtaining supported collation types

\n
\n

If the Locale object doesn't have a collation already, getCollations() lists all commonly-used collation types for the given Locale. For examples of explicitly setting a collation, see collation examples.

\n

js

\n
const locale = new Intl.Locale(\"zh\");\nconsole.log(locale.getCollations()); // [\"pinyin\", \"stroke\", \"zhuyin\", \"emoji\", \"eor\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getCollations
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getCollations
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations\n

\n
\n", + "global_objects/intl/locale/gethourcycles": "

Intl.Locale.prototype.getHourCycles()

\n

The getHourCycles() method of Intl.Locale instances returns a list of one or more unique hour cycle identifiers for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called hourCycles. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of locale.hourCycles === locale.hourCycles returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getHourCycles()\n
\n

Parameters

\n

None.

Return value

\n
\n

An array of strings representing all hour cycle types commonly used for the Locale, sorted in descending preference. If the Locale already has an hourCycle, then the returned array contains that single value.

Below is a list of supported hour cycle types.

\n

Supported hour cycle types

\n
h12

Hour system using 1–12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am. As used, for example, in the United States.

h23

Hour system using 0–23; corresponds to 'H' in patterns. The 24 hour clock, with midnight starting at 0:00.

h11

Hour system using 0–11; corresponds to 'K' in patterns. The 12 hour clock, with midnight starting at 0:00 am. Mostly used in Japan.

h24

Hour system using 1–24; corresponds to 'k' in pattern. The 24 hour clock, with midnight starting at 24:00. Not used anywhere.

Examples

\n

Obtaining supported hour cycles

\n
\n

If the Locale object doesn't have a hourCycle already, getHourCycles() lists all commonly-used collation types for the given Locale. For examples of explicitly setting a hourCycle, see hourCycle examples.

\n

js

\n
const arEG = new Intl.Locale(\"ar-EG\");\nconsole.log(arEG.getHourCycles()); // [\"h12\"]\n
\n
\n

js

\n
const jaJP = new Intl.Locale(\"ja-JP\");\nconsole.log(jaJP.getHourCycles()); // [\"h23\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getHourCycles
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getHourCycles
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getHourCycles\n

\n
\n", + "global_objects/intl/locale/getnumberingsystems": "

Intl.Locale.prototype.getNumberingSystems()

\n

The getNumberingSystems() method of Intl.Locale instances returns a list of one or more unique numbering system identifiers for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called numberingSystems. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of locale.numberingSystems === locale.numberingSystems returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getNumberingSystems()\n
\n

Parameters

\n

None.

Return value

\n
\n

An array of strings representing all numbering systems commonly used for the Locale, sorted in descending preference. If the Locale already has a numberingSystem, then the returned array contains that single value.

A table of the standard Unicode numeral systems can be seen below.

\n

Supported numbering system types

\n
Value Description
adlm Adlam digits
ahom Ahom digits
arab Arabic-Indic digits
arabext Extended Arabic-Indic digits
armn Armenian upper case numerals — algorithmic
armnlow Armenian lower case numerals — algorithmic
bali Balinese digits
beng Bengali digits
bhks Bhaiksuki digits
brah Brahmi digits
cakm Chakma digits
cham Cham digits
cyrl Cyrillic numerals — algorithmic
deva Devanagari digits
ethi Ethiopic numerals — algorithmic
finance Financial numerals — may be algorithmic
fullwide Full width digits
geor Georgian numerals — algorithmic
gong Gunjala Gondi digits
gonm Masaram Gondi digits
grek Greek upper case numerals — algorithmic
greklow Greek lower case numerals — algorithmic
gujr Gujarati digits
guru Gurmukhi digits
hanidays Han-character day-of-month numbering for lunar/other traditional calendars
hanidec Positional decimal system using Chinese number ideographs as digits
hans Simplified Chinese numerals — algorithmic
hansfin Simplified Chinese financial numerals — algorithmic
hant Traditional Chinese numerals — algorithmic
hantfin Traditional Chinese financial numerals — algorithmic
hebr Hebrew numerals — algorithmic
hmng Pahawh Hmong digits
hmnp Nyiakeng Puachue Hmong digits
java Javanese digits
jpan Japanese numerals — algorithmic
jpanfin Japanese financial numerals — algorithmic
jpanyear Japanese first-year Gannen numbering for Japanese calendar
kali Kayah Li digits
khmr Khmer digits
knda Kannada digits
lana Tai Tham Hora (secular) digits
lanatham Tai Tham (ecclesiastical) digits
laoo Lao digits
latn Latin digits
lepc Lepcha digits
limb Limbu digits
mathbold Mathematical bold digits
mathdbl Mathematical double-struck digits
mathmono Mathematical monospace digits
mathsanb Mathematical sans-serif bold digits
mathsans Mathematical sans-serif digits
mlym Malayalam digits
modi Modi digits
mong Mongolian digits
mroo Mro digits
mtei Meetei Mayek digits
mymr Myanmar digits
mymrshan Myanmar Shan digits
mymrtlng Myanmar Tai Laing digits
native Native digits
newa Newa digits
nkoo N'Ko digits
olck Ol Chiki digits
orya Oriya digits
osma Osmanya digits
rohg Hanifi Rohingya digits
roman Roman upper case numerals — algorithmic
romanlow Roman lowercase numerals — algorithmic
saur Saurashtra digits
shrd Sharada digits
sind Khudawadi digits
sinh Sinhala Lith digits
sora Sora_Sompeng digits
sund Sundanese digits
takr Takri digits
talu New Tai Lue digits
taml Tamil numerals — algorithmic
tamldec Modern Tamil decimal digits
telu Telugu digits
thai Thai digits
tirh Tirhuta digits
tibt Tibetan digits
traditio Traditional numerals — may be algorithmic
vaii Vai digits
wara Warang Citi digits
wcho Wancho digits

Examples

\n

Obtaining supported numbering systems

\n
\n

If the Locale object doesn't have a numberingSystem already, getNumberingSystems() lists all commonly-used numbering systems for the given Locale. For examples of explicitly setting a numberingSystem, see numberingSystem examples.

\n

js

\n
const arEG = new Intl.Locale(\"ar-EG\");\nconsole.log(arEG.getNumberingSystems()); // [\"arab\"]\n
\n
\n

js

\n
const ja = new Intl.Locale(\"ja\");\nconsole.log(ja.getNumberingSystems()); // [\"latn\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getNumberingSystems
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getNumberingSystems
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems\n

\n
\n", + "global_objects/intl/locale/gettextinfo": "

Intl.Locale.prototype.getTextInfo()

\n

The getTextInfo() method of Intl.Locale instances returns the ordering of characters indicated by either ltr (left-to-right) or by rtl (right-to-left) for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called textInfo. However, because it returns a new object on each access, it is now implemented as a method to prevent the situation of locale.textInfo === locale.textInfo returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getTextInfo()\n
\n

Parameters

\n

None.

Return value

\n
\n

An object representing text typesetting information associated with the Locale data specified in UTS 35's Layouts Elements. It has the following properties:

direction

A string indicating the direction of text for the locale. Can be either \"ltr\" (left-to-right) or \"rtl\" (right-to-left).

\n

Examples

\n

Obtaining text info

\n
\n

Return the supported text directions for a given Locale.

\n

js

\n
const ar = new Intl.Locale(\"ar\");\nconsole.log(ar.getTextInfo()); // { direction: \"rtl\" }\nconsole.log(ar.getTextInfo().direction); // \"rtl\"\n
\n
\n

js

\n
const es = new Intl.Locale(\"es\");\nconsole.log(es.getTextInfo()); // { direction: \"ltr\" }\nconsole.log(es.getTextInfo().direction); // \"ltr\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getTextInfo
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getTextInfo
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo\n

\n
\n", + "global_objects/intl/locale/gettimezones": "

Intl.Locale.prototype.getTimeZones()

\n

The getTimeZones() method of Intl.Locale instances returns a list of supported time zones for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called timeZones. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of locale.timeZones === locale.timeZones returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getTimeZones()\n
\n

Parameters

\n

None.

Return value

\n

An array of strings representing supported time zones for the associated Locale, where each value is an IANA time zone canonical name, sorted in alphabetical order. If the locale identifier does not contain a region subtag, the returned value is undefined.

Examples

\n

Obtaining supported time zones

\n
\n

List supported time zones for a given Locale.

\n

js

\n
const arEG = new Intl.Locale(\"ar-EG\");\nconsole.log(arEG.getTimeZones()); // [\"Africa/Cairo\"]\n
\n
\n

js

\n
const jaJP = new Intl.Locale(\"ja-JP\");\nconsole.log(jaJP.getTimeZones()); // [\"Asia/Tokyo\"]\n
\n
\n

js

\n
const ar = new Intl.Locale(\"ar\");\nconsole.log(ar.getTimeZones()); // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getTimeZones
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getTimeZones
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTimeZones\n

\n
\n", + "global_objects/intl/locale/getweekinfo": "

Intl.Locale.prototype.getWeekInfo()

\n

The getWeekInfo() method of Intl.Locale instances returns a weekInfo object with the properties firstDay, weekend and minimalDays for this locale.

Note: In some versions of some browsers, this method was implemented as an accessor property called weekInfo. However, because it returns a new object on each access, it is now implemented as a method to prevent the situation of locale.weekInfo === locale.weekInfo returning false. Check the browser compatibility table for details.

\n
\n

Syntax

\n
\n

js

\n
getWeekInfo()\n
\n

Parameters

\n

None.

Return value

\n
\n

An object representing week information associated with the Locale data specified in UTS 35's Week Elements. It has the following properties:

firstDay

An integer indicating the first day of the week for the locale. Can be either 1 (Monday) or 7 (Sunday).

weekend

An array of integers indicating the weekend days for the locale, where 1 is Monday and 7 is Sunday.

minimalDays

An integer between 1 and 7 indicating the minimal days required in the first week of a month or year, for calendar purposes.

\n

Examples

\n

Obtaining the Week Information

\n
\n

Return the week information for a given Locale.

\n

js

\n
const he = new Intl.Locale(\"he\");\nconsole.log(he.getWeekInfo()); // { firstDay: 7, weekend: [5, 6], minimalDays: 1 }\n\nconst af = new Intl.Locale(\"af\");\nconsole.log(af.getWeekInfo()); // { firstDay: 7, weekend: [6, 7], minimalDays: 1 }\n\nconst enGB = new Intl.Locale(\"en-GB\");\nconsole.log(enGB.getWeekInfo()); // { firstDay: 1, weekend: [6, 7], minimalDays: 4 }\n\nconst msBN = new Intl.Locale(\"ms-BN\");\nconsole.log(msBN.getWeekInfo()); // { firstDay: 7, weekend: [5, 7], minimalDays: 1 }\n// Brunei weekend is Friday and Sunday but not Saturday\n
\n
\n

Specifications

\n
\n\n\n
Specification
Intl Locale Info Proposal
# sec-Intl.Locale.prototype.getWeekInfo
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
getWeekInfo
99Implemented as an accessor property.
99Implemented as an accessor property.
NoNo
85Implemented as an accessor property.
17
15.4–previewImplemented as an accessor property.
\n
99Implemented as an accessor property.
99Implemented as an accessor property.
No
68Implemented as an accessor property.
17
15.4Implemented as an accessor property.
\n
18.0Implemented as an accessor property.
1.19
18.0.0Implemented as an accessor property.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo\n

\n
\n", + "global_objects/intl/locale/maximize": "

Intl.Locale.prototype.maximize()

The maximize() method of Intl.Locale instances gets the most likely values for the language, script, and region of this locale based on existing values.

\n

Try it

\n

Syntax

\n
\n

js

\n
maximize()\n
\n

Parameters

\n

None.

Return value

\n

A Intl.Locale instance whose baseName property returns the result of the Add Likely Subtags algorithm executed against locale.baseName.

Description

\n

Sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete language ID. The Add Likely Subtags algorithm gives us this functionality. For instance, given the language ID \"en\", the algorithm would return \"en-Latn-US\", since English can only be written in the Latin script, and is most likely to be used in the United States, as it is the largest English-speaking country in the world. This functionality is provided to JavaScript programmers via the maximize() method. maximize() only affects the main subtags that comprise the language identifier: language, script, and region subtags. Other subtags after the \"-u\" in the locale identifier are called extension subtags and are not affected by the maximize() method. Examples of these subtags include hourCycle, calendar, and numeric.

Examples

\n

Using maximize

\n
\n

js

\n
const myLocale = new Intl.Locale(\"fr\", {\n  hourCycle: \"h12\",\n  calendar: \"gregory\",\n});\nconsole.log(myLocale.baseName); // Prints \"fr\"\nconsole.log(myLocale.toString()); // Prints \"fr-u-ca-gregory-hc-h12\"\nconst myLocMaximized = myLocale.maximize();\n\n// Prints \"fr-Latn-FR\". The \"Latn\" and \"FR\" tags are added,\n// since French is only written in the Latin script and is most likely to be spoken in France.\nconsole.log(myLocMaximized.baseName);\n\n// Prints \"fr-Latn-FR-u-ca-gregory-hc-h12\".\n// Note that the extension tags (after \"-u\") remain unchanged.\nconsole.log(myLocMaximized.toString());\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.maximize
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
maximize747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/maximize\n

\n
\n", + "global_objects/intl/locale/minimize": "

Intl.Locale.prototype.minimize()

The minimize() method of Intl.Locale instances attempts to remove information about this locale that would be added by calling maximize().

\n

Try it

\n

Syntax

\n
\n

js

\n
minimize()\n
\n

Parameters

\n

None.

Return value

\n

A Intl.Locale instance whose baseName property returns the result of the Remove Likely Subtags algorithm executed against locale.baseName.

Description

\n

This method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of baseName). This is useful when there are superfluous subtags in the language identifier; for instance, \"en-Latn\" can be simplified to \"en\", since \"Latn\" is the only script used to write English. minimize() only affects the main subtags that comprise the language identifier: language, script, and region subtags. Other subtags after the \"-u\" in the locale identifier are called extension subtags and are not affected by the minimize() method. Examples of these subtags include hourCycle, calendar, and numeric.

Examples

\n

Using minimize

\n
\n

js

\n
const myLocale = new Intl.Locale(\"fr-Latn-FR\", {\n  hourCycle: \"h12\",\n  calendar: \"gregory\",\n});\nconsole.log(myLocale.baseName); // Prints \"fr-Latn-FR\"\nconsole.log(myLocale.toString()); // Prints \"fr-Latn-FR-u-ca-gregory-hc-h12\"\n\nconst myLocMinimized = myLocale.minimize();\n\n// Prints \"fr\", since French is only written in the Latin script\n// and is most likely to be spoken in France.\nconsole.log(myLocMinimized.baseName);\n\n// Prints \"fr-u-ca-gregory-hc-h12\".\n// Note that the extension tags (after \"-u\") remain unchanged.\nconsole.log(myLocMinimized.toString());\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.minimize
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
minimize747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/minimize\n

\n
\n", + "global_objects/intl/locale/tostring": "

Intl.Locale.prototype.toString()

The toString() method of Intl.Locale instances returns this Locale's full locale identifier string.

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

The locale's Unicode locale identifier string.

Description

\n

The Locale object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. Calling the toString method on a Locale object will return the identifier string for that particular Locale. The toString method allows Locale instances to be provided as an argument to existing Intl constructors, serialized in JSON, or any other context where an exact string representation is useful.

Examples

\n

Using toString

\n
\n

js

\n
const myLocale = new Intl.Locale(\"fr-Latn-FR\", {\n  hourCycle: \"h12\",\n  calendar: \"gregory\",\n});\nconsole.log(myLocale.baseName); // Prints \"fr-Latn-FR\"\nconsole.log(myLocale.toString()); // Prints \"fr-Latn-FR-u-ca-gregory-hc-h12\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.Locale.prototype.toString
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString747975No6214747479531411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/toString\n

\n
\n", + "global_objects/intl/numberformat/supportedlocalesof": "

Intl.NumberFormat.supportedLocalesOf()

The Intl.NumberFormat.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.NumberFormat.supportedLocalesOf(locales)\nIntl.NumberFormat.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.NumberFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.supportedlocalesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/supportedLocalesOf\n

\n
\n", + "global_objects/intl/numberformat/format": "

Intl.NumberFormat.prototype.format()

The format() method of Intl.NumberFormat instances formats a number according to the locale and formatting options of this Intl.NumberFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
format(number)\n
\n

Parameters

\n
\n
number

A Number, BigInt, or string, to format. Strings are parsed in the same way as in number conversion, except that format() will use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number.

Note: Older versions of the specification parsed strings as a Number. Check the compatibility table for your browser.

\n

Return value

\n

A string representing the given number formatted according to the locale and formatting options of this Intl.NumberFormat object.

Description

\n
\n

Number values in JavaScript suffer from loss of precision if they are too big or too small, making the text representation inaccurate. If you are performing calculations with integers larger than Number.MAX_SAFE_INTEGER you should use a BigInt instead, which will format correctly:

\n

js

\n
new Intl.NumberFormat(\"en-US\").format(1234567891234567891); // 1,234,567,891,234,568,000\nnew Intl.NumberFormat(\"en-US\").format(1234567891234567891n); // 1,234,567,891,234,567,891\n
\n

You can also pass through very large strings to be formatted as an arbitrary-precision decimal string (if you're performing calculations on the data you will still need to work with BigInt):

\n

js

\n
new Intl.NumberFormat(\"en-US\").format(\"1234567891234567891\"); // 1,234,567,891,234,567,891\n
\n
\n

Examples

\n

Using format

\n
\n

Use the format getter function for formatting a single currency value. The code below shows how to format the roubles currency for a Russian locale:

\n

js

\n
const options = { style: \"currency\", currency: \"RUB\" };\nconst numberFormat = new Intl.NumberFormat(\"ru-RU\", options);\nconsole.log(numberFormat.format(654321.987));\n// \"654 321,99 ₽\"\n
\n
\n

Using format with map

\n
\n

Use the format getter function for formatting all numbers in an array. Note that the function is bound to the Intl.NumberFormat from which it was obtained, so it can be passed directly to Array.prototype.map. This is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs.

\n

js

\n
const a = [123456.789, 987654.321, 456789.123];\nconst numberFormat = new Intl.NumberFormat(\"es-ES\");\nconst formatted = a.map((n) => numberFormat.format(n));\nconsole.log(formatted.join(\"; \"));\n// \"123.456,789; 987.654,321; 456.789,123\"\n
\n
\n

Using format with a string

\n
\n

Using a string we can specify very numbers that are larger than Number.MAX_SAFE_INTEGER without losing precision.

\n

js

\n
const numberFormat = new Intl.NumberFormat(\"en-US\");\n\n// Here the value is converted to a Number\nconsole.log(numberFormat.format(987654321987654321));\n// 987,654,321,987,654,300\n\n// Here we use a string and don't lose precision\nconsole.log(numberFormat.format(\"987654321987654321\"));\n// 987,654,321,987,654,321\n
\n

We can also use the general \"E\" exponent syntax for decimal strings: #.#E#. The code below creates a BigInt, coerces it to a string with the suffix E-6, and then formats it.

\n

js

\n
const numberFormat = new Intl.NumberFormat(\"en-US\");\nconst bigNum = 1000000000000000110000n;\nconsole.log(numberFormat.format(bigNum));\n// \"1,000,000,000,000,000,110,000\"\n\n// Format as a string using the `E` syntax:\nconsole.log(numberFormat.format(`${bigNum}E-6`));\n// \"1,000,000,000,000,000.11\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.prototype.format
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
format24
12Before Edge 18, numbers are rounded to 15 decimal digits. For example, new Intl.NumberFormat('en-US').format(1000000000000005) returns \"1,000,000,000,000,010\".
29
11In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, new Intl.NumberFormat('en-US').format(1000000000000005) returns \"1,000,000,000,000,010\".
15104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
number_parameter-string_decimal106106116No9215.41061061167215.420.0No19.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format\n

\n
\n", + "global_objects/intl/numberformat/formatrange": "

Intl.NumberFormat.prototype.formatRange()

The formatRange() method of Intl.NumberFormat instances formats a range of numbers according to the locale and formatting options of this Intl.NumberFormat object.

\n

Syntax

\n
\n

js

\n
formatRange(startRange, endRange)\n
\n

Parameters

\n
startRange

A Number or BigInt.

endRange

A Number or BigInt.

Return value

\n

A string representing the given range of numbers formatted according to the locale and formatting options of this Intl.NumberFormat object.

Exceptions

\n
RangeError

Thrown if startRange is less than endRange, or either value is NaN.

TypeError

Thrown if either startRange or endRange is undefined.

Description

\n

The formatRange getter function formats a range of numbers into a string according to the locale and formatting options of this Intl.NumberFormat object from which it is called.

Examples

\n

Using formatRange

\n
\n

Use the formatRange getter function for formatting a range of currency values:

\n

js

\n
const nf = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 0,\n});\n\nconsole.log(nf.formatRange(3, 5)); // \"$3 – $5\"\n\n// Note: the \"approximately equals\" symbol is added if\n// startRange and endRange round to the same values.\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~$3\"\n
\n
\n

js

\n
const nf = new Intl.NumberFormat(\"es-ES\", {\n  style: \"currency\",\n  currency: \"EUR\",\n  maximumFractionDigits: 0,\n});\n\nconsole.log(nf.formatRange(3, 5)); // \"3-5 €\"\nconsole.log(nf.formatRange(2.9, 3.1)); // \"~3 €\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.prototype.formatrange
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatRange106106116No9215.41061061167215.420.0No19.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange\n

\n
\n", + "global_objects/intl/numberformat/formatrangetoparts": "

Intl.NumberFormat.prototype.formatRangeToParts()

The formatRangeToParts() method of Intl.NumberFormat instances returns an Array of objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.

\n

Syntax

\n
\n

js

\n
formatRangeToParts(startRange, endRange)\n
\n

Parameters

\n
startRange

A Number or BigInt.

endRange

A Number or BigInt.

Return value

\n
\n

An Array of objects containing the formatted range of numbers in parts.

The structure of the returned looks like this:

\n

js

\n
[\n  { type: \"integer\", value: \"3\", source: \"startRange\" },\n  { type: \"literal\", value: \"-\", source: \"shared\" },\n  { type: \"integer\", value: \"5\", source: \"endRange\" },\n  { type: \"literal\", value: \" \", source: \"shared\" },\n  { type: \"currency\", value: \"€\", source: \"shared\" },\n];\n
\n

Possible values for the type property include:

currency

The currency string, such as the symbols \"$\" and \"€\" or the name \"Dollar\", \"Euro\", depending on how currencyDisplay is specified.

decimal

The decimal separator string (\".\").

fraction

The fraction number.

group

The group separator string (\",\").

infinity

The Infinity string (\"∞\").

integer

The integer number.

literal

Any literal strings or whitespace in the formatted number.

minusSign

The minus sign string (\"-\").

nan

The NaN string (\"NaN\").

plusSign

The plus sign string (\"+\").

percentSign

The percent sign string (\"%\").

unit

The unit string, such as the \"l\" or \"litres\", depending on how unitDisplay is specified.

Possible values for the source property include:

startRange

The object is the start part of the range.

endRange

The object is the end part of the range.

shared

The object is a \"shared\" part of the range, such as a separator or currency.

\n

Exceptions

\n
RangeError

Thrown if startRange is less than endRange, or either value is NaN.

TypeError

Thrown if either startRange or endRange is undefined.

Examples

\n

Comparing formatRange and formatRangeToParts

\n
\n

NumberFormat outputs localized, opaque strings that cannot be manipulated directly:

\n

js

\n
const startRange = 3500;\nconst endRange = 9500;\n\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\n  style: \"currency\",\n  currency: \"EUR\",\n});\n\nconsole.log(formatter.formatRange(startRange, endRange));\n// \"3.500,00–9.500,00 €\"\n
\n

However, for many user interfaces there is a need to customize the formatting of this string. The formatRangeToParts method enables locale-aware formatting of strings produced by NumberFormat formatters by providing you the string in parts:

\n

js

\n
console.log(formatter.formatRangeToParts(startRange, endRange));\n\n// return value:\n[\n  { type: \"integer\", value: \"3\", source: \"startRange\" },\n  { type: \"group\", value: \".\", source: \"startRange\" },\n  { type: \"integer\", value: \"500\", source: \"startRange\" },\n  { type: \"decimal\", value: \",\", source: \"startRange\" },\n  { type: \"fraction\", value: \"00\", source: \"startRange\" },\n  { type: \"literal\", value: \"–\", source: \"shared\" },\n  { type: \"integer\", value: \"9\", source: \"endRange\" },\n  { type: \"group\", value: \".\", source: \"endRange\" },\n  { type: \"integer\", value: \"500\", source: \"endRange\" },\n  { type: \"decimal\", value: \",\", source: \"endRange\" },\n  { type: \"fraction\", value: \"00\", source: \"endRange\" },\n  { type: \"literal\", value: \" \", source: \"shared\" },\n  { type: \"currency\", value: \"€\", source: \"shared\" },\n];\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.prototype.formatrangetoparts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatRangeToParts106106116No9215.41061061167215.420.0No19.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRangeToParts\n

\n
\n", + "global_objects/intl/numberformat/numberformat": "

Intl.NumberFormat() constructor

The Intl.NumberFormat() constructor creates Intl.NumberFormat objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.NumberFormat()\nnew Intl.NumberFormat(locales)\nnew Intl.NumberFormat(locales, options)\n\nIntl.NumberFormat()\nIntl.NumberFormat(locales)\nIntl.NumberFormat(locales, options)\n
\n

Note: Intl.NumberFormat() can be called with or without new. Both create a new Intl.NumberFormat instance. However, there's a special behavior when it's called without new and the this value is another Intl.NumberFormat instance; see Return value.

\n

Parameters

\n
\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

The following Unicode extension key is allowed:

nu

See numberingSystem.

This key can also be set with options (as listed below). When both are set, the options property takes precedence.

\noptions Optional\n

An object. For ease of reading, the property list is broken into sections based on their purposes, including locale options, style options, digit options, and other options.

Locale options

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

numberingSystem

The numbering system to use for number formatting, such as \"arab\", \"hans\", \"mathsans\", and so on. For a list of supported numbering system types, see Intl.Locale.prototype.getNumberingSystems(). This option can also be set through the nu Unicode extension key; if both are provided, this options property takes precedence.

Style options

Depending on the style used, some of them may be ignored, and others may be required:

style

The formatting style to use.

\n\"decimal\" (default)

For plain number formatting.

\"currency\"

For currency formatting.

\"percent\"

For percent formatting.

\"unit\"

For unit formatting.

currency

The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as \"USD\" for the US dollar, \"EUR\" for the euro, or \"CNY\" for the Chinese RMB — see the Current currency & funds code list. There is no default value; if the style is \"currency\", the currency property must be provided.

currencyDisplay

How to display the currency in currency formatting.

\"code\"

Use the ISO currency code.

\n\"symbol\" (default)

Use a localized currency symbol such as €.

\"narrowSymbol\"

Use a narrow format symbol (\"$100\" rather than \"US$100\").

\"name\"

Use a localized currency name such as \"dollar\".

currencySign

In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. Possible values are \"standard\" and \"accounting\"; the default is \"standard\".

unit

The unit to use in unit formatting, Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset of units from the full list was selected for use in ECMAScript. Pairs of simple units can be concatenated with \"-per-\" to make a compound unit. There is no default value; if the style is \"unit\", the unit property must be provided.

unitDisplay

The unit formatting style to use in unit formatting. Possible values are:

\n\"short\" (default)

E.g., 16 l.

\"narrow\"

E.g., 16l.

\"long\"

E.g., 16 litres.

Digit options

The following properties are also supported by Intl.PluralRules.

minimumIntegerDigits

The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from 1 to 21; the default is 1.

minimumFractionDigits

The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).

maximumFractionDigits

The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3; the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.

minimumSignificantDigits

The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.

maximumSignificantDigits

The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.

The above properties fall into two groups: minimumIntegerDigits, minimumFractionDigits, and maximumFractionDigits in one group, minimumSignificantDigits and maximumSignificantDigits in the other. If properties from both groups are specified, conflicts in the resulting display format are resolved based on th value of the roundingPriority property.

roundingPriority

Specify how rounding conflicts will be resolved if both \"FractionDigits\" (minimumFractionDigits/maximumFractionDigits) and \"SignificantDigits\" (minimumSignificantDigits/maximumSignificantDigits) are specified. Possible values are:

\n\"auto\" (default)

The result from the significant digits property is used.

\"morePrecision\"

The result from the property that results in more precision is used.

\"lessPrecision\"

The result from the property that results in less precision is used.

Note that for values other than auto the result with more precision is calculated from the maximumSignificantDigits and maximumFractionDigits (minimum fractional and significant digit settings are ignored).

roundingIncrement

Indicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, and 5000. It cannot be mixed with significant-digits rounding or any setting of roundingPriority other than auto.

roundingMode

How decimals should be rounded. Possible values are:

\"ceil\"

Round toward +∞. Positive values round up. Negative values round \"more positive\".

\"floor\"

Round toward -∞. Positive values round down. Negative values round \"more negative\".

\"expand\"

round away from 0. The magnitude of the value is always increased by rounding. Positive values round up. Negative values round \"more negative\".

\"trunc\"

Round toward 0. This magnitude of the value is always reduced by rounding. Positive values round down. Negative values round \"less negative\".

\"halfCeil\"

ties toward +∞. Values above the half-increment round like \"ceil\" (towards +∞), and below like \"floor\" (towards -∞). On the half-increment, values round like \"ceil\".

\"halfFloor\"

Ties toward -∞. Values above the half-increment round like \"ceil\" (towards +∞), and below like \"floor\" (towards -∞). On the half-increment, values round like \"floor\".

\n\"halfExpand\" (default)

Ties away from 0. Values above the half-increment round like \"expand\" (away from zero), and below like \"trunc\" (towards 0). On the half-increment, values round like \"expand\".

\"halfTrunc\"

Ties toward 0. Values above the half-increment round like \"expand\" (away from zero), and below like \"trunc\" (towards 0). On the half-increment, values round like \"trunc\".

\"halfEven\"

Ties towards the nearest even integer. Values above the half-increment round like \"expand\" (away from zero), and below like \"trunc\" (towards 0). On the half-increment values round towards the nearest even digit.

These options reflect the ICU user guide, where \"expand\" and \"trunc\" map to ICU \"UP\" and \"DOWN\", respectively. The rounding modes example below demonstrates how each mode works.

trailingZeroDisplay

The strategy for displaying trailing zeros on whole numbers. Possible values are:

\n\"auto\" (default)

Keep trailing zeros according to minimumFractionDigits and minimumSignificantDigits.

\"stripIfInteger\"

Remove the fraction digits if they are all zero. This is the same as \"auto\" if any of the fraction digits is non-zero.

Other options

notation

The formatting that should be displayed for the number. Possible values are:

\n\"standard\" (default)

Plain number formatting.

\"scientific\"

Return the order-of-magnitude for formatted number.

\"engineering\"

Return the exponent of ten when divisible by three.

\"compact\"

String representing exponent; defaults to using the \"short\" form.

compactDisplay

Only used when notation is \"compact\". Possible values are \"short\" and \"long\"; the default is \"short\".

useGrouping

Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.

\"always\"

Display grouping separators even if the locale prefers otherwise.

\"auto\"

Display grouping separators based on the locale preference, which may also be dependent on the currency.

\"min2\"

Display grouping separators when there are at least 2 digits in a group.

The default is \"min2\" if notation is \"compact\", and \"auto\" otherwise. The boolean values true and false are accepted, but are always converted to the default value.

signDisplay

When to display the sign for the number. Possible values are:

\n\"auto\" (default)

Sign display for negative numbers only, including negative zero.

\"always\"

Always display sign.

\"exceptZero\"

Sign display for positive and negative numbers, but not zero.

\"negative\"

Sign display for negative numbers only, excluding negative zero.

\"never\"

Never display sign.

\n

Return value

\n
\n

A new Intl.NumberFormat object.

Note: The text below describes behavior that is marked by the specification as \"optional\". It may not work in all environments. Check the browser compatibility table.

Normally, Intl.NumberFormat() can be called with or without new, and a new Intl.NumberFormat instance is returned in both cases. However, if the this value is an object that is instanceof Intl.NumberFormat (doesn't necessarily mean it's created via new Intl.NumberFormat; just that it has Intl.NumberFormat.prototype in its prototype chain), then the value of this is returned instead, with the newly created Intl.NumberFormat object hidden in a [Symbol(IntlLegacyConstructedSymbol)] property (a unique symbol that's reused between instances).

\n

js

\n
const formatter = Intl.NumberFormat.call(\n  { __proto__: Intl.NumberFormat.prototype },\n  \"en-US\",\n  { notation: \"scientific\" },\n);\nconsole.log(Object.getOwnPropertyDescriptors(formatter));\n// {\n//   [Symbol(IntlLegacyConstructedSymbol)]: {\n//     value: NumberFormat [Intl.NumberFormat] {},\n//     writable: false,\n//     enumerable: false,\n//     configurable: false\n//   }\n// }\n
\n

Note that there's only one actual Intl.NumberFormat instance here: the one hidden in [Symbol(IntlLegacyConstructedSymbol)]. Calling the format() and resolvedOptions() methods on formatter would correctly use the options stored in that instance, but calling all other methods (e.g. formatRange()) would fail with \"TypeError: formatRange method called on incompatible Object\", because those methods don't consult the hidden instance's options.

This behavior, called ChainNumberFormat, does not happen when Intl.NumberFormat() is called without new but with this set to anything else that's not an instanceof Intl.NumberFormat. If you call it directly as Intl.NumberFormat(), the this value is Intl, and a new Intl.NumberFormat instance is created normally.

\n

Exceptions

\n
RangeError

Thrown in one of the following cases:

  • A property that takes enumerated values (such as style, units, currency, and so on) is set to an invalid value.
  • Both maximumFractionDigits and minimumFractionDigits are set, and they are set to different values. Note that depending on various formatting options, these properties can have default values. It is therefore possible to get this error even if you only set one of the properties.
TypeError

Thrown if the options.style property is set to \"unit\" or \"currency\", and no value has been set for the corresponding property options.unit or options.currency.

Examples

\n

Basic usage

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

\n

js

\n
const amount = 3500;\n\nconsole.log(new Intl.NumberFormat().format(amount));\n// '3,500' if in US English locale\n
\n
\n

Decimal and percent formatting

\n
\n

js

\n
const amount = 3500;\n\nnew Intl.NumberFormat(\"en-US\", {\n  style: \"decimal\",\n}).format(amount); // '3,500'\nnew Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n}).format(amount); // '350,000%'\n
\n

Unit formatting

\n
\n

If the style is 'unit', a unit property must be provided. Optionally, unitDisplay controls the unit formatting.

\n

js

\n
const amount = 3500;\n\nnew Intl.NumberFormat(\"en-US\", {\n  style: \"unit\",\n  unit: \"liter\",\n}).format(amount); // '3,500 L'\n\nnew Intl.NumberFormat(\"en-US\", {\n  style: \"unit\",\n  unit: \"liter\",\n  unitDisplay: \"long\",\n}).format(amount); // '3,500 liters'\n
\n
\n

Currency formatting

\n
\n

If the style is 'currency', a currency property must be provided. Optionally, currencyDisplay and currencySign control the unit formatting.

\n

js

\n
const amount = -3500;\nnew Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n}).format(amount); // '-$3,500.00'\n\nnew Intl.NumberFormat(\"bn\", {\n  style: \"currency\",\n  currency: \"USD\",\n  currencyDisplay: \"name\",\n}).format(amount); // '-3,500.00 US dollars'\n\nnew Intl.NumberFormat(\"bn\", {\n  style: \"currency\",\n  currency: \"USD\",\n  currencySign: \"accounting\",\n}).format(amount); // '($3,500.00)'\n
\n
\n

Scientific, engineering or compact notations

\n
\n

Scientific and compact notation are represented by the notation option and can be formatted like this:

\n

js

\n
new Intl.NumberFormat(\"en-US\", {\n  notation: \"scientific\",\n}).format(987654321);\n// 9.877E8\n\nnew Intl.NumberFormat(\"pt-PT\", {\n  notation: \"scientific\",\n}).format(987654321);\n// 9,877E8\n\nnew Intl.NumberFormat(\"en-GB\", {\n  notation: \"engineering\",\n}).format(987654321);\n// 987.654E6\n\nnew Intl.NumberFormat(\"de\", {\n  notation: \"engineering\",\n}).format(987654321);\n// 987,654E6\n\nnew Intl.NumberFormat(\"zh-CN\", {\n  notation: \"compact\",\n}).format(987654321);\n// 9.9亿\n\nnew Intl.NumberFormat(\"fr\", {\n  notation: \"compact\",\n  compactDisplay: \"long\",\n}).format(987654321);\n// 988 millions\n\nnew Intl.NumberFormat(\"en-GB\", {\n  notation: \"compact\",\n  compactDisplay: \"short\",\n}).format(987654321);\n// 988M\n
\n
\n

Displaying signs

\n
\n

Display a sign for positive and negative numbers, but not zero:

\n

js

\n
new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  signDisplay: \"exceptZero\",\n}).format(0.55);\n// '+55%'\n
\n

Note that when the currency sign is \"accounting\", parentheses might be used instead of a minus sign:

\n

js

\n
new Intl.NumberFormat(\"bn\", {\n  style: \"currency\",\n  currency: \"USD\",\n  currencySign: \"accounting\",\n  signDisplay: \"always\",\n}).format(-3500);\n// '($3,500.00)'\n
\n
\n

FractionDigits, SignificantDigits and IntegerDigits

\n
\n

You can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.

Note: If both significant and fractional digit limits are specified, then the actual formatting depends on the roundingPriority.

Using FractionDigits and IntegerDigits

The integer and fraction digit properties indicate the number of digits to display before and after the decimal point, respectively. If the value to display has fewer integer digits than specified, it will be left-padded with zeros to the expected number. If it has fewer fractional digits, it will be right-padded with zeros. Both cases are shown below:

\n

js

\n
// Formatting adds zeros to display minimum integers and fractions\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    minimumIntegerDigits: 3,\n    minimumFractionDigits: 4,\n  }).format(4.33),\n);\n// \"004.3300\"\n
\n

If a value has more fractional digits than the specified maximum number, it will be rounded. The way that it is rounded depends on the roundingMode property (more details are provided in the rounding modes section). Below the value is rounded from five fractional digits (4.33145) to two (4.33):

\n

js

\n
// Display value shortened to maximum number of digits\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 2,\n  }).format(4.33145),\n);\n// \"4.33\"\n
\n

The minimum fractional digits have no effect if the value already has more than 2 fractional digits:

\n

js

\n
// Minimum fractions have no effect if value is higher precision.\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    minimumFractionDigits: 2,\n  }).format(4.33145),\n);\n// \"4.331\"\n
\n

Warning: Watch out for default values as they may affect formatting even if not specified in your code. The default maximum digit value is 3 for plain values, 2 for currency, and may have different values for other predefined types.

The formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits! This is because a default value of maximumFractionDigits is set when we specify minimumFractionDigits, and visa versa. The default values of maximumFractionDigits and minimumFractionDigits are 3 and 0, respectively.

You can use resolvedOptions() to inspect the formatter.

\n

js

\n
console.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 2,\n  }).resolvedOptions(),\n);\n// {\n//   …\n//   minimumIntegerDigits: 1,\n//   minimumFractionDigits: 0,\n//   maximumFractionDigits: 2,\n//   …\n// }\n\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    minimumFractionDigits: 2,\n  }).resolvedOptions(),\n);\n// {\n//   …\n//   minimumIntegerDigits: 1,\n//   minimumFractionDigits: 2,\n//   maximumFractionDigits: 3,\n//   …\n// }\n
\n

Using SignificantDigits

The number of significant digits is the total number of digits including both integer and fractional parts. The maximumSignificantDigits is used to indicate the total number of digits from the original value to display.

The examples below show how this works. Note in particular the last case: only the first digit is retained and the others are discarded/set to zero.

\n

js

\n
// Display 5 significant digits\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 5,\n  }).format(54.33145),\n);\n// \"54.331\"\n\n// Max 2 significant digits\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(54.33145),\n);\n// \"54\"\n\n// Max 1 significant digits\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 1,\n  }).format(54.33145),\n);\n// \"50\"\n
\n

The minimumSignificantDigits ensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.

\n

js

\n
// Minimum 10 significant digits\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    minimumSignificantDigits: 10,\n  }).format(54.33145),\n);\n// \"54.33145000\"\n
\n

Warning: Watch out for default values as they may affect formatting. If only one SignificantDigits property is used, then its counterpart will automatically be applied with the default value. The default maximum and minimum significant digit values are 20 and 1, respectively.

Specifying significant and fractional digits at the same time

The fraction digits (minimumFractionDigits/maximumFractionDigits) and significant digits (minimumSignificantDigits/maximumSignificantDigits) are both ways of controlling how many fractional and leading digits should be formatted. If both are used at the same time, it is possible for them to conflict.

These conflicts are resolved using the roundingPriority property. By default, this has a value of \"auto\", which means that if either minimumSignificantDigits or maximumSignificantDigits is specified, the fractional and integer digit properties will be ignored.

For example, the code below formats the value of 4.33145 with maximumFractionDigits: 3, and then maximumSignificantDigits: 2, and then both. The value with both is the one set with maximumSignificantDigits.

\n

js

\n
console.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 3,\n  }).format(4.33145),\n);\n// \"4.331\"\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(4.33145),\n);\n// \"4.3\"\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 3,\n    maximumSignificantDigits: 2,\n  }).format(4.33145),\n);\n// \"4.3\"\n
\n

Using resolvedOptions() to inspect the formatter, we can see that the returned object does not include maximumFractionDigits when maximumSignificantDigits or minimumSignificantDigits are specified.

\n

js

\n
console.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 3,\n    maximumSignificantDigits: 2,\n  }).resolvedOptions(),\n);\n// {\n//   …\n//   minimumIntegerDigits: 1,\n//   minimumSignificantDigits: 1,\n//   maximumSignificantDigits: 2,\n//   …\n// }\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumFractionDigits: 3,\n    minimumSignificantDigits: 2,\n  }).resolvedOptions(),\n);\n// {\n//   …\n//   minimumIntegerDigits: 1,\n//   minimumSignificantDigits: 2,\n//   maximumSignificantDigits: 21,\n//   …\n// }\n
\n

In addition to \"auto\", you can resolve conflicts by specifying roundingPriority as \"morePrecision\" or \"lessPrecision\". The formatter calculates the precision using the values of maximumSignificantDigits and maximumFractionDigits.

The code below shows the format being selected for the three different rounding priorities:

\n

js

\n
const maxFracNF = new Intl.NumberFormat(\"en\", {\n  maximumFractionDigits: 3,\n});\nconsole.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);\n// \"maximumFractionDigits:2 - 1.235\"\n\nconst maxSigNS = new Intl.NumberFormat(\"en\", {\n  maximumSignificantDigits: 3,\n});\nconsole.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);\n// \"maximumSignificantDigits:3 - 1.23\"\n\nconst bothAuto = new Intl.NumberFormat(\"en\", {\n  maximumSignificantDigits: 3,\n  maximumFractionDigits: 3,\n});\nconsole.log(`auto - ${bothAuto.format(1.23456)}`);\n// \"auto - 1.23\"\n\nconst bothLess = new Intl.NumberFormat(\"en\", {\n  roundingPriority: \"lessPrecision\",\n  maximumSignificantDigits: 3,\n  maximumFractionDigits: 3,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1.23456)}`);\n// \"lessPrecision - 1.23\"\n\nconst bothMore = new Intl.NumberFormat(\"en\", {\n  roundingPriority: \"morePrecision\",\n  maximumSignificantDigits: 3,\n  maximumFractionDigits: 3,\n});\nconsole.log(`morePrecision - ${bothMore.format(1.23456)}`);\n// \"morePrecision - 1.235\"\n
\n

Note that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value. The example below formats the value 1 specifying minimumFractionDigits: 2 (formatting to 1.00) and minimumSignificantDigits: 2 (formatting to 1.0). Since 1.00 has more digits than 1.0, this should be the result when prioritizing morePrecision, but in fact the opposite is true:

\n

js

\n
const bothLess = new Intl.NumberFormat(\"en\", {\n  roundingPriority: \"lessPrecision\",\n  minimumFractionDigits: 2,\n  minimumSignificantDigits: 2,\n});\nconsole.log(`lessPrecision - ${bothLess.format(1)}`);\n// \"lessPrecision - 1.00\"\n\nconst bothMore = new Intl.NumberFormat(\"en\", {\n  roundingPriority: \"morePrecision\",\n  minimumFractionDigits: 2,\n  minimumSignificantDigits: 2,\n});\nconsole.log(`morePrecision - ${bothMore.format(1)}`);\n// \"morePrecision - 1.0\"\n
\n

The reason for this is that only the \"maximum precision\" values are used for the calculation, and the default value of maximumSignificantDigits is much higher than maximumFractionDigits.

Note: The working group have proposed a modification of the algorithm where the formatter should evaluate the result of using the specified fractional and significant digits independently (taking account of both minimum and maximum values). It will then select the option that displays more fractional digits if morePrecision is set, and fewer if lessPrecision is set. This will result in more intuitive behavior for this case.

\n

Rounding modes

\n
\n

If a value has more fractional digits than allowed by the constructor options, the formatted value will be rounded to the specified number of fractional digits. The way in which the value is rounded depends on the roundingMode property.

Number formatters use halfExpand rounding by default, which rounds values \"away from zero\" at the half-increment (in other words, the magnitude of the value is rounded up).

For a positive number, if the fractional digits to be removed are closer to the next increment (or on the half way point) then the remaining fractional digits will be rounded up, otherwise they are rounded down. This is shown below: 2.23 rounded to two significant digits is truncated to 2.2 because 2.23 is less than the half increment 2.25, while values of 2.25 and greater are rounded up to 2.3:

\n

js

\n
// Value below half-increment: round down.\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(2.23),\n);\n// \"2.2\"\n\n// Value on or above half-increment: round up.\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(2.25),\n);\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(2.28),\n);\n// \"2.3\"\n// \"2.3\"\n
\n

A negative number on or below the half-increment point is also rounded away from zero (becomes more negative):

\n

js

\n
// Value below half-increment: round down.\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(-2.23),\n);\n// \"-2.2\"\n\n// Value on or above half-increment: round up.\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(-2.25),\n);\nconsole.log(\n  new Intl.NumberFormat(\"en\", {\n    maximumSignificantDigits: 2,\n  }).format(-2.28),\n);\n// \"-2.3\"\n// \"-2.3\"\n
\n

The table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.

rounding mode 2.23 2.25 2.28 -2.23 -2.25 -2.28
ceil 2.3 2.3 2.3 -2.2 -2.2 -2.2
floor 2.2 2.2 2.2 -2.3 -2.3 -2.3
expand 2.3 2.3 2.3 -2.3 -2.3 -2.3
trunc 2.2 2.2 2.2 -2.2 -2.2 -2.2
halfCeil 2.2 2.3 2.3 -2.2 -2.2 -2.3
halfFloor 2.2 2.2 2.3 -2.2 -2.3 -2.3
halfExpand 2.2 2.3 2.3 -2.2 -2.3 -2.3
halfTrunc 2.2 2.2 2.3 -2.2 -2.2 -2.3
halfEven 2.2 2.2 2.3 -2.2 -2.2 -2.3

When using halfEven, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of halfEven in the table above is the same as halfTrunc, because the magnitudes of all numbers are between a smaller \"even\" number (2.2) and a larger \"odd\" number (2.3). If the numbers are between ±2.3 and ±2.4, halfEven will behave like halfExpand instead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.

\n

Using roundingIncrement

\n
\n

Sometimes we want to round the remaining fractional digits to some other increment than the next integer. For example, currencies for which the smallest coin is 5 cents might want to round the value to increments of 5, reflecting amounts that can actually be paid in cash.

This kind of rounding can be achieved with the roundingIncrement property.

For example, if maximumFractionDigits is 2 and roundingIncrement is 5, then the number is rounded to the nearest 0.05:

\n

js

\n
const nf = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 2,\n  roundingIncrement: 5,\n});\n\nconsole.log(nf.format(11.29)); // \"$11.30\"\nconsole.log(nf.format(11.25)); // \"$11.25\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\n
\n

This particular pattern is referred to as \"nickel rounding\", where nickel is the colloquial name for a USA 5 cent coin. To round to the nearest 10 cents (\"dime rounding\"), you could change roundingIncrement to 10.

\n

js

\n
const nf = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 2,\n  roundingIncrement: 5,\n});\n\nconsole.log(nf.format(11.29)); // \"$11.30\"\nconsole.log(nf.format(11.25)); // \"$11.25\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\n
\n

You can also use roundingMode to change the rounding algorithm. The example below shows how halfCeil rounding can be used to round the value \"less positive\" below the half-rounding increment and \"more positive\" if above or on the half-increment. The incremented digit is \"0.05\" so the half-increment is at .025 (below, this is shown at 11.225).

\n

js

\n
const nf = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 2,\n  roundingIncrement: 5,\n  roundingMode: \"halfCeil\",\n});\n\nconsole.log(nf.format(11.21)); // \"$11.20\"\nconsole.log(nf.format(11.22)); // \"$11.20\"\nconsole.log(nf.format(11.224)); // \"$11.20\"\nconsole.log(nf.format(11.225)); // \"$11.25\"\nconsole.log(nf.format(11.23)); // \"$11.25\"\n
\n

If you need to change the number of digits, remember that minimumFractionDigits and maximumFractionDigits must both be set to the same value, or a RangeError is thrown.

roundingIncrement cannot be mixed with significant-digits rounding or any setting of roundingPriority other than auto.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-numberformat-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
IntlLegacyConstructedSymbol91
57The fallback symbol property has description IntlFallback.
\n
91
79The fallback symbol property has description IntlFallback.
\n
54No77
44The fallback symbol property has description IntlFallback.
\n
14.191
57The fallback symbol property has description IntlFallback.
\n
91
57The fallback symbol property has description IntlFallback.
\n
5664
43The fallback symbol property has description IntlFallback.
\n
14.516.0
7.0The fallback symbol property has description IntlFallback.
\n
?16.0.0
8.0.0The fallback symbol property has description IntlFallback.
\n
NumberFormat2412291115104.4255614101.51.80.12.0
locales_parameter2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the NumberFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options_compactDisplay_parameter777978No6414.17777795514.512.01.812.11.0
options_currencyDisplay_parameter777978No6414.1
10–14.1Doesn't support currencyDisplay: 'narrowSymbol'.
\n
7777795514.5
10–14.5Doesn't support currencyDisplay: 'narrowSymbol'.
\n
12.01.812.11.0
options_currencySign_parameter777978No6414.17777795514.512.01.812.11.0
options_currency_parameter2412291115104.4255614101.51.80.12.0
options_localeMatcher_parameter2412291115104.4255614101.51.80.12.0
options_maximumFractionDigits_parameter2412291115104.4255614101.51.80.12.0
options_maximumSignificantDigits_parameter2412291115104.4255614101.51.80.12.0
options_minimumFractionDigits_parameter2412291115104.4255614101.51.80.12.0
options_minimumIntegerDigits_parameter2412291115104.4255614101.51.80.12.0
options_minimumSignificantDigits_parameter2412291115104.4255614101.51.80.12.0
options_notation_parameter777978No6414.17777795514.512.01.812.11.0
options_numberingSystem_parameter2412291115104.4255614101.51.80.12.0
options_roundingIncrement_parameter106106116No9215.41061061167215.420.0No19.0.0
options_roundingMode_parameter106106116No9215.41061061167215.420.0No19.0.0
options_roundingPriority_parameter106106116No9215.41061061167215.420.0No19.0.0
options_signDisplay_parameter777978No6414.17777795514.512.01.812.11.0
options_style_parameter2412291115104.4255614101.51.80.12.0
options_trailingZeroDisplay_parameter106106116No9215.41061061167215.420.0NoNo
options_unitDisplay_parameter777978No6414.17777795514.512.01.812.11.0
options_unit_parameter777978No6414.17777795514.512.01.812.11.0
options_useGrouping_parameter2412291115104.4255614101.51.813.0.0
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the NumberFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat\n

\n
\n", + "global_objects/intl/numberformat/formattoparts": "

Intl.NumberFormat.prototype.formatToParts()

The formatToParts() method of Intl.NumberFormat instances allows locale-aware formatting of strings produced by this Intl.NumberFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatToParts()\nformatToParts(number)\n
\n

Parameters

\n
\nnumber Optional\n

A Number or BigInt to format.

Return value

\n

An Array of objects containing the formatted number in parts.

Description

\n
\n

The formatToParts() method is useful for custom formatting of number strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts() method returns, looks like this:

\n

js

\n
[\n  { type: \"integer\", value: \"3\" },\n  { type: \"group\", value: \".\" },\n  { type: \"integer\", value: \"500\" },\n];\n
\n

Possible types are the following:

compact

The exponent in \"long\" or \"short\" form, depending on how compactDisplay (which defaults to short) is specified when notation is set to compact.

currency

The currency string, such as the symbols \"$\" and \"€\" or the name \"Dollar\", \"Euro\", depending on how currencyDisplay is specified.

decimal

The decimal separator string (\".\").

exponentInteger

The exponent integer value, when notation is set to scientific or engineering.

exponentMinusSign

The exponent minus sign string (\"-\").

exponentSeparator

The exponent separator, when notation is set to scientific or engineering.

fraction

The fraction number.

group

The group separator string (\",\").

infinity

The Infinity string (\"∞\").

integer

The integer number.

literal

Any literal strings or whitespace in the formatted number.

minusSign

The minus sign string (\"-\").

nan

The NaN string (\"NaN\").

plusSign

The plus sign string (\"+\").

percentSign

The percent sign string (\"%\").

unit

The unit string, such as the \"l\" or \"litres\", depending on how unitDisplay is specified.

unknown

The string for unknown type results.

\n

Examples

\n

Comparing format and formatToParts

\n
\n

NumberFormat outputs localized, opaque strings that cannot be manipulated directly:

\n

js

\n
const number = 3500;\n\nconst formatter = new Intl.NumberFormat(\"de-DE\", {\n  style: \"currency\",\n  currency: \"EUR\",\n});\n\nformatter.format(number);\n// \"3.500,00 €\"\n
\n

However, in many User Interfaces there is a desire to customize the formatting of this string. The formatToParts method enables locale-aware formatting of strings produced by NumberFormat formatters by providing you the string in parts:

\n

js

\n
formatter.formatToParts(number);\n\n// return value:\n[\n  { type: \"integer\", value: \"3\" },\n  { type: \"group\", value: \".\" },\n  { type: \"integer\", value: \"500\" },\n  { type: \"decimal\", value: \",\" },\n  { type: \"fraction\", value: \"00\" },\n  { type: \"literal\", value: \" \" },\n  { type: \"currency\", value: \"€\" },\n];\n
\n

Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map(), arrow functions, a switch statement, template literals, and Array.prototype.reduce().

\n

js

\n
const numberString = formatter\n  .formatToParts(number)\n  .map(({ type, value }) => {\n    switch (type) {\n      case \"currency\":\n        return `<strong>${value}</strong>`;\n      default:\n        return value;\n    }\n  })\n  .reduce((string, part) => string + part);\n
\n

This will make the currency bold, when using the formatToParts() method.

\n

js

\n
console.log(numberString);\n// \"3.500,00 <strong>€</strong>\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.prototype.formattoparts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatToParts641258No511364645847139.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts\n

\n
\n", + "global_objects/intl/numberformat/resolvedoptions": "

Intl.NumberFormat.prototype.resolvedOptions()

The resolvedOptions() method of Intl.NumberFormat instances returns a new object with properties reflecting the locale and number formatting options computed during initialization of this Intl.NumberFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n
\n

A new object with properties reflecting the locale and number formatting options computed during the construction of the given Intl.NumberFormat object.

The resulting object has the following properties:

compactDisplay

Whether to use short or long form when using compact notation. This is the value provided in the options.compactDisplay argument of the constructor, or the default value: \"short\". The value is only present if notation is set to \"compact\", and otherwise is undefined.

currency

The currency to use in currency formatting. The value is defined if style is \"currency\", and is otherwise undefined. This is the value provided in the options.currency argument of the constructor.

currencyDisplay

The display format for the currency, such as a symbol, or currency code. The value is defined if style is \"currency\", and otherwise is undefined. This is the value provided in the options.currencyDisplay argument of the constructor, or the default value: \"symbol\".

currencySign

The method used to specify the sign of the currency value: standard or accounting. The value is present if style is \"currency\", and otherwise is undefined. This is the value provided in the options.currencySign argument of the constructor, or the default value: \"standard\".

locale

The BCP 47 language tag for the locale that was actually used. The key-value pairs that were requested in the constructor locale and are supported for this locale are included.

notation

The formatting that should be applied to the number, such as standard or engineering. This is the value provided in the options.notation argument of the constructor, or the default value: \"standard\".

numberingSystem

The numbering system. This is the value provided in the options.numberingSystem argument of the constructor, if present, or the value set using the Unicode extension key nu, or filled in as a default.

roundingMode

The rounding mode. This is the value provided for the options.roundingMode argument in the constructor, or the default value: halfExpand.

roundingPriority

The priority for resolving rounding conflicts if both \"FractionDigits\" and \"SignificantDigits\" are specified. This is the value provided for the options.roundingPriority argument in the constructor, or the default value: auto.

roundingIncrement

The rounding-increment precision (the increment used when rounding numbers). This is the value specified in the options.roundingIncrement argument in the constructor.

signDisplay

Whether or not to display the positive/negative sign. This is the value specified in the options.signDisplay argument in the constructor, or the default value: \"auto\".

unit

The unit to use in unit formatting. The value is only present if style is \"unit\", and is otherwise undefined. This is the value specified in the options.unit argument in the constructor.

unitDisplay

The display format to use for units in unit formatting, such as \"long\", \"short\" or \"narrow\". The value is only present if style is \"unit\", and is otherwise undefined. This is the value specified in the options.unitDisplay argument in the constructor, or the default value: short.

useGrouping

Whether or not to use grouping separators to indicate \"thousands\", \"millions\" and son on. This is the value specified in the options.useGrouping argument in the constructor, or the default value: \"auto\".

trailingZeroDisplay

The strategy for displaying trailing zeros on whole numbers. This is the value specified in the options.trailingZeroDisplay argument in the constructor, or the default value: \"auto\".

Only one of the following two groups of properties is included:

\nminimumIntegerDigits, minimumFractionDigits, maximumFractionDigits\n

The values provided for these properties in the options argument or filled in as defaults. These properties are present only if neither minimumSignificantDigits nor maximumSignificantDigits was provided in the options argument.

\nminimumSignificantDigits, maximumSignificantDigits\n

The values provided for these properties in the options argument or filled in as defaults. These properties are present only if at least one of them was provided in the options argument.

\n

Examples

\n

Using the resolvedOptions method

\n
\n

js

\n
// Create a NumberFormat\nconst de = new Intl.NumberFormat(\"de-DE\", {\n  style: \"currency\",\n  currency: \"USD\",\n  maximumFractionDigits: 2,\n  roundingIncrement: 5,\n  roundingMode: \"halfCeil\",\n});\n\n// Resolve the options\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.numberingSystem); // \"latn\"\nconsole.log(usedOptions.compactDisplay); // undefined (\"notation\" not set to \"compact\")\nconsole.log(usedOptions.currency); // \"USD\"\nconsole.log(usedOptions.currencyDisplay); // \"symbol\"\nconsole.log(usedOptions.currencySign); // \"standard\"\nconsole.log(usedOptions.minimumIntegerDigits); // 1\nconsole.log(usedOptions.minimumFractionDigits); // 2\nconsole.log(usedOptions.maximumFractionDigits); // 2\nconsole.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)\nconsole.log(usedOptions.notation); // \"standard\"\nconsole.log(usedOptions.roundingIncrement); // 5\nconsole.log(usedOptions.roundingMode); // halfCeil\nconsole.log(usedOptions.roundingPriority); // auto\nconsole.log(usedOptions.signDisplay); // \"auto\"\nconsole.log(usedOptions.style); // \"currency\"\nconsole.log(usedOptions.trailingZeroDisplay); // auto\nconsole.log(usedOptions.useGrouping); // auto\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.numberformat.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions2412291115104.4255614101.51.8
0.12.0Before version 13.0.0, only the locale data for en-US is available by default. See the NumberFormat() constructor for more details.
result_roundingIncrement_property106106116No9216.41061061167216.420.0No19.0.0
result_roundingMode_property106106116No9216.41061061167216.420.0No19.0.0
result_roundingPriority_property106106116No9216.41061061167216.420.0No19.0.0
result_signDisplay_property106106116No9216.41061061167216.420.0No19.0.0
result_trailingZeroDisplay_property106106116No9216.41061061167216.420.0No19.0.0
result_useGrouping_property106106116No9216.41061061167216.420.0No19.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions\n

\n
\n", + "global_objects/intl/pluralrules/select": "

Intl.PluralRules.prototype.select()

The select() method of Intl.PluralRules instances returns a string indicating which plural rule to use for locale-aware formatting of a number.

\n

Try it

\n

Syntax

\n
\n

js

\n
select(number)\n
\n

Parameters

\n
number

The number to get a plural rule for.

Return value

\n

A string representing the pluralization category of the number. This can be one of zero, one, two, few, many, or other.

Description

\n

This function selects a pluralization category according to the locale and formatting options of an Intl.PluralRules object. These options are set in the Intl.PluralRules() constructor.

Examples

\n

Using select()

\n
\n

First, create an Intl.PluralRules object, passing the appropriate locales and options parameters. Here we create a plural rules object for Arabic in the Egyptian dialect. Because the type is not specified the rules object will provide formatting for cardinal numbers (the default).

\n

js

\n
const pr = new Intl.PluralRules(\"ar-EG\");\n
\n

Then call select() on the rules object, specifying the number for which the plural form is required. Note that Arabic has 5 forms for cardinal numbers, as shown.

\n

js

\n
pr.select(0); // 'zero'\npr.select(1); // 'one'\npr.select(2); // 'two'\npr.select(6); // 'few'\npr.select(18); // 'many'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.pluralrules.prototype.select
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
select631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/select\n

\n
\n", + "global_objects/intl/pluralrules/selectrange": "

Intl.PluralRules.prototype.selectRange()

The selectRange() method of Intl.PluralRules instances receives two values and returns a string indicating which plural rule to use for locale-aware formatting of the indicated range.

\n

Syntax

\n
\n

js

\n
selectRange(startRange, endRange)\n
\n

Parameters

\n
startRange

A number representing the start of the range.

endRange

A number representing the end of the range.

Return value

\n

A string representing the pluralization category of the specified range. This can be one of zero, one, two, few, many or other, that are relevant for the locale whose localization is specified in LDML Language Plural Rules.

Description

\n
\n

This function selects a pluralization category according to the locale and formatting options of an Intl.PluralRules object.

Conceptually the behavior is the same as getting plural rules for a single cardinal or ordinal number. Languages have one or more forms for describing ranges, and this method returns the appropriate form given the supplied locale and formatting options. In English there is only one plural form, such as \"1–10 apples\", and the method will return other. Other languages can have many forms.

\n

Examples

\n

Using selectRange()

\n
\n

js

\n
new Intl.PluralRules(\"sl\").selectRange(102, 201); // 'few'\n\nnew Intl.PluralRules(\"pt\").selectRange(102, 102); // 'other'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.pluralrules.prototype.selectrange
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
selectRange106106116No9215.41061061167215.420.0No19.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/selectRange\n

\n
\n", + "global_objects/intl/pluralrules/pluralrules": "

Intl.PluralRules() constructor

The Intl.PluralRules() constructor creates Intl.PluralRules objects.

\n

Syntax

\n
\n
\n

js

\n
new Intl.PluralRules()\nnew Intl.PluralRules(locales)\nnew Intl.PluralRules(locales, options)\n
\n

Note: Intl.PluralRules() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

type

The type to use. Possible values are:

\n\"cardinal\" (default)

For cardinal numbers (referring to the quantity of things).

\"ordinal\"

For ordinal number (referring to the ordering or ranking of things, e.g. \"1st\", \"2nd\", \"3rd\" in English).

Intl.PluralRules also supports the Intl.NumberFormat() digit options (see Intl.NumberFormat() for details):

  • minimumIntegerDigits
  • minimumFractionDigits
  • maximumFractionDigits
  • minimumSignificantDigits
  • maximumSignificantDigits
  • roundingPriority
  • roundingIncrement
  • roundingMode

These options are interpreted as if the notation option from Intl.NumberFormat is \"standard\" and style is \"decimal\".

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Basic usage

\n
\n

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. This is useful to distinguish between singular and plural forms, e.g. \"dog\" and \"dogs\".

\n

js

\n
const pr = new Intl.PluralRules();\n\npr.select(0); // 'other' if in US English locale\n\npr.select(1); // 'one' if in US English locale\n\npr.select(2); // 'other' if in US English locale\n
\n
\n

Using options

\n
\n

The results can be customized using the options argument, which has one property called type which you can set to ordinal. This is useful to figure out the ordinal indicator, e.g. \"1st\", \"2nd\", \"3rd\", \"4th\", \"42nd\", and so forth.

\n

js

\n
const pr = new Intl.PluralRules(\"en-US\", { type: \"ordinal\" });\n\nconst suffixes = new Map([\n  [\"one\", \"st\"],\n  [\"two\", \"nd\"],\n  [\"few\", \"rd\"],\n  [\"other\", \"th\"],\n]);\nconst formatOrdinals = (n) => {\n  const rule = pr.select(n);\n  const suffix = suffixes.get(rule);\n  return `${n}${suffix}`;\n};\n\nformatOrdinals(0); // '0th'\nformatOrdinals(1); // '1st'\nformatOrdinals(2); // '2nd'\nformatOrdinals(3); // '3rd'\nformatOrdinals(4); // '4th'\nformatOrdinals(11); // '11th'\nformatOrdinals(21); // '21st'\nformatOrdinals(42); // '42nd'\nformatOrdinals(103); // '103rd'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-pluralrules-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
PluralRules631858No501363635846138.01.813.0.0
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the PluralRules instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
options_roundingIncrement_parameterNoNo116NoNoNoNoNo116NoNoNoNoNo
options_roundingMode_parameterNoNo116NoNoNoNoNo116NoNoNoNoNo
options_roundingPriority_parameterNoNo116NoNoNoNoNo116NoNoNoNoNo
options_trailingZeroDisplay_parameterNoNo116NoNoNoNoNo116NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules\n

\n
\n", + "global_objects/intl/pluralrules/supportedlocalesof": "

Intl.PluralRules.supportedLocalesOf()

The Intl.PluralRules.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in plural rules without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.PluralRules.supportedLocalesOf(locales)\nIntl.PluralRules.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in plural rules without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in plural rules, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to plural rules nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.PluralRules.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.pluralrules.supportedlocalesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/supportedLocalesOf\n

\n
\n", + "global_objects/intl/pluralrules/resolvedoptions": "

Intl.PluralRules.prototype.resolvedOptions()

The resolvedOptions() method of Intl.PluralRules instances returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this Intl.PluralRules object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n
\n

A new object with properties reflecting the locale and plural formatting options computed during the initialization of the given Intl.PluralRules object.

The object has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

pluralCategories

An Array of plural categories used by the given locale, selected from the list \"zero\", \"one\", \"two\", \"few\", \"many\" and \"other\".

type

The type used (cardinal or ordinal).

\nroundingMode Experimental \n

The rounding mode. This is the value provided for the options.roundingMode argument in the constructor, or the default value: halfExpand.

\nroundingPriority Experimental \n

The priority for resolving rounding conflicts if both \"FractionDigits\" and \"SignificantDigits\" are specified. This is the value provided for the options.roundingPriority argument in the constructor, or the default value: auto.

\nroundingIncrement Experimental \n

The rounding-increment precision (the increment used when rounding numbers). This is the value specified in the options.roundingIncrement argument in the constructor.

\ntrailingZeroDisplay Experimental \n

The strategy for displaying trailing zeros on whole numbers. This is the value specified in the options.trailingZeroDisplay argument in the constructor, or the default value: \"auto\".

Only one of the following two groups of properties is included:

\nminimumIntegerDigits, minimumFractionDigits, maximumFractionDigits\n

The values provided for these properties in the options argument or filled in as defaults. These properties are present only if neither minimumSignificantDigits nor maximumSignificantDigits was provided in the options argument.

\nminimumSignificantDigits, maximumSignificantDigits\n

The values provided for these properties in the options argument or filled in as defaults. These properties are present only if at least one of them was provided in the options argument.

\n

Examples

\n

Using the resolvedOptions() method

\n
\n

The code below shows the construction of a PluralRules object, followed by logging of each of the resolved options.

\n

js

\n
// Create a PluralRules instance\nconst de = new Intl.PluralRules(\"de-DE\", {\n  maximumSignificantDigits: 2,\n  trailingZeroDisplay: \"auto\",\n});\n\n// Resolve the options\nconst usedOptions = de.resolvedOptions();\nconsole.log(usedOptions.locale); // \"de-DE\"\nconsole.log(usedOptions.pluralCategories); // Array [\"one\", \"other\"]\nconsole.log(usedOptions.type); // \"cardinal\"\nconsole.log(usedOptions.minimumIntegerDigits); // 1\nconsole.log(usedOptions.minimumFractionDigits); // undefined (maximumSignificantDigits is set)\nconsole.log(usedOptions.maximumFractionDigits); //undefined (maximumSignificantDigits is set)\nconsole.log(usedOptions.minimumSignificantDigits); // 1\nconsole.log(usedOptions.maximumSignificantDigits); //2\nconsole.log(usedOptions.roundingIncrement); // 1\nconsole.log(usedOptions.roundingMode); // \"halfExpand\"\nconsole.log(usedOptions.roundingPriority); // \"auto\"\nconsole.log(usedOptions.trailingZeroDisplay); // \"auto\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.pluralrules.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions631858No501363635846138.01.8
10.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the PluralRules() constructor for more details.
result_roundingIncrement_propertyNoNo116NoNoNoNoNo116NoNoNoNoNo
result_roundingMode_propertyNoNo116NoNoNoNoNo116NoNoNoNoNo
result_roundingPriority_propertyNoNo116NoNoNoNoNo116NoNoNoNoNo
result_trailingZeroDisplay_propertyNoNo116NoNoNoNoNo116NoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/resolvedOptions\n

\n
\n", + "global_objects/intl/relativetimeformat/supportedlocalesof": "

Intl.RelativeTimeFormat.supportedLocalesOf()

The Intl.RelativeTimeFormat.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in relative time formatting without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.RelativeTimeFormat.supportedLocalesOf(locales)\nIntl.RelativeTimeFormat.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in relative time formatting without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in relative time formatting, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to relative time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.RelativeTimeFormat.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.RelativeTimeFormat.supportedLocalesOf
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf717965No5814717165501410.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf\n

\n
\n", + "global_objects/intl/relativetimeformat/format": "

Intl.RelativeTimeFormat.prototype.format()

The format() method of Intl.RelativeTimeFormat instances formats a value and unit according to the locale and formatting options of this Intl.RelativeTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
format(value, unit)\n
\n

Parameters

\n
value

Numeric value to use in the internationalized relative time message.

unit

Unit to use in the relative time internationalized message. Possible values are: \"year\", \"quarter\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\". Plural forms are also permitted.

Return value

\n

A string representing the given value and unit formatted according to the locale and formatting options of this Intl.RelativeTimeFormat object.

Examples

\n

Basic format usage

\n
\n

The following example shows how to create a relative time formatter using the English language.

\n

js

\n
// Create a relative time formatter in your locale\n// with default values explicitly passed in.\nconst rtf = new Intl.RelativeTimeFormat(\"en\", {\n  localeMatcher: \"best fit\", // other values: \"lookup\"\n  numeric: \"always\", // other values: \"auto\"\n  style: \"long\", // other values: \"short\" or \"narrow\"\n});\n\n// Format relative time using negative value (-1).\nrtf.format(-1, \"day\"); // \"1 day ago\"\n\n// Format relative time using positive value (1).\nrtf.format(1, \"day\"); // \"in 1 day\"\n
\n
\n

Using the auto option

\n
\n

If numeric:auto option is passed, it will produce the string yesterday, today, or tomorrow instead of 1 day ago, in 0 days, or in 1 day. This allows to not always have to use numeric values in the output.

\n

js

\n
// Create a relative time formatter in your locale\n// with numeric: \"auto\" option value passed in.\nconst rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n\n// Format relative time using negative value (-1).\nrtf.format(-1, \"day\"); // \"yesterday\"\n\nrtf.format(0, \"day\"); // \"today\"\n\n// Format relative time using positive day unit (1).\nrtf.format(1, \"day\"); // \"tomorrow\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.RelativeTimeFormat.prototype.format
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
format717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format\n

\n
\n", + "global_objects/intl/relativetimeformat/formattoparts": "

Intl.RelativeTimeFormat.prototype.formatToParts()

The formatToParts() method of Intl.RelativeTimeFormat instances returns an Array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.

\n

Try it

\n

Syntax

\n
\n

js

\n
formatToParts(value, unit)\n
\n

Parameters

\n
value

Numeric value to use in the internationalized relative time message.

unit

Unit to use in the relative time internationalized message. Possible values are: \"year\", \"quarter\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\". Plural forms are also permitted.

Return value

\n

An Array of objects containing the formatted relative time in parts.

Description

\n

The Intl.RelativeTimeFormat.prototype.formatToParts method is a version of the format method which it returns an array of objects which represent \"parts\" of the object, separating the formatted number into its constituent parts and separating it from other surrounding text. These objects have two properties: type a NumberFormat formatToParts type, and value, which is the String which is the component of the output. If a \"part\" came from NumberFormat, it will have a unit property which indicates the unit being formatted; literals which are part of the larger frame will not have this property.

Examples

\n

Using formatToParts

\n
\n

js

\n
const rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n\n// Format relative time using the day unit\nrtf.formatToParts(-1, \"day\");\n// [{ type: \"literal\", value: \"yesterday\"}]\n\nrtf.formatToParts(100, \"day\");\n// [\n//   { type: \"literal\", value: \"in \" },\n//   { type: \"integer\", value: \"100\", unit: \"day\" },\n//   { type: \"literal\", value: \" days\" }\n// ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-Intl.RelativeTimeFormat.prototype.formatToParts
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
formatToParts717970No5814717179501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts\n

\n
\n", + "global_objects/intl/relativetimeformat/resolvedoptions": "

Intl.RelativeTimeFormat.prototype.resolvedOptions()

The resolvedOptions() method of Intl.RelativeTimeFormat instances returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this Intl.RelativeTimeFormat object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

A new object with properties reflecting the locale and number formatting options computed during the initialization of the given Intl.RelativeTimeFormat object.

Description

\n
\n

The resulting object has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

style

The length of the internationalized message. Possible values are:

  • \n\"long\" (default, e.g., in 1 month)
  • \n\"short\" (e.g., in 1 mo.),
  • or \"narrow\" (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales.
numeric

The format of output message. Possible values are:

  • \n\"always\" (default, e.g., 1 day ago),
  • or \"auto\" (e.g., yesterday). The \"auto\" value allows to not always have to use numeric values in the output.
numberingSystem

The value requested using the Unicode extension key \"nu\" or filled in as a default.

\n

Examples

\n

Using the resolvedOptions() method

\n
\n

js

\n
const de = new Intl.RelativeTimeFormat(\"de-DE\");\nconst usedOptions = de.resolvedOptions();\n\nusedOptions.locale; // \"de-DE\"\nusedOptions.style; // \"long\"\nusedOptions.numeric; // \"always\"\nusedOptions.numberingSystem; // \"latn\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.relativetimeformat.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions717965No5814717165501410.01.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.
numberingSystem737970No6014737379521411.01.812.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions\n

\n
\n", + "global_objects/intl/segmenter/segmenter": "

Intl.Segmenter() constructor

The Intl.Segmenter() constructor creates Intl.Segmenter objects.

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
new Intl.Segmenter()\nnew Intl.Segmenter(locales)\nnew Intl.Segmenter(locales, options)\n
\n

Note: Intl.Segmenter() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

granularity

How granularly should the input be split. Possible values are:

\n\"grapheme\" (default)

Split the input into segments at grapheme cluster (user-perceived character) boundaries, as determined by the locale.

\"word\"

Split the input into segments at word boundaries, as determined by the locale.

\"sentence\"

Split the input into segments at sentence boundaries, as determined by the locale.

Return value

\n

A new Intl.Segmenter instance.

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Basic usage

\n
\n

The following example shows how to count words in a string using the Japanese language (where splitting the string using String methods would have given an incorrect result).

\n

js

\n
const text = \"吾輩は猫である。名前はたぬき。\";\nconst japaneseSegmenter = new Intl.Segmenter(\"ja-JP\", { granularity: \"word\" });\nconsole.log(\n  [...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike)\n    .length,\n);\n// 8, as the text is segmented as '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。'\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-segmenter-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Segmenter8787NoNo7314.18787No6214.514.01.816.0.0
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter\n

\n
\n", + "global_objects/intl/segmenter/supportedlocalesof": "

Intl.Segmenter.supportedLocalesOf()

The Intl.Segmenter.supportedLocalesOf() static method returns an array containing those of the provided locales that are supported in segmentation without having to fall back to the runtime's default locale.

\n

Try it

\n

Syntax

\n
\n

js

\n
Intl.Segmenter.supportedLocalesOf(locales)\nIntl.Segmenter.supportedLocalesOf(locales, options)\n
\n

Parameters

\n
locales

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object that may have the following property:

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see the Intl page.

Return value

\n

An array of strings representing a subset of the given locale tags that are supported in segmentation without having to fall back to the runtime's default locale.

Examples

\n

Using supportedLocalesOf()

\n
\n

Assuming a runtime that supports Indonesian and German but not Balinese in segmentation, supportedLocalesOf returns the Indonesian and German language tags unchanged, even though pinyin collation is neither relevant to segmentation nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the \"lookup\" algorithm here — a \"best fit\" matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

\n

js

\n
const locales = [\"ban\", \"id-u-co-pinyin\", \"de-ID\"];\nconst options = { localeMatcher: \"lookup\" };\nconsole.log(Intl.Segmenter.supportedLocalesOf(locales, options));\n// [\"id-u-co-pinyin\", \"de-ID\"]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.segmenter.supportedlocalesof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
supportedLocalesOf8787NoNo7314.18787No6214.514.01.816.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf\n

\n
\n", + "global_objects/intl/segmenter/resolvedoptions": "

Intl.Segmenter.prototype.resolvedOptions()

The resolvedOptions() method of Intl.Segmenter instances returns a new object with properties reflecting the locale and granularity options computed during the initialization of this Intl.Segmenter object.

\n

Try it

\n

Syntax

\n
\n

js

\n
resolvedOptions()\n
\n

Parameters

\n

None.

Return value

\n

A new object with properties reflecting the locale and collation options computed during the initialization of the given Intl.Segmenter object.

Description

\n
\n

The resulting object has the following properties:

locale

The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale.

granularity

The value provided for this property in the options argument or filled in as the default.

\n

Examples

\n

Basic usage

\n
\n

js

\n
const spanishSegmenter = new Intl.Segmenter(\"es\", { granularity: \"sentence\" });\nconst options = spanishSegmenter.resolvedOptions();\nconsole.log(options.locale); // \"es\"\nconsole.log(options.granularity); // \"sentence\"\n
\n

Default granularity

\n
\n

js

\n
const spanishSegmenter = new Intl.Segmenter(\"es\");\nconst options = spanishSegmenter.resolvedOptions();\nconsole.log(options.locale); // \"es\"\nconsole.log(options.granularity); // \"grapheme\"\n
\n

Fallback locale

\n
\n

js

\n
const banSegmenter = new Intl.Segmenter(\"ban\");\nconst options = banSegmenter.resolvedOptions();\nconsole.log(options.locale);\n// \"fr\" on a runtime where the Balinese locale\n// is not supported and French is the default locale\nconsole.log(options.granularity); // \"grapheme\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl.segmenter.prototype.resolvedoptions
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolvedOptions8787NoNo7314.18787No6214.514.01.816.0.0
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/resolvedOptions\n

\n
\n", + "errors/stmt_after_return": "

Warning: unreachable code after return statement

The JavaScript warning \"unreachable code after return statement\" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.

\n

Message

\n
Warning: unreachable code after return statement (Firefox)\n

Error type

\n

Warning

What went wrong?

\n
\n

Unreachable code after a return statement might occur in these situations:

When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run.

Why should I have semicolons after return statements? In the case of semicolon-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return. The warning indicates that there is ambiguity in the way the return statement is written.

Warnings will not be shown for semicolon-less returns if these statements follow it:

\n

Examples

\n

Invalid cases

\n
\n

js

\n
function f() {\n  let x = 3;\n  x += 4;\n  return x;   // return exits the function immediately\n  x -= 3;     // so this line will never run; it is unreachable\n}\n\nfunction g() {\n  return     // this is treated like `return;`\n    3 + 4;   // so the function returns, and this line is never reached\n}\n
\n

Valid cases

\n
\n

js

\n
function f() {\n  let x = 3;\n  x += 4;\n  x -= 3;\n  return x; // OK: return after all other statements\n}\n\nfunction g() {\n  return 3 + 4 // OK: semicolon-less return with expression on the same line\n}\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Stmt_after_return\n

\n
\n", + "errors/invalid_for-in_initializer": "

SyntaxError: for-in loop head declarations may not have initializers

The JavaScript strict mode-only exception \"for-in loop head declarations may not have initializers\" occurs when the head of a for...in contains an initializer expression, such as for (var i = 0 in obj). This is not allowed in for-in loops in strict mode. In addition, lexical declarations with initializers like for (const i = 0 in obj) are not allowed outside strict mode either.

\n

Message

\n
SyntaxError: for-in loop variable declaration may not have an initializer. (V8-based)\nSyntaxError: for-in loop head declarations may not have initializers (Firefox)\nSyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer (Firefox)\nSyntaxError: Cannot assign to the loop variable inside a for-in loop header. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

The head of a for...in loop contains an initializer expression. That is, a variable is declared and assigned a value for (var i = 0 in obj). In non-strict mode, this head declaration is silently ignored and behaves like for (var i in obj). In strict mode, however, a SyntaxError is thrown. In addition, lexical declarations with initializers like for (const i = 0 in obj) are not allowed outside strict mode either, and will always produce a SyntaxError.

Examples

\n
\n

This example throws a SyntaxError:

\n

js

\n
const obj = { a: 1, b: 2, c: 3 };\n\nfor (const i = 0 in obj) {\n  console.log(obj[i]);\n}\n\n// SyntaxError: for-in loop head declarations may not have initializers\n
\n
\n

Valid for-in loop

\n
\n

You can remove the initializer (i = 0) in the head of the for-in loop.

\n

js

\n
const obj = { a: 1, b: 2, c: 3 };\n\nfor (const i in obj) {\n  console.log(obj[i]);\n}\n
\n
\n

Array iteration

\n
\n

The for...in loop shouldn't be used for Array iteration. Did you intend to use a for loop instead of a for-in loop to iterate an Array? The for loop allows you to set an initializer then as well:

\n

js

\n
const arr = [\"a\", \"b\", \"c\"];\n\nfor (let i = 2; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n\n// \"c\"\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer\n

\n
\n", + "global_objects/intl/relativetimeformat/relativetimeformat": "

Intl.RelativeTimeFormat() constructor

The Intl.RelativeTimeFormat() constructor creates Intl.RelativeTimeFormat objects.

\n

Syntax

\n
\n
\n

js

\n
new Intl.RelativeTimeFormat()\nnew Intl.RelativeTimeFormat(locales)\nnew Intl.RelativeTimeFormat(locales, options)\n
\n

Note: Intl.RelativeTimeFormat() can only be constructed with new. Attempting to call it without new throws a TypeError.

\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

The following Unicode extension key is allowed:

nu

See numberingSystem.

This key can also be set with options (as listed below). When both are set, the options property takes precedence.

\noptions Optional\n

An object containing the following properties, in the order they are retrieved (all of them are optional):

localeMatcher

The locale matching algorithm to use. Possible values are \"lookup\" and \"best fit\"; the default is \"best fit\". For information about this option, see Locale identification and negotiation.

numberingSystem

The numbering system to use for number formatting, such as \"arab\", \"hans\", \"mathsans\", and so on. For a list of supported numbering system types, see Intl.Locale.prototype.getNumberingSystems(). This option can also be set through the nu Unicode extension key; if both are provided, this options property takes precedence.

style

The style of the formatted relative time. Possible values are:

\n\"long\" (default)

E.g., \"in 1 month\"

\"short\"

E.g., \"in 1 mo.\"

\"narrow\"

E.g., \"in 1 mo.\". The narrow style could be similar to the short style for some locales.

numeric

Whether to use numeric values in the output. Possible values are \"always\" and \"auto\"; the default is \"always\". When set to \"auto\", the output may use more idiomatic phrasing such as \"yesterday\" instead of \"1 day ago\".

Exceptions

\n
RangeError

Thrown if locales or options contain invalid values.

Examples

\n

Basic format usage

\n
\n

The following example shows how to create a relative time formatter using the English language.

\n

js

\n
// Create a relative time formatter in your locale\n// with default values explicitly passed in.\nconst rtf = new Intl.RelativeTimeFormat(\"en\", {\n  localeMatcher: \"best fit\", // other values: \"lookup\"\n  numeric: \"always\", // other values: \"auto\"\n  style: \"long\", // other values: \"short\" or \"narrow\"\n});\n\n// Format relative time using negative value (-1).\nrtf.format(-1, \"day\"); // \"1 day ago\"\n\n// Format relative time using positive value (1).\nrtf.format(1, \"day\"); // \"in 1 day\"\n
\n
\n

Using the auto option

\n
\n

If numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day. This allows to not always have to use numeric values in the output.

\n

js

\n
// Create a relative time formatter in your locale\n// with numeric: \"auto\" option value passed in.\nconst rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n\n// Format relative time using negative value (-1).\nrtf.format(-1, \"day\"); // \"yesterday\"\n\n// Format relative time using positive day unit (1).\nrtf.format(1, \"day\"); // \"tomorrow\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-intl-relativetimeformat-constructor
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
RelativeTimeFormat717965No5814717165501410.01.813.0.0
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the RelativeTimeFormat instance silently falls back to en-US. To make full ICU (locale) data available before version 13, see Node.js documentation on the --with-intl option and how to provide the data.
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat\n

\n
\n", + "regular_expressions/character_escape": "

Character escape: \\n, \\u{...}

A character escape represents a character that may not be able to be conveniently represented in its literal form.

\n

Syntax

\n
\n
\n

regex

\n
\\f, \\n, \\r, \\t, \\v\n\\cA, \\cB, …, \\cz\n\\0\n\\^, \\$, \\\\, \\., \\*, \\+, \\?, \\(, \\), \\[, \\], {, }, \\|, \\/\n\n\\xHH\n\\uHHHH\n\\u{HHH}\n
\n

Note: , is not part of the syntax.

\n

Parameters

\n
HHH

A hexadecimal number representing the Unicode code point of the character. The \\xHH form must have two hexadecimal digits; the \\uHHHH form must have four; the \\u{HHH} form may have 1 to 6 hexadecimal digits.

Description

\n
\n

The following character escapes are recognized in regular expressions:

\n\\f, \\n, \\r, \\t, \\v\n

Same as those in string literals, except \\b, which represents a word boundary in regexes unless in a character class.

\n\\c followed by a letter from A to Z or a to z\n

Represents the control character with value equal to the letter's character value modulo 32. For example, \\cJ represents line break (\\n), because the code point of J is 74, and 74 modulo 32 is 10, which is the code point of line break. Because an uppercase letter and its lowercase form differ by 32, \\cJ and \\cj are equivalent. You can represent control characters from 1 to 26 in this form.

\\0

Represents the U+0000 NUL character. Cannot be followed by a digit (which makes it a legacy octal escape sequence).

\n\\^, \\$, \\\\, \\. \\*, \\+, \\?, \\(, \\), \\[, \\], {, }, \\|, \\/\n

Represents the character itself. For example, \\\\ represents a backslash, and \\( represents a left parenthesis. These are syntax characters in regexes (/ is the delimiter of a regex literal), so they require escaping unless in a character class.

\\xHH

Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly two digits long.

\\uHHHH

Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly four digits long. Two such escape sequences can be used to represent a surrogate pair in Unicode-aware mode. (In Unicode-unaware mode, they are always two separate characters.)

\\u{HHH}

(Unicode-aware mode only) Represents the character with the given hexadecimal Unicode code point. The hexadecimal number can be from 1 to 6 digits long.

In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \\a represents the character a. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.

In Unicode-unaware mode, ], {, and } may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a deprecated syntax for web compatibility, and you should not rely on it.

In Unicode-unaware mode, escape sequences within character classes of the form \\cX where X is a number or _ are decoded in the same way as those with ASCII letters: \\c0 is the same as \\cP when taken modulo 32. In addition, if the form \\cX is encountered anywhere where X is not one of the recognized characters, then the backslash is treated as a literal character. These syntaxes are also deprecated.

\n

js

\n
/[\\c0]/.test(\"\\x10\"); // true\n/[\\c_]/.test(\"\\x1f\"); // true\n/[\\c*]/.test(\"\\\\\"); // true\n/\\c/.test(\"\\\\c\"); // true\n/\\c0/.test(\"\\\\c0\"); // true (the \\c0 syntax is only supported in character classes)\n
\n
\n

Examples

\n

Using character escapes

\n
\n

Character escapes are useful when you want to match a character that is not easily represented in its literal form. For example, you cannot use a line break literally in a regex literal, so you must use a character escape:

\n

js

\n
const pattern = /a\\nb/;\nconst string = `a\nb`;\nconsole.log(pattern.test(string)); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-CharacterEscape
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Character_escape11214514.418410.111.01.00.10.0
unicode501246No371050504637105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape\n

\n
\n", + "operators/operator_precedence": "

Operator precedence

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

\n

Try it

\n

Precedence And Associativity

\n
\n

Consider an expression describable by the representation below, where both OP1 and OP2 are fill-in-the-blanks for OPerators.

a OP1 b OP2 c\n

The combination above has two possible interpretations:

(a OP1 b) OP2 c\na OP1 (b OP2 c)\n

Which one the language decides to adopt depends on the identity of OP1 and OP2.

If OP1 and OP2 have different precedence levels (see the table below), the operator with the higher precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

\n

js

\n
console.log(3 + 10 * 2); // 23\nconsole.log(3 + (10 * 2)); // 23, because parentheses here are superfluous\nconsole.log((3 + 10) * 2); // 26, because the parentheses change the order\n
\n

Within operators of the same precedence, the language groups them by associativity. Left-associativity (left-to-right) means that it is interpreted as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

\n

js

\n
a = b = 5; // same as writing a = (b = 5);\n
\n

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5, a.k.a. right operand of the assignment.

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

\n

js

\n
const a = 4 ** 3 ** 2; // Same as 4 ** (3 ** 2); evaluates to 262144\nconst b = 4 / 3 / 2; // Same as (4 / 3) / 2; evaluates to 0.6666...\n
\n

Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

For prefix unary operators, suppose we have the following pattern:

OP1 a OP2 b\n

where OP1 is a prefix unary operator and OP2 is a binary operator. If OP1 has higher precedence than OP2, then it would be grouped as (OP1 a) OP2 b; otherwise, it would be OP1 (a OP2 b).

\n

js

\n
const a = 1;\nconst b = 2;\ntypeof a + b; // Equivalent to (typeof a) + b; result is \"number2\"\n
\n

If the unary operator is on the second operand:

a OP2 OP1 b\n

Then the binary operator OP2 must have lower precedence than the unary operator OP1 for it to be grouped as a OP2 (OP1 b). For example, the following is invalid:

\n

js

\n
function* foo() {\n  a + yield 1;\n}\n
\n

Because + has higher precedence than yield, this would become (a + yield) 1 — but because yield is a reserved word in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.

If we have two prefix unary operators:

OP1 OP2 a\n

Then the unary operator closer to the operand, OP2, must have higher precedence than OP1 for it to be grouped as OP1 (OP2 a). It's possible to get it the other way and end up with (OP1 OP2) a:

\n

js

\n
async function* foo() {\n  await yield 1;\n}\n
\n

Because await has higher precedence than yield, this would become (await yield) 1, which is awaiting an identifier called yield, and a syntax error. Similarly, if you have new !A;, because ! has lower precedence than new, this would become (new !) A, which is obviously invalid. (This code looks nonsensical to write anyway, since !A always produces a boolean, not a constructor function.)

For postfix unary operators (namely, ++ and --), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because ++ evaluates to a value, not a reference, you can't chain multiple increments together either, as you may do in C.

\n

js

\n
let a = 1;\na++++; // SyntaxError: Invalid left-hand side in postfix operation.\n
\n

Operator precedence will be handled recursively. For example, consider this expression:

\n

js

\n
1 + 2 ** 3 * 4 / 5 >> 6\n
\n

First, we group operators with different precedence by decreasing levels of precedence.

  1. The ** operator has the highest precedence, so it's grouped first.
  2. Looking around the ** expression, it has * on the right and + on the left. * has higher precedence, so it's grouped first. * and / have the same precedence, so we group them together for now.
  3. Looking around the *// expression grouped in 2, because + has higher precedence than >>, the former is grouped.
\n

js

\n
   (1 + ( (2 ** 3) * 4 / 5) ) >> 6\n// │    │ └─ 1. ─┘        │ │\n// │    └────── 2. ───────┘ │\n// └────────── 3. ──────────┘\n
\n

Within the *// group, because they are both left-associative, the left operand would be grouped.

\n

js

\n
   (1 + ( ( (2 ** 3) * 4 ) / 5) ) >> 6\n// │    │ │ └─ 1. ─┘     │    │ │\n// │    └─│─────── 2. ───│────┘ │\n// └──────│───── 3. ─────│──────┘\n//        └───── 4. ─────┘\n
\n

Note that operator precedence and associativity only affect the order of evaluation of operators (the implicit grouping), but not the order of evaluation of operands. The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.

\n

js

\n
function echo(name, num) {\n  console.log(`Evaluating the ${name} side`);\n  return num;\n}\n// Exponentiation operator (**) is right-associative,\n// but all call expressions (echo()), which have higher precedence,\n// will be evaluated before ** does\nconsole.log(echo(\"left\", 4) ** echo(\"middle\", 3) ** echo(\"right\", 2));\n// Evaluating the left side\n// Evaluating the middle side\n// Evaluating the right side\n// 262144\n\n// Exponentiation operator (**) has higher precedence than division (/),\n// but evaluation always starts with the left operand\nconsole.log(echo(\"left\", 4) / echo(\"middle\", 3) ** echo(\"right\", 2));\n// Evaluating the left side\n// Evaluating the middle side\n// Evaluating the right side\n// 0.4444444444444444\n
\n

If you are familiar with binary trees, think about it as a post-order traversal.

                /\n       ┌────────┴────────┐\necho(\"left\", 4)         **\n                ┌────────┴────────┐\n        echo(\"middle\", 3)  echo(\"right\", 2)\n

After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group — which is the operator with the lowest precedence (/ in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression echo(\"left\", 4)). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes — the echo() calls — would be visited left-to-right, regardless of the precedence of operators joining them.

\n

Short-circuiting

\n
\n

In the previous section, we said \"the higher-precedence expressions are always evaluated first\" — this is generally true, but it has to be amended with the acknowledgement of short-circuiting, in which case an operand may not be evaluated at all.

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is falsy, then the sub-expression (b + c) will not even get evaluated, even if it is grouped and therefore has higher precedence than &&. We could say that the logical AND operator (&&) is \"short-circuited\". Along with logical AND, other short-circuited operators include logical OR (||), nullish coalescing (??), and optional chaining (?.).

\n

js

\n
a || (b * c); // evaluate `a` first, then produce `a` if `a` is \"truthy\"\na && (b < c); // evaluate `a` first, then produce `a` if `a` is \"falsy\"\na ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`\na?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`\n
\n

When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.

Note: The behavior of short-circuiting is baked in these operators. Other operators would always evaluate both operands, regardless if that's actually useful — for example, NaN * foo() will always call foo, even when the result would never be something other than NaN.

The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of || is already truthy), the result is directly returned without visiting the right subtree.

Consider this case:

\n

js

\n
function A() { console.log('called A'); return false; }\nfunction B() { console.log('called B'); return false; }\nfunction C() { console.log('called C'); return true; }\n\nconsole.log(C() || B() && A());\n\n// Logs:\n// called C\n// true\n
\n

Only C() is evaluated, despite && having higher precedence. This does not mean that || has higher precedence in this case — it's exactly because (B() && A()) has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:

\n

js

\n
console.log(A() && C() || B());\n// Logs:\n// called A\n// called B\n// false\n
\n

Then the short-circuiting effect of && would only prevent C() from being evaluated, but because A() && C() as a whole is false, B() would still be evaluated.

However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of operands, not how operators are grouped — if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.

The assignment counterparts of these operators (&&=, ||=, ??=) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.

\n

Table

\n
\n

The following table lists operators in order from highest precedence (18) to lowest precedence (1).

Several notes about the table:

  1. Not all syntax included here are \"operators\" in the strict sense. For example, spread ... and arrow => are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
  2. The left operand of an exponentiation ** (precedence 13) cannot be one of the unary operators with precedence 14 without grouping, or there will be a SyntaxError. That means, although -1 ** 2 is technically unambiguous, the language requires you to use (-1) ** 2 instead.
  3. The operands of nullish coalescing ?? (precedence 3) cannot be a logical OR || (precedence 3) or logical AND && (precedence 4). That means you have to write (a ?? b) || c or a ?? (b || c), instead of a ?? b || c.
  4. Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access . (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow => (precedence 2) must be an arguments list or a single identifier instead of some random expression.
  5. Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation [ … ] (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is \"automatically grouped\". In this case we will omit the associativity.
Precedence Operator type Associativity Individual operators
18 Grouping n/a ( … )
17 Member Access left-to-right … . …
Optional chaining … ?. …
Computed Member Access n/a … [ … ]
\nnew (with argument list) new … ( … )
Function Call … ( … )
16 \nnew (without argument list) n/a new …
15 Postfix Increment n/a … ++
Postfix Decrement … --
14 Logical NOT (!) n/a ! …
Bitwise NOT (~) ~ …
Unary plus (+) + …
Unary negation (-) - …
Prefix Increment ++ …
Prefix Decrement -- …
typeof typeof …
void void …
delete delete …
await await …
13 Exponentiation (**) right-to-left … ** …
12 Multiplication (*) left-to-right … * …
Division (/) … / …
Remainder (%) … % …
11 Addition (+) left-to-right … + …
Subtraction (-) … - …
10 Bitwise Left Shift (<<) left-to-right … << …
Bitwise Right Shift (>>) … >> …
Bitwise Unsigned Right Shift (>>>) … >>> …
9 Less Than (<) left-to-right … < …
Less Than Or Equal (<=) … <= …
Greater Than (>) … > …
Greater Than Or Equal (>=) … >= …
in … in …
instanceof … instanceof …
8 Equality (==) left-to-right … == …
Inequality (!=) … != …
Strict Equality (===) … === …
Strict Inequality (!==) … !== …
7 Bitwise AND (&) left-to-right … & …
6 Bitwise XOR (^) left-to-right … ^ …
5 Bitwise OR (|) left-to-right … | …
4 Logical AND (&&) left-to-right … && …
3 Logical OR (||) left-to-right … || …
Nullish coalescing operator (??) … ?? …
2 Assignment right-to-left … = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
… &&= …
… ||= …
… ??= …
Conditional (ternary) operator right-to-left
(Groups on expressions after ?)
… ? … : …
Arrow (=>) right-to-left … => …
yield n/a yield …
yield* yield* …
Spread (...) ... …
1 Comma / Sequence left-to-right … , …
\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence\n

\n
\n", + "functions/arguments/callee": "

arguments.callee

\n

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: Accessing arguments.callee in strict mode will throw a TypeError. If a function must reference itself, either give the function expression a name or use a function declaration.

The arguments.callee data property contains the currently executing function that the arguments belong to.

\n
\n

Value

\n
\n

A reference to the currently executing function.

\n
Property attributes of arguments.callee\n
Writable yes
Enumerable no
Configurable yes

Note: callee is a data property only in non-strict functions with simple parameters (in which case the arguments object is also auto-syncing). Otherwise, it is an accessor property whose getter and setter both throw a TypeError.

\n

Description

\n
\n

callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called \"anonymous functions\").

(The text below is largely adapted from a Stack Overflow answer by olliej)

Early versions of JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expression.

For example, this syntax worked:

\n

js

\n
function factorial(n) {\n  return n <= 1 ? 1 : factorial(n - 1) * n;\n}\n\n[1, 2, 3, 4, 5].map(factorial);\n
\n

but:

\n

js

\n
[1, 2, 3, 4, 5].map(function (n) {\n  return n <= 1 ? 1 : /* what goes here? */ (n - 1) * n;\n});\n
\n

did not. To get around this arguments.callee was added so you could do

\n

js

\n
[1, 2, 3, 4, 5].map(function (n) {\n  return n <= 1 ? 1 : arguments.callee(n - 1) * n;\n});\n
\n

However, the design of arguments.callee has multiple issues. The first problem is that the recursive call will get a different this value. For example:

\n

js

\n
const global = this;\n\nconst sillyFunction = function (recursed) {\n  if (this !== global) {\n    console.log(\"This is:\", this);\n  } else {\n    console.log(\"This is the global\");\n  }\n\n  if (!recursed) {\n    return arguments.callee(true);\n  }\n};\n\nsillyFunction();\n// This is the global\n// This is: [object Arguments]\n
\n

In addition, references to arguments.callee make inlining and tail recursion impossible in the general case. (You can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.)

ECMAScript 3 resolved these issues by allowing named function expressions. For example:

\n

js

\n
[1, 2, 3, 4, 5].map(function factorial(n) {\n  return n <= 1 ? 1 : factorial(n - 1) * n;\n});\n
\n

This has numerous benefits:

Strict mode has banned other properties that leak stack information, like the caller property of functions. This is because looking at the call stack has one single major effect: it makes a large number of optimizations impossible, or much more difficult. For example, if you cannot guarantee that a function f will not call an unknown function, it is not possible to inline f.

\n

js

\n
function f(a, b, c, d, e) {\n  return a ? b * c : d * e;\n}\n
\n

If the JavaScript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. This means any call site that may have been trivially inlinable accumulates a large number of guards. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.

\n

Examples

\n

Using arguments.callee in an anonymous recursive function

\n
\n

A recursive function must be able to refer to itself. Typically, a function refers to itself by its name. However, an anonymous function (which can be created by a function expression or the Function constructor) does not have a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by arguments.callee.

The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions.

\n

js

\n
function create() {\n  return function (n) {\n    if (n <= 1) {\n      return 1;\n    }\n    return n * arguments.callee(n - 1);\n  };\n}\n\nconst result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)\n
\n
\n

Recursion of anonymous functions with a Y-combinator

\n
\n

Although function expressions can now be named, arrow functions always remain anonymous, which means they cannot reference themselves without being assigned to a variable first. Fortunately, in Lambda calculus there's a very good solution which allows a function to both be anonymous and self-referential. The technique is called a Y-combinator. Here we will not explain how it works, only that it works.

\n

js

\n
// The Y-combinator: a utility function!\nconst Y = (hof) => ((x) => x(x))((x) => hof((y) => x(x)(y)));\n\nconsole.log(\n  [1, 2, 3, 4, 5].map(\n    // Wrap the higher-order function in the Y-combinator\n    // \"factorial\" is not a function's name: it's introduced as a parameter\n    Y((factorial) => (n) => (n <= 1 ? 1 : factorial(n - 1) * n)),\n  ),\n);\n// [ 1, 2, 6, 24, 120 ]\n
\n

Note: This method allocates a new closure for every iteration, which may significantly increase memory usage. It's only here to demonstrate the possibility, but should be avoided in production. Use a temporary variable or a named function expression instead.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arguments-exotic-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
callee11216414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee\n

\n
\n", + "operators/import.meta/resolve": "

import.meta.resolve()

import.meta.resolve() is a built-in function defined on the import.meta object of a JavaScript module that resolves a module specifier to a URL using the current module's URL as base.

\n

Syntax

\n
\n

js

\n
import.meta.resolve(moduleName)\n
\n

Parameters

\n
moduleName

A string that specifies a potentially importable module. This may be a relative path (such as \"./lib/helper.js\"), a bare name (such as \"my-module\"), or an absolute URL (such as \"https://example.com/lib/helper.js\").

Return value

\n

Returns a string corresponding to the path that would be imported if the argument were passed to import().

Description

\n
\n

import.meta.resolve() allows a script to access the module specifier resolution algorithm for a name, like this:

\n

js

\n
// Script at https://example.com/main.js\n\nconst helperPath = import.meta.resolve(\"./lib/helper.js\");\nconsole.log(helperPath); // \"https://example.com/lib/helper.js\"\n
\n

Note that import.meta.resolve() only performs resolution and does not attempt to load or import the resulting path. (The explainer for the specification describes the reasoning for this behavior.) Therefore, its return value is the same regardless of whether the returned path corresponds to a file that exists, and regardless of whether that file contains valid code for a module.

It is different from dynamic import, because although both accept a module specifier as the first argument, import.meta.resolve() returns the path that would be imported without making any attempt to access that path. Therefore, the following two are effectively the same code:

\n

js

\n
// Approach 1\nconsole.log(await import(\"./lib/helper.js\"));\n\n// Approach 2\nconst helperPath = import.meta.resolve(\"./lib/helper.js\");\nconsole.log(await import(helperPath));\n
\n

However, even if \"./lib/helper.js\" cannot be successfully imported, the second snippet will not encounter an error until it attempts to perform the import on line 2.

\n

Bare module names

\n
\n

You can pass a bare module name (also known as a bare module specifier) to import.meta.resolve(), as long as module resolution is defined for the name. For example, you can define this using an import map inside a browser:

\n

html

\n
<!-- index.html -->\n<script type=\"importmap\">\n  {\n    \"imports\": {\n      \"my-module\": \"./modules/my-module/index.js\"\n    }\n  }\n</script>\n\n<script type=\"module\">\n  const moduleEntryPath = import.meta.resolve(\"my-module\");\n  console.log(moduleEntryPath);\n</script>\n
\n

Again, since this snippet does not try to import moduleEntryPath — neither does the import map — it prints the resolved URL regardless of whether ./modules/my-module/index.js actually exists.

\n

Comparison with new URL()

\n
\n

The URL() constructor accepts a second base URL argument. When the first argument is a relative path and the base URL is import.meta.url, the effect is similar to import.meta.resolve().

\n

js

\n
const helperPath = new URL(\"./lib/helper.js\", import.meta.url).href;\nconsole.log(helperPath);\n
\n

This is also a useful replacement syntax when targeting older browsers. However, there are some differences:

Some tools recognize new URL(\"./lib/helper.js\", import.meta.url).href as a dependency on \"./lib/helper.js\" (similar to an import), and take this into account for features like bundling, rewriting imports for moved files, \"go to source\" functionality, etc. However, since import.meta.resolve() is less ambiguous and specifically designed to indicate a module path resolution dependency, you should use import.meta.resolve(moduleName) instead of new URL(moduleName, import.meta.url) for these use cases wherever possible.

\n

Not an ECMAScript feature

\n
\n

import.meta.resolve() is not specified or documented as part of the ECMAScript specification for JavaScript modules. Instead, the specification defines the import.meta object but leaves all its properties as \"host-defined\". The WHATWG HTML standard picks up where the ECMAScript standard leaves off, and defines import.meta.resolve using its module specifier resolution.

This means that import.meta.resolve() is not required to be implemented by all conformant JavaScript implementations. However, import.meta.resolve() may also be available in non-browser environments:

\n

Examples

\n

Resolve a path for the Worker() constructor

\n
\n

import.meta.resolve() is particularly valuable for APIs that take a path to a script file as an argument, such as the Worker() constructor:

\n

js

\n
// main.js\nconst workerPath = import.meta.resolve(\"./worker.js\");\nconst worker = new Worker(workerPath, { type: \"module\" });\nworker.addEventListener(\"message\", console.log);\n
\n
\n

js

\n
// worker.js\nself.postMessage(\"hello!\");\n
\n

This is also useful to calculate paths for other workers, such as service workers and shared workers. However, if you are using a relative path to calculate the URL of a service worker, keep in mind that the directory of the resolved path determines its registration scope by default (although a different scope can be specified during registration).

\n

Specifications

\n
\n\n\n
Specification
HTML Standard
# hostgetimportmetaproperties
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
resolve105105106No9116.41051051067216.420.01.24
20.6.0Returns a URL object instead of a string.
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve\n

\n
\n", + "errors/unparenthesized_unary_expr_lhs_exponentiation": "

SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'

The JavaScript exception \"unparenthesized unary expression can't appear on the left-hand side of '**'\" occurs when a unary operator (one of typeof, void, delete, await, !, ~, +, -) is used on the left operand of the exponentiation operator without parentheses.

\n

Message

\n
SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence (V8-based)\nSyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' (Firefox)\nSyntaxError: Unexpected token '**'. Ambiguous unary expression in the left hand side of the exponentiation expression; parentheses must be used to disambiguate the expression. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

You likely wrote something like this:

\n

js

\n
-a ** b\n
\n

Whether it should be evaluated as (-a) ** b or -(a ** b) is ambiguous. In mathematics, -x2 means -(x ** 2) — and that's how many languages, including Python, Haskell, and PHP, handle it. But making the unary minus operator take precedence over ** breaks symmetry with a ** -b, which is unambiguously a ** (-b). Therefore, the language forbids this syntax and requires you to parenthesize either side to resolve the ambiguity.

\n

js

\n
(-a) ** b\n-(a ** b)\n
\n

Other unary operators cannot be the left-hand side of exponentiation either.

\n

js

\n
await a ** b\n!a ** b\n+a ** b\n~a ** b\n
\n
\n

Examples

\n
\n

When writing complex math expressions involving exponentiation, you may write something like this:

\n

js

\n
function taylorSin(x) {\n  return (n) => (-1 ** n * x ** (2 * n + 1)) / factorial(2 * n + 1);\n  // SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'\n}\n
\n

However, the -1 ** n part is illegal in JavaScript. Instead, parenthesize the left operand:

\n

js

\n
function taylorSin(x) {\n  return (n) => ((-1) ** n * x ** (2 * n + 1)) / factorial(2 * n + 1);\n}\n
\n

This also makes the code's intent much clearer to other readers.

\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unparenthesized_unary_expr_lhs_exponentiation\n

\n
\n", + "errors/invalid_bigint_syntax": "

SyntaxError: invalid BigInt syntax

The JavaScript exception \"invalid BigInt syntax\" occurs when a string value is being coerced to a BigInt but it failed to be parsed as an integer.

\n

Message

\n
SyntaxError: Cannot convert x to a BigInt (V8-based)\nSyntaxError: invalid BigInt syntax (Firefox)\nSyntaxError: Failed to parse String to BigInt (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

When using the BigInt() function to convert a string to a BigInt, the string will be parsed in the same way as source code, and the resulting value must be an integer value.

Examples

\n

Invalid cases

\n
\n

js

\n
const a = BigInt(\"1.5\");\nconst b = BigInt(\"1n\");\nconst c = BigInt.asIntN(4, \"8n\");\n// SyntaxError: invalid BigInt syntax\n
\n

Valid cases

\n
\n

js

\n
const a = BigInt(\"1\");\nconst b = BigInt(\"  1   \");\nconst c = BigInt.asIntN(4, \"8\");\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_BigInt_syntax\n

\n
\n", + "errors/cant_use_nullish_coalescing_unparenthesized": "

SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions

The JavaScript exception \"cannot use ?? unparenthesized within || and && expressions\" occurs when an nullish coalescing operator is used with a logical OR or logical AND in the same expression without parentheses.

\n

Message

\n
SyntaxError: Unexpected token '??' (V8-based)\nSyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions (Firefox)\nSyntaxError: Unexpected token '??'. Coalescing and logical operators used together in the same expression; parentheses must be used to disambiguate. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

The operator precedence chain looks like this:

|   >   &&   >   ||   >   =\n|   >   ??   >   =\n

However, the precedence between ?? and &&/|| is intentionally undefined, because the short circuiting behavior of logical operators can make the expression's evaluation counter-intuitive. Therefore, the following combinations are all syntax errors, because the language doesn't know how to parenthesize the operands:

\n

js

\n
a ?? b || c;\na || b ?? c;\na ?? b && c;\na && b ?? c;\n
\n

Instead, make your intent clear by parenthesizing either side explicitly:

\n

js

\n
(a ?? b) || c;\na ?? (b && c);\n
\n
\n

Examples

\n
\n

When migrating legacy code that uses || and && for guarding against null or undefined, you may often convert it partially:

\n

js

\n
function getId(user, fallback) {\n  // Previously: user && user.id || fallback\n  return user && user.id ?? fallback; // SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions\n}\n
\n

Instead, consider parenthesizing the &&:

\n

js

\n
function getId(user, fallback) {\n  return (user && user.id) ?? fallback;\n}\n
\n

Even better, consider using optional chaining instead of &&:

\n

js

\n
function getId(user, fallback) {\n  return user?.id ?? fallback;\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_use_nullish_coalescing_unparenthesized\n

\n
\n", + "functions/arguments/length": "

arguments.length

The arguments.length data property contains the number of arguments passed to the function.

\n

Value

\n
\n

A non-negative integer.

\n
Property attributes of arguments.length\n
Writable yes
Enumerable no
Configurable yes
\n

Description

\n
\n

The arguments.length property provides the number of arguments actually passed to a function. This can be more or less than the defined parameter's count (see Function.prototype.length). For example, for the function below:

\n

js

\n
function func1(a, b, c) {\n  console.log(arguments.length);\n}\n
\n

func1.length returns 3, because func1 declares three formal parameters. However, func1(1, 2, 3, 4, 5) logs 5, because func1 was called with five arguments. Similarly, func1(1) logs 1, because func1 was called with one argument.

\n

Examples

\n

Using arguments.length

\n
\n

In this example, we define a function that can add two or more numbers together.

\n

js

\n
function adder(base /*, num1, …, numN */) {\n  base = Number(base);\n  for (let i = 1; i < arguments.length; i++) {\n    base += Number(arguments[i]);\n  }\n  return base;\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-arguments-exotic-objects
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
length11214414.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length\n

\n
\n", + "errors/strict_non_simple_params": "

SyntaxError: \"use strict\" not allowed in function with non-simple parameters

The JavaScript exception \"\"use strict\" not allowed in function\" occurs when a \"use strict\" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters.

\n

Message

\n
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based)\nSyntaxError: \"use strict\" not allowed in function with default parameter (Firefox)\nSyntaxError: \"use strict\" not allowed in function with rest parameter (Firefox)\nSyntaxError: \"use strict\" not allowed in function with destructuring parameter (Firefox)\nSyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n
\n

A \"use strict\" directive is written at the top of a function that has one of the following parameters:

A \"use strict\" directive is not allowed at the top of such functions per the ECMAScript specification.

\n

Examples

\n

Function statement

\n
\n

In this case, the function sum has default parameters a=1 and b=2:

\n

js

\n
function sum(a = 1, b = 2) {\n  // SyntaxError: \"use strict\" not allowed in function with default parameter\n  \"use strict\";\n  return a + b;\n}\n
\n

If the function should be in strict mode, and the entire script or enclosing function is also okay to be in strict mode, you can move the \"use strict\" directive outside of the function:

\n

js

\n
\"use strict\";\nfunction sum(a = 1, b = 2) {\n  return a + b;\n}\n
\n
\n

Function expression

\n
\n

A function expression can use yet another workaround:

\n

js

\n
const sum = function sum([a, b]) {\n  // SyntaxError: \"use strict\" not allowed in function with destructuring parameter\n  \"use strict\";\n  return a + b;\n};\n
\n

This can be converted to the following expression:

\n

js

\n
const sum = (function () {\n  \"use strict\";\n  return function sum([a, b]) {\n    return a + b;\n  };\n})();\n
\n
\n

Arrow function

\n
\n

If an arrow function needs to access the this variable, you can use the arrow function as the enclosing function:

\n

js

\n
const callback = (...args) => {\n  // SyntaxError: \"use strict\" not allowed in function with rest parameter\n  \"use strict\";\n  return this.run(args);\n};\n
\n

This can be converted to the following expression:

\n

js

\n
const callback = (() => {\n  \"use strict\";\n  return (...args) => {\n    return this.run(args);\n  };\n})();\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Strict_non_simple_params\n

\n
\n", + "errors/property_access_denied": "

Error: Permission denied to access property \"x\"

The JavaScript exception \"Permission denied to access property\" occurs when there was an attempt to access an object for which you have no permission.

\n

Message

\n
DOMException: Blocked a frame with origin \"x\" from accessing a cross-origin frame. (Chromium-based)\nDOMException: Permission denied to access property \"x\" on cross-origin object (Firefox)\nSecurityError: Blocked a frame with origin \"x\" from accessing a cross-origin frame. Protocols, domains, and ports must match. (Safari)\n

Error type

\n

DOMException.

What went wrong?

\n

There was attempt to access an object for which you have no permission. This is likely an <iframe> element loaded from a different domain for which you violated the same-origin policy.

Examples

\n

No permission to access document

\n
\n

html

\n
<!doctype html>\n<html lang=\"en-US\">\n  <head>\n    <iframe\n      id=\"myframe\"\n      src=\"http://www1.w3c-test.org/common/blank.html\"></iframe>\n    <script>\n      onload = function () {\n        console.log(frames[0].document);\n        // Error: Permission denied to access property \"document\"\n      };\n    </script>\n  </head>\n  <body></body>\n</html>\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Property_access_denied\n

\n
\n", + "errors/bigint_negative_exponent": "

RangeError: BigInt negative exponent

The JavaScript exception \"BigInt negative exponent\" occurs when a BigInt is raised to the power of a negative BigInt value.

\n

Message

\n
RangeError: Exponent must be positive (V8-based)\nRangeError: BigInt negative exponent (Firefox)\nRangeError: Negative exponent is not allowed (Safari)\n

Error type

\n

RangeError.

What went wrong?

\n

The exponent of an exponentiation operation must be positive. Since negative exponents would take the reciprocal of the base, the result will be between -1 and 1 in almost all cases, which gets rounded to 0n. To catch mistakes, negative exponents are not allowed. Check if the exponent is non-negative before doing exponentiation.

Examples

\n

Using a negative BigInt as exponent

\n
\n
\n

js

\n
const a = 1n;\nconst b = -1n;\nconst c = a ** b;\n// RangeError: BigInt negative exponent\n
\n

Instead, check if the exponent is negative first, and either issue an error with a better message, or fallback to a different value, like 0n or undefined.

\n

js

\n
const a = 1n;\nconst b = -1n;\nconst quotient = b >= 0n ? a ** b : 0n;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/BigInt_negative_exponent\n

\n
\n", + "errors/resulting_string_too_large": "

RangeError: repeat count must be less than infinity

The JavaScript exception \"repeat count must be less than infinity\" occurs when the String.prototype.repeat() method is used with a count argument that is infinity.

\n

Message

\n
RangeError: Invalid string length (V8-based)\nRangeError: Invalid count value: Infinity (V8-based)\nRangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)\nRangeError: Out of memory (Safari)\nRangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)\n

Error type

\n
RangeError

What went wrong?

\n
\n

The String.prototype.repeat() method has been used. It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +∞).

The resulting string can also not be larger than the maximum string size, which can differ in JavaScript engines. In Firefox (SpiderMonkey) the maximum string size is 230 - 2 (~2GiB).

\n

Examples

\n

Invalid cases

\n
\n

js

\n
\"abc\".repeat(Infinity); // RangeError\n\"a\".repeat(2 ** 30); // RangeError\n
\n

Valid cases

\n
\n

js

\n
\"abc\".repeat(0); // ''\n\"abc\".repeat(1); // 'abc'\n\"abc\".repeat(2); // 'abcabc'\n\"abc\".repeat(3.5); // 'abcabcabc' (count will be converted to integer)\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Resulting_string_too_large\n

\n
\n", + "errors/bigint_division_by_zero": "

RangeError: BigInt division by zero

The JavaScript exception \"BigInt division by zero\" occurs when a BigInt is divided by 0n.

\n

Message

\n
RangeError: Division by zero (V8-based)\nRangeError: BigInt division by zero (Firefox)\nRangeError: 0 is an invalid divisor value. (Safari)\n

Error type

\n

RangeError.

What went wrong?

\n

The divisor of a division or remainder operator is 0n. In Number arithmetic, this produces Infinity, but there's no \"infinity value\" in BigInts, so an error is issued. Check if the divisor is 0n before doing the division.

Examples

\n

Division by 0n

\n
\n
\n

js

\n
const a = 1n;\nconst b = 0n;\nconst quotient = a / b;\n// RangeError: BigInt division by zero\n
\n

Instead, check if the divisor is 0n first, and either issue an error with a better message, or fallback to a different value, like Infinity or undefined.

\n

js

\n
const a = 1n;\nconst b = 0n;\nconst quotient = b === 0n ? undefined : a / b;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/BigInt_division_by_zero\n

\n
\n", + "errors/not_a_valid_code_point": "

RangeError: argument is not a valid code point

The JavaScript exception \"Invalid code point\" occurs when NaN values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111) are used with String.fromCodePoint().

\n

Message

\n
RangeError: Invalid code point -1 (V8-based)\nRangeError: -1 is not a valid code point (Firefox)\nRangeError: Arguments contain a value that is out of range of code points (Safari)\n

Error type

\n
RangeError

What went wrong?

\n
\n

String.fromCodePoint() throws this error when passed NaN values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).

A code point is a value in the Unicode codespace; that is, the range of integers from 0 to 0x10FFFF.

\n

Examples

\n

Invalid cases

\n
\n

js

\n
String.fromCodePoint(\"_\"); // RangeError\nString.fromCodePoint(Infinity); // RangeError\nString.fromCodePoint(-1); // RangeError\nString.fromCodePoint(3.14); // RangeError\nString.fromCodePoint(3e-2); // RangeError\nString.fromCodePoint(NaN); // RangeError\n
\n

Valid cases

\n
\n

js

\n
String.fromCodePoint(42); // \"*\"\nString.fromCodePoint(65, 90); // \"AZ\"\nString.fromCodePoint(0x404); // 'Є' (U+0404)\nString.fromCodePoint(0x2f804); // '你' (U+2F804)\nString.fromCodePoint(194564); // '你'\nString.fromCodePoint(0x1d306, 0x61, 0x1d307); // '𝌆a𝌇'\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_valid_code_point\n

\n
\n", + "errors/invalid_date": "

RangeError: invalid date

The JavaScript exception \"invalid date\" occurs when a string leading to an invalid date has been provided to Date or Date.parse().

\n

Message

\n
RangeError: Invalid time value (V8-based)\nRangeError: invalid date (Firefox)\nRangeError: Invalid Date (Safari)\n

Error type

\n
RangeError

What went wrong?

\n

A string leading to an invalid date has been provided to Date or Date.parse().

Examples

\n

Invalid cases

\n
\n

Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return NaN. However, depending on the implementation, non–conforming ISO format strings, may also throw RangeError: invalid date, like the following cases in Firefox:

\n

js

\n
new Date(\"foo-bar 2014\");\nnew Date(\"2014-25-23\").toISOString();\nnew Date(\"foo-bar 2014\").toString();\n
\n

This, however, returns NaN in Firefox:

\n

js

\n
Date.parse(\"foo-bar 2014\"); // NaN\n
\n

For more details, see the Date.parse() documentation.

\n

Valid cases

\n
\n

js

\n
new Date(\"05 October 2011 14:48 UTC\");\nnew Date(1317826080); // Unix Timestamp for 05 October 2011 14:48:00 UTC\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_date\n

\n
\n", + "errors/precision_range": "

RangeError: precision is out of range

The JavaScript exception \"precision is out of range\" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision.

\n

Message

\n
RangeError: toExponential() argument must be between 0 and 100 (V8-based & Safari)\nRangeError: toFixed() digits argument must be between 0 and 100 (V8-based & Safari)\nRangeError: toPrecision() argument must be between 1 and 100 (V8-based & Safari)\nRangeError: precision -1 out of range (Firefox)\n

Error type

\n
RangeError

What went wrong?

\n
\n

There was an out of range precision argument in one of these methods:

\n

Examples

\n

Invalid cases

\n
\n

js

\n
(77.1234).toExponential(-1); // RangeError\n(77.1234).toExponential(101); // RangeError\n\n(2.34).toFixed(-100); // RangeError\n(2.34).toFixed(1001); // RangeError\n\n(1234.5).toPrecision(-1); // RangeError\n(1234.5).toPrecision(101); // RangeError\n
\n

Valid cases

\n
\n

js

\n
(77.1234).toExponential(4); // 7.7123e+1\n(77.1234).toExponential(2); // 7.71e+1\n\n(2.34).toFixed(1); // 2.3\n(2.35).toFixed(1); // 2.4 (note that it rounds up in this case)\n\n(5.123456).toPrecision(5); // 5.1235\n(5.123456).toPrecision(2); // 5.1\n(5.123456).toPrecision(1); // 5\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Precision_range\n

\n
\n", + "errors/bad_radix": "

RangeError: radix must be an integer

The JavaScript exception \"radix must be an integer at least 2 and no greater than 36\" occurs when the optional radix parameter of the Number.prototype.toString() or the BigInt.prototype.toString() method was specified and is not between 2 and 36.

\n

Message

\n
RangeError: toString() radix argument must be between 2 and 36 (V8-based & Safari)\nRangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)\n

Error type

\n
RangeError

What went wrong?

\n
\n

The optional radix parameter of the Number.prototype.toString() or the BigInt.prototype.toString() method was specified. Its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. For example, the decimal (base 10) number 169 is represented in hexadecimal (base 16) as A9.

Why is this parameter's value limited to 36? A radix that is larger than 10 uses alphabetical characters as digits; therefore, the radix can't be larger than 36, since the Latin alphabet (used by English and many other languages) only has 26 characters.

The most common radixes:

\n

Examples

\n

Invalid cases

\n
\n

js

\n
(42).toString(0);\n(42).toString(1);\n(42).toString(37);\n(42).toString(150);\n// You cannot use a string like this for formatting:\n(12071989).toString(\"MM-dd-yyyy\");\n
\n

Valid cases

\n
\n

js

\n
(42).toString(2); // \"101010\" (binary)\n(13).toString(8); // \"15\" (octal)\n(0x42).toString(10); // \"66\" (decimal)\n(100000).toString(16); // \"186a0\" (hexadecimal)\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_radix\n

\n
\n", + "errors/negative_repetition_count": "

RangeError: repeat count must be non-negative

The JavaScript exception \"repeat count must be non-negative\" occurs when the String.prototype.repeat() method is used with a count argument that is a negative number.

\n

Message

\n
RangeError: Invalid count value: -1 (V8-based)\nRangeError: repeat count must be non-negative (Firefox)\nRangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)\n

Error type

\n
RangeError

What went wrong?

\n

The String.prototype.repeat() method has been used. It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +∞).

Examples

\n

Invalid cases

\n
\n

js

\n
\"abc\".repeat(-1); // RangeError\n
\n

Valid cases

\n
\n

js

\n
\"abc\".repeat(0); // ''\n\"abc\".repeat(1); // 'abc'\n\"abc\".repeat(2); // 'abcabc'\n\"abc\".repeat(3.5); // 'abcabcabc' (count will be converted to integer)\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Negative_repetition_count\n

\n
\n", + "errors/cant_be_converted_to_bigint_because_it_isnt_an_integer": "

RangeError: x can't be converted to BigInt because it isn't an integer

The JavaScript exception \"x can't be converted to BigInt because it isn't an integer\" occurs when the BigInt() function is used on a number that isn't an integer.

\n

Message

\n
RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer (V8-based & Firefox)\nRangeError: Not an integer (Safari)\n

Error type

\n

RangeError.

What went wrong?

\n

When using the BigInt() function to convert a number to a BigInt, the number must be an integer (such that Number.isInteger returns true).

Examples

\n

Invalid cases

\n
\n

js

\n
const a = BigInt(1.5);\n// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer\nconst b = BigInt(NaN);\n// RangeError: NaN cannot be converted to a BigInt because it is not an integer\n
\n

Valid cases

\n
\n

js

\n
const a = BigInt(1);\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_be_converted_to_BigInt_because_it_isnt_an_integer\n

\n
\n", + "errors/not_defined": "

ReferenceError: \"x\" is not defined

The JavaScript exception \"variable is not defined\" occurs when there is a non-existent variable referenced somewhere.

\n

Message

\n
ReferenceError: \"x\" is not defined (V8-based & Firefox)\nReferenceError: Can't find variable: x (Safari)\n

Error type

\n

ReferenceError.

What went wrong?

\n
\n

There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.

Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as \"$\". Put the <script> element that loads the library before your code that uses it.

\n

Examples

\n

Variable not declared

\n
\n
\n

js

\n
foo.substring(1); // ReferenceError: foo is not defined\n
\n

The \"foo\" variable isn't defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.

\n

js

\n
const foo = \"bar\";\nfoo.substring(1); // \"ar\"\n
\n
\n

Wrong scope

\n
\n

A variable needs to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function

\n

js

\n
function numbers() {\n  const num1 = 2;\n  const num2 = 3;\n  return num1 + num2;\n}\n\nconsole.log(num1); // ReferenceError num1 is not defined.\n
\n

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.

\n

js

\n
const num1 = 2;\nconst num2 = 3;\n\nfunction numbers() {\n  return num1 + num2;\n}\n\nconsole.log(numbers()); // 5\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined\n

\n
\n", + "errors/undeclared_var": "

ReferenceError: assignment to undeclared variable \"x\"

The JavaScript strict mode-only exception \"Assignment to undeclared variable\" occurs when the value has been assigned to an undeclared variable.

\n

Message

\n
ReferenceError: x is not defined (V8-based)\nReferenceError: assignment to undeclared variable x (Firefox)\nReferenceError: Can't find variable: x (Safari)\n

Error type

\n

ReferenceError in strict mode only.

What went wrong?

\n
\n

A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

For more details and examples, see the var reference page.

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

\n

Examples

\n

Invalid cases

\n
\n

In this case, the variable \"bar\" is an undeclared variable.

\n

js

\n
function foo() {\n  \"use strict\";\n  bar = true;\n}\nfoo(); // ReferenceError: assignment to undeclared variable bar\n
\n
\n

Valid cases

\n
\n

To make \"bar\" a declared variable, you can add a let, const, or var keyword in front of it.

\n

js

\n
function foo() {\n  \"use strict\";\n  const bar = true;\n}\nfoo();\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Undeclared_var\n

\n
\n", + "errors/cant_access_lexical_declaration_before_init": "

ReferenceError: can't access lexical declaration 'X' before initialization

The JavaScript exception \"can't access lexical declaration `variable' before initialization\" occurs when a lexical variable was accessed before it was initialized. This happens within any block statement, when let or const variables are accessed before the place where they are declared is executed.

\n

Message

\n
ReferenceError: Cannot access 'X' before initialization (V8-based)\nReferenceError: can't access lexical declaration 'X' before initialization (Firefox)\nReferenceError: Cannot access uninitialized variable. (Safari)\n

Error type

\n
ReferenceError

What went wrong?

\n
\n

A lexical variable was accessed before it was initialized. This happens within any block statement, when variables declared with let or const are accessed before the place where they are declared has been executed.

Note that it is the execution order of access and variable declaration that matters, not the order in which the statements appear in the code. For more information, see the description of Temporal Dead Zone.

This issue does not occur for variables declared using var, because they are initialized with a default value of undefined when they are hoisted.

This error can also occur in cyclic imports when a module uses a variable that depends on the module itself being evaluated.

\n

Examples

\n

Invalid cases

\n
\n

In this case, the variable foo is accessed before it is declared. At this point foo has not been initialized with a value, so accessing the variable throws a reference error.

\n

js

\n
function test() {\n  // Accessing the 'const' variable foo before it's declared\n  console.log(foo); // ReferenceError: foo is not initialized\n  const foo = 33; // 'foo' is declared and initialized here using the 'const' keyword\n}\n\ntest();\n
\n

In this example, the imported variable a is accessed but is uninitialized, because the evaluation of a.js is blocked by the evaluation of the current module b.js.

\n

js

\n
// -- a.js (entry module) --\nimport { b } from \"./b.js\";\n\nexport const a = 2;\n\n// -- b.js --\nimport { a } from \"./a.js\";\n\nconsole.log(a); // ReferenceError: Cannot access 'a' before initialization\nexport const b = 1;\n
\n
\n

Valid cases

\n
\n

In the following example, we correctly declare a variable using the const keyword before accessing it.

\n

js

\n
function test() {\n  // Declaring variable foo\n  const foo = 33;\n  console.log(foo); // 33\n}\ntest();\n
\n

In this example, the imported variable a is asynchronously accessed, so both modules are evaluated before the access to a occurs.

\n

js

\n
// -- a.js (entry module) --\nimport { b } from \"./b.js\";\n\nexport const a = 2;\n\n// -- b.js --\nimport { a } from \"./a.js\";\n\nsetTimeout(() => {\n  console.log(a); // 2\n}, 10);\nexport const b = 1;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init\n

\n
\n", + "errors/deprecated_caller_or_arguments_usage": "

ReferenceError: deprecated caller or arguments usage

The JavaScript strict mode-only exception \"deprecated caller or arguments usage\" occurs when the deprecated Function.prototype.caller or Function.prototype.arguments properties are used.

\n

Message

\n
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them (V8-based & Firefox)\nTypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context. (Safari)\n

Error type

\n

TypeError in strict mode only.

What went wrong?

\n

In strict mode, the Function.prototype.caller or Function.prototype.arguments properties are used and shouldn't be. They are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature.

Examples

\n

Deprecated function.caller or arguments.callee

\n
\n

Function.prototype.caller and arguments.callee are deprecated (see the reference articles for more information).

\n

js

\n
\"use strict\";\n\nfunction myFunc() {\n  if (myFunc.caller === null) {\n    return \"The function was called from the top!\";\n  } else {\n    return `This function's caller was ${myFunc.caller}`;\n  }\n}\n\nmyFunc();\n// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them\n
\n
\n

Function.prototype.arguments

\n
\n

Function.prototype.arguments is deprecated (see the reference article for more information).

\n

js

\n
\"use strict\";\n\nfunction f(n) {\n  g(n - 1);\n}\n\nfunction g(n) {\n  console.log(`before: ${g.arguments[0]}`);\n  if (n > 0) {\n    f(n);\n  }\n  console.log(`after: ${g.arguments[0]}`);\n}\n\nf(2);\n\nconsole.log(`returned: ${g.arguments}`);\n// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage\n

\n
\n", + "errors/undefined_prop": "

ReferenceError: reference to undefined property \"x\"

The JavaScript warning \"reference to undefined property\" occurs when a script attempted to access an object property which doesn't exist.

\n

Message

\n
ReferenceError: reference to undefined property \"x\" (Firefox)\n

Error type

\n

(Firefox only) ReferenceError warning which is reported only if javascript.options.strict preference is set to true.

What went wrong?

\n

The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them.

Examples

\n

Invalid cases

\n
\n

In this case, the property bar is an undefined property, so a ReferenceError will occur.

\n

js

\n
const foo = {};\nfoo.bar; // ReferenceError: reference to undefined property \"bar\"\n
\n
\n

Valid cases

\n
\n

To avoid the error, you need to either add a definition for bar to the object or check for the existence of the bar property before trying to access it; ways to do that include using the in operator, or the Object.hasOwn() method, like this:

\n

js

\n
const foo = {};\n\n// Define the bar property\n\nfoo.bar = \"moon\";\nconsole.log(foo.bar); // \"moon\"\n\n// Test to be sure bar exists before accessing it\n\nif (Object.hasOwn(foo, \"bar\")) {\n  console.log(foo.bar);\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Undefined_prop\n

\n
\n", + "errors/deprecated_octal": "

SyntaxError: \"0\"-prefixed octal literals and octal escape seq. are deprecated

The JavaScript strict mode-only exception \"0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead\" occurs when deprecated octal literals and octal escape sequences are used.

\n

Message

\n
SyntaxError: Octal literals are not allowed in strict mode. (V8-based)\nSyntaxError: \"0\"-prefixed octal literals are deprecated; use the \"0o\" prefix instead (Firefox)\nSyntaxError: Decimal integer literals with a leading zero are forbidden in strict mode (Safari)\n\nSyntaxError: Octal escape sequences are not allowed in strict mode. (V8-based)\nSyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code (Firefox)\nSyntaxError: The only valid numeric escape in strict mode is '\\0' (Safari)\n

Error type

\n

SyntaxError in strict mode only.

What went wrong?

\n

Octal literals and octal escape sequences are deprecated and will throw a SyntaxError in strict mode. The standardized syntax uses a leading zero followed by a lowercase or uppercase Latin letter \"O\" (0o or 0O).

Examples

\n

\"0\"-prefixed octal literals

\n
\n

js

\n
\"use strict\";\n\n03;\n\n// SyntaxError: \"0\"-prefixed octal literals are deprecated; use the \"0o\" prefix instead\n
\n

Octal escape sequences

\n
\n

js

\n
\"use strict\";\n\n\"\\251\";\n\n// SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code\n
\n

Valid octal numbers

\n
\n

Use a leading zero followed by the letter \"o\" or \"O\":

\n

js

\n
0o3;\n
\n

For octal escape sequences, you can use hexadecimal escape sequences instead:

\n

js

\n
\"\\xA9\";\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal\n

\n
\n", + "errors/reserved_identifier": "

SyntaxError: \"x\" is a reserved identifier

The JavaScript exception \"variable is a reserved identifier\" occurs when reserved keywords are used as identifiers.

\n

Message

\n
SyntaxError: Unexpected reserved word (V8-based)\nSyntaxError: implements is a reserved identifier (Firefox)\nSyntaxError: Cannot use the reserved word 'implements' as a variable name. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

Reserved keywords will throw in if they are used as identifiers. These are reserved in strict mode and sloppy mode:

The following are only reserved when they are found in strict mode code:

\n

Examples

\n

Strict and non-strict reserved keywords

\n
\n

The enum identifier is generally reserved.

\n

js

\n
const enum = { RED: 0, GREEN: 1, BLUE: 2 };\n// SyntaxError: enum is a reserved identifier\n
\n

In strict mode code, more identifiers are reserved.

\n

js

\n
\"use strict\";\nconst package = [\"potatoes\", \"rice\", \"fries\"];\n// SyntaxError: package is a reserved identifier\n
\n

You'll need to rename these variables.

\n

js

\n
const colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };\nconst list = [\"potatoes\", \"rice\", \"fries\"];\n
\n
\n

Update older browsers

\n
\n

If you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these new language features.

\n

js

\n
\"use strict\";\nclass DocArchiver {}\n\n// SyntaxError: class is a reserved identifier\n// (throws in older browsers only, e.g. Firefox 44 and older)\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reserved_identifier\n

\n
\n", + "errors/json_bad_parse": "

SyntaxError: JSON.parse: bad parsing

The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON.

\n

Message

\n
SyntaxError: JSON.parse: unterminated string literal\nSyntaxError: JSON.parse: bad control character in string literal\nSyntaxError: JSON.parse: bad character in string literal\nSyntaxError: JSON.parse: bad Unicode escape\nSyntaxError: JSON.parse: bad escape character\nSyntaxError: JSON.parse: unterminated string\nSyntaxError: JSON.parse: no number after minus sign\nSyntaxError: JSON.parse: unexpected non-digit\nSyntaxError: JSON.parse: missing digits after decimal point\nSyntaxError: JSON.parse: unterminated fractional number\nSyntaxError: JSON.parse: missing digits after exponent indicator\nSyntaxError: JSON.parse: missing digits after exponent sign\nSyntaxError: JSON.parse: exponent part is missing a number\nSyntaxError: JSON.parse: unexpected end of data\nSyntaxError: JSON.parse: unexpected keyword\nSyntaxError: JSON.parse: unexpected character\nSyntaxError: JSON.parse: end of data while reading object contents\nSyntaxError: JSON.parse: expected property name or '}'\nSyntaxError: JSON.parse: end of data when ',' or ']' was expected\nSyntaxError: JSON.parse: expected ',' or ']' after array element\nSyntaxError: JSON.parse: end of data when property name was expected\nSyntaxError: JSON.parse: expected double-quoted property name\nSyntaxError: JSON.parse: end of data after property name when ':' was expected\nSyntaxError: JSON.parse: expected ':' after property name in object\nSyntaxError: JSON.parse: end of data after property value in object\nSyntaxError: JSON.parse: expected ',' or '}' after property value in object\nSyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal\nSyntaxError: JSON.parse: property names must be double-quoted strings\nSyntaxError: JSON.parse: expected property name or '}'\nSyntaxError: JSON.parse: unexpected character\nSyntaxError: JSON.parse: unexpected non-whitespace character after JSON data\n

Error type

\n
SyntaxError

What went wrong?

\n

JSON.parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

Examples

\n

JSON.parse() does not allow trailing commas

\n
\n

Both lines will throw a SyntaxError:

\n

js

\n
JSON.parse(\"[1, 2, 3, 4,]\");\nJSON.parse('{\"foo\": 1,}');\n// SyntaxError JSON.parse: unexpected character\n// at line 1 column 14 of the JSON data\n
\n

Omit the trailing commas to parse the JSON correctly:

\n

js

\n
JSON.parse(\"[1, 2, 3, 4]\");\nJSON.parse('{\"foo\": 1}');\n
\n
\n

Property names must be double-quoted strings

\n
\n

You cannot use single-quotes around properties, like 'foo'.

\n

js

\n
JSON.parse(\"{'foo': 1}\");\n// SyntaxError: JSON.parse: expected property name or '}'\n// at line 1 column 2 of the JSON data\n
\n

Instead write \"foo\":

\n

js

\n
JSON.parse('{\"foo\": 1}');\n
\n
\n

Leading zeros and decimal points

\n
\n

You cannot use leading zeros, like 01, and decimal points must be followed by at least one digit.

\n

js

\n
JSON.parse('{\"foo\": 01}');\n// SyntaxError: JSON.parse: expected ',' or '}' after property value\n// in object at line 1 column 2 of the JSON data\n\nJSON.parse('{\"foo\": 1.}');\n// SyntaxError: JSON.parse: unterminated fractional number\n// at line 1 column 2 of the JSON data\n
\n

Instead write just 1 without a zero and use at least one digit after a decimal point:

\n

js

\n
JSON.parse('{\"foo\": 1}');\nJSON.parse('{\"foo\": 1.0}');\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse\n

\n
\n", + "errors/hash_outside_class": "

SyntaxError: Unexpected '#' used outside of class body

The JavaScript exception \"Unexpected '#' used outside of class body\" occurs when a hash (\"#\") is encountered in an unexpected context, most notably outside of a class declaration. Hashes are valid at the beginning of a file as a hashbang comment, or inside of a class as part of a private field. You may encounter this error if you forget the quotation marks when trying to access a DOM identifier as well.

\n

Message

\n
SyntaxError: Unexpected '#' used outside of class body.\n

Error type

\n
SyntaxError

What went wrong?

\n

We encountered a # somewhere unexpected. This may be due to code moving around and no longer being part of a class, a hashbang comment found on a line other than the first line of a file, or accidentally forgetting the quotation marks around a DOM identifier.

Examples

\n

Missing quotation marks

\n
\n

For each case, there might be something slightly wrong. For example

\n

js

\n
document.querySelector(#some-element)\n
\n

This can be fixed via

\n

js

\n
document.querySelector(\"#some-element\");\n
\n
\n

Outside of a class

\n
\n
\n

js

\n
class ClassWithPrivateField {\n  #privateField;\n\n  constructor() {}\n}\n\nthis.#privateField = 42;\n
\n

This can be fixed by moving the private field back into the class

\n

js

\n
class ClassWithPrivateField {\n  #privateField;\n\n  constructor() {\n    this.#privateField = 42;\n  }\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Hash_outside_class\n

\n
\n", + "errors/unexpected_token": "

SyntaxError: Unexpected token

The JavaScript exceptions \"unexpected token\" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

\n

Message

\n
SyntaxError: expected expression, got \"x\"\nSyntaxError: expected property name, got \"x\"\nSyntaxError: expected target, got \"x\"\nSyntaxError: expected rest argument name, got \"x\"\nSyntaxError: expected closing parenthesis, got \"x\"\nSyntaxError: expected '=>' after argument list, got \"x\"\n

Error type

\n
SyntaxError

What went wrong?

\n

A specific language construct was expected, but something else was provided. This might be a simple typo.

Examples

\n

Expression expected

\n
\n

For example, when chaining expressions, trailing commas are not allowed.

\n

js

\n
for (let i = 0; i < 5,; ++i) {\n  console.log(i);\n}\n// Uncaught SyntaxError: expected expression, got ';'\n
\n

Correct would be omitting the comma or adding another expression:

\n

js

\n
for (let i = 0; i < 5; ++i) {\n  console.log(i);\n}\n
\n
\n

Not enough parenthese

\n
\n

Sometimes, you leave out parenthese around if statements:

\n

js

\n
function round(n, upperBound, lowerBound) {\n  if (n > upperBound) || (n < lowerBound) { // Not enough parenthese here!\n    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);\n  } else if (n < (upperBound + lowerBound) / 2) {\n    return lowerBound;\n  } else {\n    return upperBound;\n  }\n} // SyntaxError: expected expression, got '||'\n
\n

The parenthese may look correct at first, but note how the || is outside the parenthese. Correct would be putting parenthese around the ||:

\n

js

\n
function round(n, upperBound, lowerBound) {\n  if ((n > upperBound) || (n < lowerBound)) {\n    throw new Error(\n      `Number ${n} is more than ${upperBound} or less than ${lowerBound}`,\n    );\n  } else if (n < (upperBound + lowerBound) / 2) {\n    return lowerBound;\n  } else {\n    return upperBound;\n  }\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token\n

\n
\n", + "errors/deprecated_source_map_pragma": "

SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead

The JavaScript warning \"Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead\" occurs when there is a deprecated source map syntax in a JavaScript source.

\n

Message

\n
Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead\n\nWarning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead\n

Error type

\n

A warning that a SyntaxError occurred. JavaScript execution won't be halted.

What went wrong?

\n
\n

There is a deprecated source map syntax in a JavaScript source.

JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files.

The source map specification changed the syntax due to a conflict with IE whenever it was found in the page after //@cc_on was interpreted to turn on conditional compilation in the IE JScript engine. The conditional compilation comment in IE is a little known feature, but it broke source maps with jQuery and other libraries.

\n

Examples

\n

Deprecated syntax

\n
\n

Syntax with the \"@\" sign is deprecated.

\n

js

\n
//@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map\n
\n
\n

Standard syntax

\n
\n

Use the \"#\" sign instead.

\n

js

\n
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map\n
\n

Or, alternatively, you can set a SourceMap header to your JavaScript file to avoid having a comment at all:

\n

http

\n
SourceMap: /path/to/file.js.map\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_source_map_pragma\n

\n
\n", + "errors/bad_continue": "

SyntaxError: continue must be inside loop

The JavaScript exception \"continue must be inside loop\" occurs when a continue statement is not inside a loop statement.

\n

Message

\n
SyntaxError: Illegal continue statement: no surrounding iteration statement (V8-based)\nSyntaxError: Illegal continue statement: 'label' does not denote an iteration statement (V8-based)\nSyntaxError: continue must be inside loop (Firefox)\nSyntaxError: 'continue' is only valid inside a loop statement. (Safari)\nSyntaxError: Cannot continue to the label 'label' as it is not targeting a loop. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

continue statements can be used to continue a loop, and using them elsewhere is a syntax error. Alternatively, you can provide a label to the continue statement to continue any loop with that label — however, if the label does not reference a containing statement, another error SyntaxError: label not found will be thrown, and if the label references a statement that is not a loop, a syntax error is still thrown.

Examples

\n

Using continue in callbacks

\n
\n

If you want to proceed with the next iteration in a forEach() loop, use return instead, or convert it to a for...of loop.

\n

js

\n
array.forEach((value) => {\n  if (value === 5) {\n    continue; // SyntaxError: continue must be inside loop\n  }\n  // do something with value\n});\n
\n
\n

js

\n
array.forEach((value) => {\n  if (value === 5) {\n    return;\n  }\n  // do something with value\n});\n
\n
\n

js

\n
for (const value of array) {\n  if (value === 5) {\n    continue;\n  }\n  // do something with value\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_continue\n

\n
\n", + "errors/either_be_both_static_or_non-static": "

SyntaxError: getter and setter for private name #x should either be both static or non-static

The JavaScript exception \"mismatched placement\" occurs when a private getter and setter are mismatched in whether or not they are static.

\n

Message

\n
SyntaxError: Identifier '#x' has already been declared (V8-based)\nSyntaxError: getter and setter for private name #x should either be both static or non-static (Firefox)\nSyntaxError: Cannot declare a private non-static getter if there is a static private setter with used name. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

Private getters and setters for the same name must either be both static, or both non-static. This limitation does not exist for public methods.

Examples

\n

Mismatched placement

\n
\n
\n

js

\n
class Test {\n  static set #foo(_) {}\n  get #foo() {}\n}\n\n// SyntaxError: getter and setter for private name #foo should either be both static or non-static\n
\n

Since foo is private, the methods must be either both static:

\n

js

\n
class Test {\n  static set #foo(_) {}\n  static get #foo() {}\n}\n
\n

or non-static:

\n

js

\n
class Test {\n  set #foo(_) {}\n  get #foo() {}\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Either_be_both_static_or_non-static\n

\n
\n", + "errors/illegal_character": "

SyntaxError: illegal character

The JavaScript exception \"illegal character\" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code.

\n

Message

\n
SyntaxError: Invalid character (Edge)\nSyntaxError: illegal character (Firefox)\nSyntaxError: Invalid or unexpected token (Chrome)\n

Error type

\n
SyntaxError

What went wrong?

\n

There is an invalid or unexpected token that doesn't belong at this position in the code. Use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign (-) versus a dash () or simple quotes (\") versus non-standard quotation marks (\").

Examples

\n

Mismatched characters

\n
\n

Some characters look similar, but will cause the parser to fail interpreting your code. Famous examples of this are quotes, the minus or semicolon (greek question mark (U+37e) looks same).

\n

js

\n
“This looks like a string”; // SyntaxError: illegal character\n// “ and ” are not \" but look like it\n\n4213; // SyntaxError: illegal character\n// – (en-dash) is not - but looks like it\n\nconst foo = \"bar\"; // SyntaxError: illegal character\n// <37e> is not ; but looks like it\n
\n

This should work:

\n

js

\n
\"This is actually a string\";\n42 - 13;\nconst foo = \"bar\";\n
\n

Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.

\n

Forgotten characters

\n
\n

It's easy to forget a character here or there.

\n

js

\n
const colors = [\"#000\", #333\", \"#666\"];\n// SyntaxError: illegal character\n
\n

Add the missing quote for \"#333\".

\n

js

\n
const colors = [\"#000\", \"#333\", \"#666\"];\n
\n
\n

Hidden characters

\n
\n

When copy pasting code from external sources, there might be invalid characters. Watch out!

\n

js

\n
const foo = \"bar\";​\n// SyntaxError: illegal character\n
\n

When inspecting this code in an editor like Vim, you can see that there is actually a zero-width space (ZWSP) (U+200B) character.

\n

js

\n
const foo = \"bar\";<200b>\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Illegal_character\n

\n
\n", + "errors/bad_regexp_flag": "

SyntaxError: invalid regular expression flag \"x\"

\n

The JavaScript exception \"invalid regular expression flag\" occurs when the flags in a regular expression contain any flag that is not one of: d, g, i, m, s, u, v, or y.

It may also be raised if the expression contains more than one instance of a valid flag.

\n
\n

Message

\n
SyntaxError: Invalid regular expression flags (V8-based)\nSyntaxError: invalid regular expression flag x (Firefox)\nSyntaxError: Invalid regular expression: invalid flags (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

The regular expression contains invalid flags, or valid flags have been used more than once in the expression.

The valid (allowed) flags are d, g, i, m, s, u, v, and y. They are introduced in more detail in Regular expressions > Advanced searching with flags.

\n

Examples

\n
\n

In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. Regular expression flags can be used separately or together in any order. This syntax shows how to declare the flags using the regular expression literal:

\n

js

\n
const re = /pattern/flags;\n
\n

They can also be defined in the constructor function of the RegExp object (second parameter):

\n

js

\n
const re = new RegExp(\"pattern\", \"flags\");\n
\n

Here is an example showing use of only correct flags.

\n

js

\n
/foo/g;\n/foo/gims;\n/foo/uy;\n
\n

Below is an example showing the use of some invalid flags b, a and r:

\n

js

\n
/foo/bar;\n\n// SyntaxError: invalid regular expression flag \"b\"\n
\n

The code below is incorrect, because W, e and b are not valid flags.

\n

js

\n
const obj = {\n  url: /docs/Web,\n};\n\n// SyntaxError: invalid regular expression flag \"W\"\n
\n

An expression containing two slashes is interpreted as a regular expression literal. Most likely the intent was to create a string literal, using single or double quotes as shown below:

\n

js

\n
const obj = {\n  url: \"/docs/Web\",\n};\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_regexp_flag\n

\n
\n", + "errors/missing_parenthesis_after_argument_list": "

SyntaxError: missing ) after argument list

The JavaScript exception \"missing ) after argument list\" occurs when there is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string.

\n

Message

\n
SyntaxError: missing ) after argument list (V8-based & Firefox)\nSyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

There is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string, for example.

Examples

\n
\n

Because there is no \"+\" operator to concatenate the string, JavaScript expects the argument for the log function to be just \"PI: \". In that case, it should be terminated by a closing parenthesis.

\n

js

\n
console.log(\"PI: \" Math.PI);\n// SyntaxError: missing ) after argument list\n
\n

You can correct the log call by adding the + operator:

\n

js

\n
console.log(\"PI: \" + Math.PI);\n// \"PI: 3.141592653589793\"\n
\n

Alternatively, you can consider using a template literal, or take advantage of the fact that console.log accepts multiple parameters:

\n

js

\n
console.log(`PI: ${Math.PI}`);\nconsole.log(\"PI:\", Math.PI);\n
\n
\n

Unterminated strings

\n
\n
\n

js

\n
console.log('\"Java\" + \"Script\" = \\\"' + \"Java\" + 'Script\\\");\n// SyntaxError: missing ) after argument list\n
\n

Here JavaScript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log. To fix this, we could put a' after the \"Script\" string:

\n

js

\n
console.log('\"Java\" + \"Script\" = \"' + \"Java\" + 'Script\"');\n// '\"Java\" + \"Script\" = \"JavaScript\"'\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list\n

\n
\n", + "errors/invalid_for-of_initializer": "

SyntaxError: a declaration in the head of a for-of loop can't have an initializer

The JavaScript exception \"a declaration in the head of a for-of loop can't have an initializer\" occurs when the head of a for...of loop contains an initializer expression such as for (const i = 0 of iterable). This is not allowed in for-of loops.

\n

Message

\n
SyntaxError: for-of loop variable declaration may not have an initializer. (V8-based)\nSyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)\nSyntaxError: Cannot assign to the loop variable inside a for-of loop header. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

The head of a for...of loop contains an initializer expression. That is, a variable is declared and assigned a value for (const i = 0 of iterable). This is not allowed in for-of loops. You might want a for loop that does allow an initializer.

Examples

\n

Invalid for-of loop

\n
\n

js

\n
const iterable = [10, 20, 30];\n\nfor (const value = 50 of iterable) {\n  console.log(value);\n}\n\n// SyntaxError: a declaration in the head of a for-of loop can't\n// have an initializer\n
\n

Valid for-of loop

\n
\n

You need to remove the initializer (value = 50) in the head of the for-of loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.

\n

js

\n
const iterable = [10, 20, 30];\n\nfor (let value of iterable) {\n  value += 50;\n  console.log(value);\n}\n// 60\n// 70\n// 80\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-of_initializer\n

\n
\n", + "errors/delete_in_strict_mode": "

SyntaxError: applying the 'delete' operator to an unqualified name is deprecated

The JavaScript strict mode-only exception \"applying the 'delete' operator to an unqualified name is deprecated\" occurs when variables are attempted to be deleted using the delete operator.

\n

Message

\n
SyntaxError: Delete of an unqualified identifier in strict mode. (V8-based)\nSyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)\nSyntaxError: Cannot delete unqualified property 'a' in strict mode. (Safari)\n

Error type

\n

SyntaxError in strict mode only.

What went wrong?

\n
\n

Normal variables in JavaScript can't be deleted using the delete operator. In strict mode, an attempt to delete a variable will throw an error and is not allowed.

The delete operator can only delete properties on an object. Object properties are \"qualified\" if they are configurable.

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details.

This error only happens in strict mode code. In non-strict code, the operation just returns false.

\n

Examples

\n

Freeing the contents of a variable

\n
\n

Attempting to delete a plain variable throws an error in strict mode:

\n

js

\n
\"use strict\";\n\nvar x;\n\n// …\n\ndelete x;\n\n// SyntaxError: applying the 'delete' operator to an unqualified name\n// is deprecated\n
\n

To free the contents of a variable, you can set it to null:

\n

js

\n
\"use strict\";\n\nvar x;\n\n// …\n\nx = null;\n\n// x can be garbage collected\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Delete_in_strict_mode\n

\n
\n", + "errors/bad_await": "

SyntaxError: await is only valid in async functions, async generators and modules

The JavaScript exception \"await is only valid in async functions, async generators and modules\" occurs when an await expression is used outside of async functions or modules or other async contexts.

\n

Message

\n
SyntaxError: await is only valid in async functions and the top level bodies of modules (V8-based)\nSyntaxError: await is only valid in async functions, async generators and modules (Firefox)\nSyntaxError: Unexpected identifier (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

JavaScript execution is never blocking: an await can never block the execution of the program. Instead, it pauses the execution of the surrounding async task, while allowing other tasks to continue running. Therefore, await cannot be used in sync tasks, such as functions, generator functions, or top level of scripts. It is not always apparent whether the current file is a script or a module — see the Modules guide for more information.

Examples

\n

Top-level await

\n
\n

You cannot use await at the top level of a script:

\n

html

\n
<script>\n  await fetch(\"https://example.com\");\n  // SyntaxError: await is only valid in async functions, async generators and modules\n</script>\n
\n

Instead, make the script a module:

\n

html

\n
<script type=\"module\">\n  await fetch(\"https://example.com\");\n</script>\n
\n
\n

Async callbacks

\n
\n

You cannot use await in a sync callback:

\n

js

\n
urls.forEach((url) => {\n  await fetch(url);\n  // SyntaxError: await is only valid in async functions, async generators and modules\n});\n
\n

Instead, make the callback async. See more explanation in the Using promises guide.

\n

js

\n
Promise.all(\n  urls.map(async (url) => {\n    await fetch(url);\n  }),\n);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_await\n

\n
\n", + "errors/unnamed_function_statement": "

SyntaxError: function statement requires a name

The JavaScript exception \"function statement requires a name\" occurs when there is a function statement in the code that requires a name.

\n

Message

\n
SyntaxError: Function statements require a function name (V8-based)\nSyntaxError: function statement requires a name (Firefox)\nSyntaxError: Function statements must have a name. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

There is a function statement in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all.

Examples

\n

Statements vs. expressions

\n
\n

A function statement (or function declaration) requires a name. This won't work:

\n

js

\n
function () {\n  return \"Hello world\";\n}\n// SyntaxError: function statement requires a name\n
\n

You can use a function expression (assignment) instead:

\n

js

\n
const greet = function () {\n  return \"Hello world\";\n};\n
\n

If your function is intended to be an IIFE (Immediately Invoked Function Expression, which is a function that runs as soon as it is defined) you will need to add a few more braces:

\n

js

\n
(function () {\n  // …\n})();\n
\n
\n

Labeled functions

\n
\n

Labels are an entirely different feature from function names. You can't use a label as a function name.

\n

js

\n
function Greeter() {\n  german: function () {\n    return \"Moin\";\n  }\n}\n// SyntaxError: function statement requires a name\n
\n

In addition, labeled function declarations themselves are a deprecated feature. Use regular function declarations instead.

\n

js

\n
function Greeter() {\n  function german() {\n    return \"Moin\";\n  }\n}\n
\n
\n

Object methods

\n
\n

If you intended to create a method of an object, you will need to create an object. The following syntax without a name after the function keyword is valid then.

\n

js

\n
const greeter = {\n  german: function () {\n    return \"Moin\";\n  },\n};\n
\n

You can also use the method syntax.

\n

js

\n
const greeter = {\n  german() {\n    return \"Moin\";\n  },\n};\n
\n
\n

Callback syntax

\n
\n

Also, check your syntax when using callbacks. Braces and commas can quickly get confusing.

\n

js

\n
promise.then(\n  function () {\n    console.log(\"success\");\n  });\n  function () {\n    console.log(\"error\");\n}\n// SyntaxError: function statement requires a name\n
\n

Correct would be:

\n

js

\n
promise.then(\n  function () {\n    console.log(\"success\");\n  },\n  function () {\n    console.log(\"error\");\n  },\n);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unnamed_function_statement\n

\n
\n", + "errors/identifier_after_number": "

SyntaxError: identifier starts immediately after numeric literal

The JavaScript exception \"identifier starts immediately after numeric literal\" occurs when an identifier started with a digit. Identifiers can only start with a letter, underscore (_), or dollar sign ($).

\n

Message

\n
SyntaxError: Unexpected identifier after numeric literal (Edge)\nSyntaxError: identifier starts immediately after numeric literal (Firefox)\nSyntaxError: Unexpected number (Chrome)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

The names of variables, called identifiers, conform to certain rules, which your code must adhere to!

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). They can't start with a digit! Only subsequent characters can be digits (0-9).

\n

Examples

\n

Variable names starting with numeric literals

\n
\n

Variable names can't start with numbers in JavaScript. The following fails:

\n

js

\n
const 1life = \"foo\";\n// SyntaxError: identifier starts immediately after numeric literal\n\nconst foo = 1life;\n// SyntaxError: identifier starts immediately after numeric literal\n\nalert(1.foo);\n// SyntaxError: identifier starts immediately after numeric literal\n
\n

You will need to rename your variable to avoid the leading number.

\n

js

\n
const life1 = \"foo\";\nconst foo = life1;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Identifier_after_number\n

\n
\n", + "errors/invalid_assignment_left-hand_side": "

SyntaxError: invalid assignment left-hand side

The JavaScript exception \"invalid assignment left-hand side\" occurs when there was an unexpected assignment somewhere. It may be triggered when a single = sign was used instead of == or ===.

\n

Message

\n
SyntaxError: Invalid left-hand side in assignment (V8-based)\nSyntaxError: invalid assignment left-hand side (Firefox)\nSyntaxError: Left side of assignment is not a reference. (Safari)\n

Error type

\n

SyntaxError or ReferenceError, depending on the syntax.

What went wrong?

\n

There was an unexpected assignment somewhere. This might be due to a mismatch of an assignment operator and an equality operator, for example. While a single = sign assigns a value to a variable, the == or === operators compare a value.

Examples

\n

Typical invalid assignments

\n
\n
\n

js

\n
if (Math.PI + 1 = 3 || Math.PI + 1 = 4) {\n  console.log(\"no way!\");\n}\n// SyntaxError: invalid assignment left-hand side\n\nconst str = \"Hello, \"\n+= \"is it me \"\n+= \"you're looking for?\";\n// SyntaxError: invalid assignment left-hand side\n
\n

In the if statement, you want to use an equality operator (===), and for the string concatenation, the plus (+) operator is needed.

\n

js

\n
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {\n  console.log(\"no way!\");\n}\n\nconst str = \"Hello, \"\n  + \"from the \"\n  + \"other side!\";\n
\n
\n

Assignments producing ReferenceErrors

\n
\n

Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed.

\n

js

\n
function foo() {\n  return { a: 1 };\n}\nfoo() = 1; // ReferenceError: invalid assignment left-hand side\n
\n

Function calls, new calls, super(), and this are all values instead of references. If you want to use them on the left hand side, the assignment target needs to be a property of their produced values instead.

\n

js

\n
function foo() {\n  return { a: 1 };\n}\nfoo().a = 1;\n
\n

Note: In Firefox and Safari, the first example produces a ReferenceError in non-strict mode, and a SyntaxError in strict mode. Chrome throws a runtime ReferenceError for both strict and non-strict modes.

\n

Using optional chaining as assignment target

\n
\n

Optional chaining is not a valid target of assignment.

\n

js

\n
obj?.foo = 1; // SyntaxError: invalid assignment left-hand side\n
\n

Instead, you have to first guard the nullish case.

\n

js

\n
if (obj) {\n  obj.foo = 1;\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side\n

\n
\n", + "errors/label_not_found": "

SyntaxError: label not found

The JavaScript exception \"label not found\" occurs when a break or continue statement references a label that does not exist on any statement that contains the break or continue statement.

\n

Message

\n
SyntaxError: Undefined label 'label' (V8-based)\nSyntaxError: label not found (Firefox)\nSyntaxError: Cannot use the undeclared label 'label'. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

In JavaScript, labels are very limited: you can only use them with break and continue statements, and you can only jump to them from a statement contained within the labeled statement. You cannot jump to this label from anywhere in the program.

Examples

\n

Unsyntactic jump

\n
\n

You cannot use labels as if they are goto.

\n

js

\n
start: console.log(\"Hello, world!\");\nconsole.log(\"Do it again\");\nbreak start;\n
\n

Instead, you can only use labels to enhance the normal semantics of break and continue statements.

\n

js

\n
start: {\n  console.log(\"Hello, world!\");\n  if (Math.random() > 0.5) {\n    break start;\n  }\n  console.log(\"Maybe I'm logged\");\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Label_not_found\n

\n
\n", + "errors/missing_parenthesis_after_condition": "

SyntaxError: missing ) after condition

The JavaScript exception \"missing ) after condition\" occurs when there is an error with how an if condition is written. It must appear in parenthesis after the if keyword.

\n

Message

\n
SyntaxError: missing ) after condition (Firefox)\nSyntaxError: Unexpected token '{'. Expected ')' to end an 'if' condition. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

There is an error with how an if condition is written. In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. The if statement executes a statement if a specified condition is truthy. In JavaScript, this condition must appear in parenthesis after the if keyword, like this:

\n

js

\n
if (condition) {\n  // do something if the condition is true\n}\n
\n
\n

Examples

\n

Missing parenthesis

\n
\n

It might just be an oversight, carefully check all you parenthesis in your code.

\n

js

\n
if (Math.PI < 3 {\n  console.log(\"wait what?\");\n}\n\n// SyntaxError: missing ) after condition\n
\n

To fix this code, you would need to add a parenthesis that closes the condition.

\n

js

\n
if (Math.PI < 3) {\n  console.log(\"wait what?\");\n}\n
\n
\n

Misused is keyword

\n
\n

If you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in JavaScript.

\n

js

\n
if (done is true) {\n console.log(\"we are done!\");\n}\n\n// SyntaxError: missing ) after condition\n
\n

Instead you need to use a correct comparison operator. For example:

\n

js

\n
if (done === true) {\n  console.log(\"we are done!\");\n}\n
\n

Or even better:

\n

js

\n
if (done) {\n  console.log(\"we are done!\");\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition\n

\n
\n", + "errors/missing_initializer_in_const": "

SyntaxError: missing = in const declaration

The JavaScript exception \"missing = in const declaration\" occurs when a const declaration was not given a value in the same statement (like const RED_FLAG;). You need to provide one (const RED_FLAG = \"#ff0\").

\n

Message

\n
SyntaxError: Missing initializer in const declaration (V8-based)\nSyntaxError: missing = in const declaration (Firefox)\nSyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).

Examples

\n

Missing const initializer

\n
\n

Unlike var or let, you must specify a value for a const declaration. This throws:

\n

js

\n
const COLUMNS;\n// SyntaxError: missing = in const declaration\n
\n
\n

Fixing the error

\n
\n

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

Adding a constant value

Specify the constant value in the same statement in which it's declared:

\n

js

\n
const COLUMNS = 80;\n
\n

\nconst, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var. Both don't require an initial value.

\n

js

\n
let columns;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_initializer_in_const\n

\n
\n", + "errors/missing_bracket_after_list": "

SyntaxError: missing ] after element list

The JavaScript exception \"missing ] after element list\" occurs when there is an error with the array initializer syntax somewhere. Likely there is a closing square bracket (]) or a comma (,) missing.

\n

Message

\n
SyntaxError: missing ] after element list (Firefox)\nSyntaxError: Unexpected token ';'. Expected either a closing ']' or a ',' following an array element. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

There is an error with the array initializer syntax somewhere. Likely there is a closing square bracket (]) or a comma (,) missing.

Examples

\n

Incomplete array initializer

\n
\n
\n

js

\n
const list = [1, 2,\n\nconst instruments = [\n  \"Ukulele\",\n  \"Guitar\",\n  \"Piano\",\n};\n\nconst data = [{ foo: \"bar\" } { bar: \"foo\" }];\n
\n

Correct would be:

\n

js

\n
const list = [1, 2];\n\nconst instruments = [\"Ukulele\", \"Guitar\", \"Piano\"];\n\nconst data = [{ foo: \"bar\" }, { bar: \"foo\" }];\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_bracket_after_list\n

\n
\n", + "errors/missing_name_after_dot_operator": "

SyntaxError: missing name after . operator

The JavaScript exception \"missing name after . operator\" occurs when there is a problem with how the dot operator (.) is used for property access.

\n

Message

\n
SyntaxError: missing name after . operator (Firefox)\nSyntaxError: Unexpected token '['. Expected a property name after '.'. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

The dot operator (.) is used for property access. You will have to specify the name of the property that you want to access. For computed property access, you might need to change your property access from using a dot to using square brackets. These will allow you to compute an expression. Maybe you intended to do concatenation instead? A plus operator (+) is needed in that case. Please see the examples below.

Examples

\n

Property access

\n
\n

Property accessors in JavaScript use either the dot (.) or square brackets ([]), but not both. Square brackets allow computed property access.

\n

js

\n
const obj = { foo: { bar: \"baz\", bar2: \"baz2\" } };\nconst i = 2;\n\nobj.[foo].[bar]\n// SyntaxError: missing name after . operator\n\nobj.foo.\"bar\"+i;\n// SyntaxError: missing name after . operator\n
\n

To fix this code, you need to access the object like this:

\n

js

\n
obj.foo.bar; // \"baz\"\n// or alternatively\nobj[\"foo\"][\"bar\"]; // \"baz\"\n\n// computed properties require square brackets\nobj.foo[\"bar\" + i]; // \"baz2\"\n// or as template literal\nobj.foo[`bar${i}`]; // \"baz2\"\n
\n
\n

Property access vs. concatenation

\n
\n

If you are coming from another programming language (like PHP), it is also easy to mix up the dot operator (.) and the concatenation operator (+).

\n

js

\n
console.log(\"Hello\" . \"world\");\n\n// SyntaxError: missing name after . operator\n
\n

Instead you need to use a plus sign for concatenation:

\n

js

\n
console.log(\"Hello\" + \"World\");\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator\n

\n
\n", + "errors/missing_colon_after_property_id": "

SyntaxError: missing : after property id

The JavaScript exception \"missing : after property id\" occurs when objects are created using the object initializer syntax. A colon (:) separates keys and values for the object's properties. Somehow, this colon is missing or misplaced.

\n

Message

\n
SyntaxError: Invalid shorthand property initializer (V8-based)\nSyntaxError: missing : after property id (Firefox)\nSyntaxError: Unexpected token '='. Expected a ':' following the property name 'x'. (Safari)\nSyntaxError: Unexpected token '+'. Expected an identifier as property name. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

When creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties.

\n

js

\n
const obj = { propertyKey: \"value\" };\n
\n
\n

Examples

\n

Colons vs. equal signs

\n
\n

This code fails, as the equal sign can't be used this way in this object initializer syntax.

\n

js

\n
const obj = { propertyKey = \"value\" };\n// SyntaxError: missing : after property id\n
\n

Correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already.

\n

js

\n
const obj = { propertyKey: \"value\" };\n
\n

Or alternatively:

\n

js

\n
const obj = {};\nobj.propertyKey = \"value\";\n
\n
\n

Computed properties

\n
\n

If you create a property key from an expression, you need to use square brackets. Otherwise the property name can't be computed:

\n

js

\n
const obj = { \"b\"+\"ar\": \"foo\" };\n// SyntaxError: missing : after property id\n
\n

Put the expression in square brackets []:

\n

js

\n
const obj = { [\"b\" + \"ar\"]: \"foo\" };\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_colon_after_property_id\n

\n
\n", + "errors/missing_formal_parameter": "

SyntaxError: missing formal parameter

The JavaScript exception \"missing formal parameter\" occurs when your function declaration is missing valid parameters.

\n

Message

\n
SyntaxError: missing formal parameter (Firefox)\nSyntaxError: Unexpected number '3'. Expected a parameter pattern or a ')' in parameter list. (Safari)\nSyntaxError: Unexpected string literal \"x\". Expected a parameter pattern or a ')' in parameter list. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

\"Formal parameter\" is a fancy way of saying \"function parameter\". Your function declaration is missing valid parameters. In the declaration of a function, the parameters must be identifiers, not any value like numbers, strings, or objects. Declaring functions and calling functions are two separate steps. Declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use.

In JavaScript, identifiers can contain only alphanumeric characters (or \"$\" or \"_\"), and may not start with a digit. An identifier differs from a string in that a string is data, while an identifier is part of the code.

\n

Examples

\n

Provide proper function parameters

\n
\n

Function parameters must be identifiers when setting up a function. All these function declarations fail, as they are providing values for their parameters:

\n

js

\n
function square(3) {\n  return number * number;\n}\n// SyntaxError: missing formal parameter\n\nfunction greet(\"Howdy\") {\n  return greeting;\n}\n// SyntaxError: missing formal parameter\n\nfunction log({ obj: \"value\"}) {\n  console.log(arg)\n}\n// SyntaxError: missing formal parameter\n
\n

You will need to use identifiers in function declarations:

\n

js

\n
function square(number) {\n  return number * number;\n}\n\nfunction greet(greeting) {\n  return greeting;\n}\n\nfunction log(arg) {\n  console.log(arg);\n}\n
\n

You can then call these functions with the arguments you like:

\n

js

\n
square(2); // 4\n\ngreet(\"Howdy\"); // \"Howdy\"\n\nlog({ obj: \"value\" }); // { obj: \"value\" }\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_formal_parameter\n

\n
\n", + "errors/missing_semicolon_before_statement": "

SyntaxError: missing ; before statement

The JavaScript exception \"missing ; before statement\" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that JavaScript can parse the source code correctly.

\n

Message

\n
SyntaxError: Expected ';' (Edge)\nSyntaxError: missing ; before statement (Firefox)\n

Error type

\n

SyntaxError.

What went wrong?

\n
\n

There is a semicolon (;) missing somewhere. JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.

However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.

\n

Examples

\n

Unescaped strings

\n
\n

This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:

\n

js

\n
const foo = 'Tom's bar';\n// SyntaxError: missing ; before statement\n
\n

You can use double quotes, or escape the apostrophe:

\n

js

\n
const foo = \"Tom's bar\";\n// OR\nconst foo = 'Tom\\'s bar';\n
\n
\n

Declaring properties with keyword

\n
\n

You cannot declare properties of an object or array with a let, const, or var declaration.

\n

js

\n
const obj = {};\nconst obj.foo = \"hi\"; // SyntaxError missing ; before statement\n\nconst array = [];\nconst array[0] = \"there\"; // SyntaxError missing ; before statement\n
\n

Instead, omit the keyword:

\n

js

\n
const obj = {};\nobj.foo = \"hi\";\n\nconst array = [];\narray[0] = \"there\";\n
\n
\n

Bad keywords

\n
\n

If you come from another programming language, it is also common to use keywords that don't mean the same or have no meaning at all in JavaScript:

\n

js

\n
def print(info) {\n  console.log(info);\n} // SyntaxError missing ; before statement\n
\n

Instead, use function instead of def:

\n

js

\n
function print(info) {\n  console.log(info);\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement\n

\n
\n", + "errors/no_variable_name": "

SyntaxError: missing variable name

The JavaScript exception \"missing variable name\" is a common error. It is usually caused by omitting a variable name or a typographic error.

\n

Message

\n
SyntaxError: missing variable name (Firefox)\nSyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

A variable is missing a name. The cause is most likely a typo or a forgotten variable name. Make sure that you've provided the name of the variable before the = sign.

When declaring multiple variables at the same time, make sure that the previous lines/declaration does not end with a comma instead of a semicolon.

\n

Examples

\n

Missing a variable name

\n
\n
\n

js

\n
const = \"foo\";\n
\n

It is easy to forget to assign a name for your variable!

\n

js

\n
const description = \"foo\";\n
\n
\n

Reserved keywords can't be variable names

\n
\n

There are a few variable names that are reserved keywords. You can't use these. Sorry :(

\n

js

\n
const debugger = \"whoop\";\n// SyntaxError: missing variable name\n
\n
\n

Declaring multiple variables

\n
\n

Pay special attention to commas when declaring multiple variables. Is there an excess comma, or did you use commas instead of semicolons? Did you remember to assign values for all your const variables?

\n

js

\n
let x, y = \"foo\",\nconst z, = \"foo\"\n\nconst first = document.getElementById(\"one\"),\nconst second = document.getElementById(\"two\"),\n\n// SyntaxError: missing variable name\n
\n

The fixed version:

\n

js

\n
let x,\n  y = \"foo\";\nconst z = \"foo\";\n\nconst first = document.getElementById(\"one\");\nconst second = document.getElementById(\"two\");\n
\n
\n

Arrays

\n
\n

Array literals in JavaScript need square brackets around the values. This won't work:

\n

js

\n
const arr = 1,2,3,4,5;\n// SyntaxError: missing variable name\n
\n

This would be correct:

\n

js

\n
const arr = [1, 2, 3, 4, 5];\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/No_variable_name\n

\n
\n", + "errors/missing_curly_after_function_body": "

SyntaxError: missing } after function body

The JavaScript exception \"missing } after function body\" occurs when there is a syntax mistake when creating a function somewhere. Check if any closing curly braces or parenthesis are in the correct order.

\n

Message

\n
SyntaxError: missing } after function body (Firefox)\n

Error type

\n
SyntaxError

What went wrong?

\n

There is a syntax mistake when creating a function somewhere. Also check if any closing curly braces or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.

Examples

\n

Forgotten closing curly bracket

\n
\n

Oftentimes, there is a missing curly bracket in your function code:

\n

js

\n
function charge() {\n  if (sunny) {\n    useSolarCells();\n  } else {\n    promptBikeRide();\n}\n
\n

Correct would be:

\n

js

\n
function charge() {\n  if (sunny) {\n    useSolarCells();\n  } else {\n    promptBikeRide();\n  }\n}\n
\n

It can be more obscure when using IIFEs or other constructs that use a lot of different parenthesis and curly braces, for example.

\n

js

\n
(function () {\n  if (Math.random() < 0.01) {\n    doSomething();\n  }\n)();\n
\n

Oftentimes, indenting differently or double checking indentation helps to spot these errors.

\n

js

\n
(function () {\n  if (Math.random() < 0.01) {\n    doSomething();\n  }\n})();\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_curly_after_function_body\n

\n
\n", + "errors/missing_curly_after_property_list": "

SyntaxError: missing } after property list

The JavaScript exception \"missing } after property list\" occurs when there is a mistake in the object initializer syntax somewhere. Might be in fact a missing curly bracket, but could also be a missing comma.

\n

Message

\n
SyntaxError: missing } after property list (Firefox)\nSyntaxError: Unexpected identifier 'c'. Expected '}' to end an object literal. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

There is a mistake in the object initializer syntax somewhere. Might be in fact a missing curly bracket, but could also be a missing comma, for example. Also check if any closing curly braces or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.

Examples

\n

Forgotten comma

\n
\n

Oftentimes, there is a missing comma in your object initializer code:

\n

js

\n
const obj = {\n  a: 1,\n  b: { myProp: 2 }\n  c: 3\n};\n
\n

Correct would be:

\n

js

\n
const obj = {\n  a: 1,\n  b: { myProp: 2 },\n  c: 3,\n};\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_curly_after_property_list\n

\n
\n", + "errors/redeclared_parameter": "

SyntaxError: redeclaration of formal parameter \"x\"

The JavaScript exception \"redeclaration of formal parameter\" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.

\n

Message

\n
SyntaxError: Identifier \"x\" has already been declared (V8-based)\nSyntaxError: redeclaration of formal parameter \"x\" (Firefox)\nSyntaxError: Cannot declare a let variable twice: 'x'. (Safari)\n

Error type

\n
SyntaxError

What went wrong?

\n

The same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. Redeclaring the same variable within the same function or block scope using let is not allowed in JavaScript.

Examples

\n

Redeclared argument

\n
\n

In this case, the variable \"arg\" redeclares the argument.

\n

js

\n
function f(arg) {\n  let arg = \"foo\";\n}\n\n// SyntaxError: redeclaration of formal parameter \"arg\"\n
\n

If you want to change the value of \"arg\" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the let keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already.

\n

js

\n
function f(arg) {\n  arg = \"foo\";\n}\n\nfunction g(arg) {\n  let bar = \"foo\";\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Redeclared_parameter\n

\n
\n", + "errors/bad_return": "

SyntaxError: return not in function

The JavaScript exception \"return not in function\" occurs when a return statement is called outside of a function.

\n

Message

\n
SyntaxError: Illegal return statement (V8-based)\nSyntaxError: return not in function (Firefox)\nSyntaxError: Return statements are only valid inside functions. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

A return statement is called outside of a function. Maybe there are missing curly braces somewhere? The return statement must be in a function, because it ends function execution and specifies a value to be returned to the function caller.

Examples

\n

Missing curly braces

\n
\n
\n

js

\n
function cheer(score) {\n  if (score === 147)\n    return \"Maximum!\";\n  }\n  if (score > 100) {\n    return \"Century!\";\n  }\n}\n\n// SyntaxError: return not in function\n
\n

The curly braces look correct at a first glance, but this code snippet is missing a { after the first if statement. Correct would be:

\n

js

\n
function cheer(score) {\n  if (score === 147) {\n    return \"Maximum!\";\n  }\n  if (score > 100) {\n    return \"Century!\";\n  }\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_return\n

\n
\n", + "errors/equal_as_assign": "

SyntaxError: test for equality (==) mistyped as assignment (=)?

The JavaScript warning \"test for equality (==) mistyped as assignment (=)?\" occurs when there was an assignment (=) when you would normally expect a test for equality (==).

\n

Message

\n
Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?\n

Error type

\n

(Firefox only) SyntaxError warning which is reported only if javascript.options.strict preference is set to true.

What went wrong?

\n

There was an assignment (=) when you would normally expect a test for equality (==). To help debugging, JavaScript (with strict warnings enabled) warns about this pattern.

Examples

\n

Assignment within conditional expressions

\n
\n

It is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:

\n

js

\n
if (x = y) {\n  // do the right thing\n}\n
\n

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

\n

js

\n
if ((x = y)) {\n  // do the right thing\n}\n
\n

Otherwise, you probably meant to use a comparison operator (e.g. == or ===):

\n

js

\n
if (x === y) {\n  // do the right thing\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Equal_as_assign\n

\n
\n", + "errors/bad_break": "

SyntaxError: unlabeled break must be inside loop or switch

The JavaScript exception \"unlabeled break must be inside loop or switch\" occurs when a break statement is not inside a loop or a switch statement.

\n

Message

\n
SyntaxError: Illegal break statement (V8-based)\nSyntaxError: unlabeled break must be inside loop or switch (Firefox)\nSyntaxError: 'break' is only valid inside a switch or loop statement. (Safari)\n

Error type

\n

SyntaxError.

What went wrong?

\n

break statements can be used to exit a loop or a switch statement, and using them elsewhere is a syntax error. Alternatively, you can provide a label to the break statement to break out of any statement with that label — however, if the label does not reference a containing statement, another error SyntaxError: label not found will be thrown.

Examples

\n

Unsyntactic break

\n
\n

break cannot be used outside switch or loops.

\n

js

\n
let score = 0;\n\nfunction increment() {\n  if (score === 100)\n    break; // SyntaxError: unlabeled break must be inside loop or switch\n  }\n  score++;\n}\n
\n

Maybe instead of break, you intend to use return to early-terminate a function.

\n

js

\n
let score = 0;\n\nfunction increment() {\n  if (score === 100) {\n    return;\n  }\n  score++;\n}\n
\n
\n

Using break in callbacks

\n
\n

break cannot be used in callbacks, even if the callback is called from a loop.

\n

js

\n
let containingIndex = 0;\nconst matrix = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9],\n];\n\nwhile (containingIndex < matrix.length) {\n  matrix[containingIndex].forEach((value) => {\n    if (value === 5) {\n      break; // SyntaxError: unlabeled break must be inside loop or switch\n    }\n  });\n  containingIndex++;\n}\n
\n

Instead, refactor the code so the break is used outside the callback.

\n

js

\n
let containingIndex = 0;\nconst matrix = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9],\n];\n\nouter: while (containingIndex < matrix.length) {\n  for (const value of matrix[containingIndex]) {\n    if (value === 5) {\n      break outer;\n    }\n  }\n  containingIndex++;\n}\n
\n
\n

js

\n
let containingIndex = 0;\nconst matrix = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9],\n];\n\nwhile (containingIndex < matrix.length) {\n  if (matrix[containingIndex].includes(5)) {\n    break;\n  }\n  containingIndex++;\n}\n
\n

There's no way to early-terminate a forEach() loop. You can use some() instead, or convert it to a for...of loop.

\n

js

\n
array.forEach((value) => {\n  if (value === 5) {\n    break; // SyntaxError: unlabeled break must be inside loop or switch\n  }\n  // do something with value\n});\n
\n
\n

js

\n
array.some((value) => {\n  if (value === 5) {\n    return true;\n  }\n  // do something with value\n  return false;\n});\n
\n
\n

js

\n
for (const value of array) {\n  if (value === 5) {\n    break;\n  }\n  // do something with value\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_break\n

\n
\n", + "errors/no_properties": "

TypeError: \"x\" has no properties

The JavaScript exception \"null (or undefined) has no properties\" occurs when you attempt to access properties of null and undefined. They don't have any.

\n

Message

\n
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)\nTypeError: null has no properties (Firefox)\nTypeError: undefined has no properties (Firefox)\nTypeError: undefined is not an object (evaluating 'undefined.x') (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n

Both null and undefined, have no properties you could access.

Examples

\n

null and undefined have no properties

\n
\n

js

\n
null.foo;\n// TypeError: null has no properties\n\nundefined.bar;\n// TypeError: undefined has no properties\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/No_properties\n

\n
\n", + "errors/unexpected_type": "

TypeError: \"x\" is (not) \"y\"

The JavaScript exception \"x is (not) y\" occurs when there was an unexpected type. Oftentimes, unexpected undefined or null values.

\n

Message

\n
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)\nTypeError: \"x\" is undefined (Firefox)\nTypeError: \"undefined\" is not an object (Firefox)\nTypeError: undefined is not an object (evaluating 'obj.x') (Safari)\n\nTypeError: \"x\" is not a symbol (V8-based & Firefox)\nTypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n
\n

There was an unexpected type. This occurs oftentimes with undefined or null values.

Also, certain methods, such as Object.create() or Symbol.keyFor(), require a specific type, that must be provided.

\n

Examples

\n

Invalid cases

\n
\n

You cannot invoke a method on an undefined or null variable.

\n

js

\n
const foo = undefined;\nfoo.substring(1); // TypeError: foo is undefined\n\nconst foo2 = null;\nfoo2.substring(1); // TypeError: foo is null\n
\n

Certain methods might require a specific type.

\n

js

\n
const foo = {};\nSymbol.keyFor(foo); // TypeError: foo is not a symbol\n\nconst foo2 = \"bar\";\nObject.create(foo2); // TypeError: \"foo\" is not an object or null\n
\n
\n

Fixing the issue

\n
\n

To fix null pointer to undefined or null values, you can test if the value is undefined or null first.

\n

js

\n
if (foo !== undefined && foo !== null) {\n  // Now we know that foo is defined, we are good to go.\n}\n
\n

Or, if you are confident that foo will not be another falsy value like \"\" or 0, or if filtering those cases out is not an issue, you can simply test for its truthiness.

\n

js

\n
if (foo) {\n  // Now we know that foo is truthy, it will necessarily not be null/undefined.\n}\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type\n

\n
\n", + "errors/not_a_constructor": "

TypeError: \"x\" is not a constructor

The JavaScript exception \"is not a constructor\" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor.

\n

Message

\n
TypeError: x is not a constructor (V8-based & Firefox & Safari)\n

Error type

\n
TypeError

What went wrong?

\n
\n

There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is.

There are many global objects, like String or Array, which are constructable using new. However, some global objects are not and their properties and methods are static. The following JavaScript standard built-in objects are not a constructor: Math, JSON, Symbol, Reflect, Intl, Atomics.

Generator functions cannot be used as constructors either.

\n

Examples

\n

Invalid cases

\n
\n

js

\n
const Car = 1;\nnew Car();\n// TypeError: Car is not a constructor\n\nnew Math();\n// TypeError: Math is not a constructor\n\nnew Symbol();\n// TypeError: Symbol is not a constructor\n\nfunction* f() {}\nconst obj = new f();\n// TypeError: f is not a constructor\n
\n

A car constructor

\n
\n

Suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

\n

js

\n
function Car(make, model, year) {\n  this.make = make;\n  this.model = model;\n  this.year = year;\n}\n
\n

Now you can create an object called mycar as follows:

\n

js

\n
const mycar = new Car(\"Eagle\", \"Talon TSi\", 1993);\n
\n
\n

In Promises

\n
\n

When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it. Instead, use the Promise.resolve() or Promise.reject() static methods.

This is not legal (the Promise constructor is not being called correctly) and will throw a TypeError: this is not a constructor exception:

\n

js

\n
const fn = () => {\n  return new Promise.resolve(true);\n};\n
\n

This is legal, but unnecessarily long:

\n

js

\n
const fn = () => {\n  return new Promise((resolve, reject) => {\n    resolve(true);\n  });\n};\n
\n

Instead, return the static method:

\n

js

\n
const resolveAlways = () => {\n  return Promise.resolve(true);\n};\n\nconst rejectAlways = () => {\n  return Promise.reject(false);\n};\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_constructor\n

\n
\n", + "errors/not_a_function": "

TypeError: \"x\" is not a function

The JavaScript exception \"is not a function\" occurs when there was an attempt to call a value from a function, but the value is not actually a function.

\n

Message

\n
TypeError: \"x\" is not a function. (V8-based & Firefox & Safari)\n

Error type

\n
TypeError

What went wrong?

\n
\n

It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:

\n

Examples

\n

A typo in the function name

\n
\n

In this case, which happens way too often, there is a typo in the method name:

\n

js

\n
const x = document.getElementByID(\"foo\");\n// TypeError: document.getElementByID is not a function\n
\n

The correct function name is getElementById:

\n

js

\n
const x = document.getElementById(\"foo\");\n
\n
\n

Function called on the wrong object

\n
\n

For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, Array.prototype.map() is used, which will work with Array objects only.

\n

js

\n
const obj = { a: 13, b: 37, c: 42 };\n\nobj.map(function (num) {\n  return num * 2;\n});\n\n// TypeError: obj.map is not a function\n
\n

Use an array instead:

\n

js

\n
const numbers = [1, 4, 9];\n\nnumbers.map(function (num) {\n  return num * 2;\n}); // [2, 8, 18]\n
\n
\n

Function shares a name with a pre-existing property

\n
\n

Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.

\n

js

\n
function Dog() {\n  this.age = 11;\n  this.color = \"black\";\n  this.name = \"Ralph\";\n  return this;\n}\n\nDog.prototype.name = function (name) {\n  this.name = name;\n  return this;\n};\n\nconst myNewDog = new Dog();\nmyNewDog.name(\"Cassidy\"); //Uncaught TypeError: myNewDog.name is not a function\n
\n

Use a different property name instead:

\n

js

\n
function Dog() {\n  this.age = 11;\n  this.color = \"black\";\n  this.dogName = \"Ralph\"; //Using this.dogName instead of .name\n  return this;\n}\n\nDog.prototype.name = function (name) {\n  this.dogName = name;\n  return this;\n};\n\nconst myNewDog = new Dog();\nmyNewDog.name(\"Cassidy\"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }\n
\n
\n

Using parenthese for multiplication

\n
\n

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

\n

js

\n
const sixteen = 2(3 + 5);\nconsole.log(`2 x (3 + 5) is ${sixteen}`);\n// Uncaught TypeError: 2 is not a function\n
\n

You can correct the code by adding a * operator:

\n

js

\n
const sixteen = 2 * (3 + 5);\nconsole.log(`2 x (3 + 5) is ${sixteen}`);\n// 2 x (3 + 5) is 16\n
\n
\n

Import the exported module correctly

\n
\n

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

\n

js

\n
const helpers = function () {};\n\nhelpers.groupBy = function (objectArray, property) {\n  return objectArray.reduce((acc, obj) => {\n    const key = obj[property];\n    acc[key] ??= [];\n    acc[key].push(obj);\n    return acc;\n  }, {});\n};\n\nexport default helpers;\n
\n

The correct import usage (App.js):

\n

js

\n
import helpers from \"./helpers\";\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function\n

\n
\n", + "errors/no_non-null_object": "

TypeError: \"x\" is not a non-null object

The JavaScript exception \"is not a non-null object\" occurs when an object is expected somewhere and wasn't provided. null is not an object and won't work.

\n

Message

\n
TypeError: Property description must be an object: x (V8-based)\nTypeError: Property descriptor must be an object, got \"x\" (Firefox)\nTypeError: Property description must be an object. (Safari)\n\nTypeError: Invalid value used in weak set (V8-based)\nTypeError: WeakSet value must be an object, got \"x\" (Firefox)\nTypeError: Attempted to add a non-object value to a WeakSet (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

An object is expected somewhere and wasn't provided. null is not an object and won't work. You must provide a proper object in the given situation.

Examples

\n

Property descriptor expected

\n
\n

When methods like Object.create() or Object.defineProperty() and Object.defineProperties() are used, the optional descriptor parameter expects a property descriptor object. Providing no object (like just a number), will throw an error:

\n

js

\n
Object.defineProperty({}, \"key\", 1);\n// TypeError: 1 is not a non-null object\n\nObject.defineProperty({}, \"key\", null);\n// TypeError: null is not a non-null object\n
\n

A valid property descriptor object might look like this:

\n

js

\n
Object.defineProperty({}, \"key\", { value: \"foo\", writable: false });\n
\n
\n

WeakMap and WeakSet objects require object or symbol keys

\n
\n

WeakMap and WeakSet objects store object or symbol keys. You can't use other types as keys.

\n

js

\n
const ws = new WeakSet();\nws.add(\"foo\");\n// TypeError: \"foo\" is not a non-null object\n
\n

Use objects instead:

\n

js

\n
ws.add({ foo: \"bar\" });\nws.add(window);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/No_non-null_object\n

\n
\n", + "errors/read-only": "

TypeError: \"x\" is read-only

The JavaScript strict mode-only exception \"is read-only\" occurs when a global variable or object property that was assigned to is a read-only property.

\n

Message

\n
TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)\nTypeError: \"x\" is read-only (Firefox)\nTypeError: Attempted to assign to readonly property. (Safari)\n

Error type

\n

TypeError in strict mode only.

What went wrong?

\n
\n

The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.)

This error happens only in strict mode code. In non-strict code, the assignment is silently ignored.

\n

Examples

\n

Invalid cases

\n
\n

Read-only properties are not super common, but they can be created using Object.defineProperty() or Object.freeze().

\n

js

\n
\"use strict\";\nconst obj = Object.freeze({ name: \"Elsa\", score: 157 });\nobj.score = 0; // TypeError\n\n(\"use strict\");\nObject.defineProperty(this, \"LUNG_COUNT\", { value: 2, writable: false });\nLUNG_COUNT = 3; // TypeError\n\n(\"use strict\");\nconst frozenArray = Object.freeze([0, 1, 2]);\nfrozenArray[0]++; // TypeError\n
\n

There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant.

\n

js

\n
\"use strict\";\nMath.PI = 4; // TypeError\n
\n

Sorry, you can't do that.

The global variable undefined is also read-only, so you can't silence the infamous \"undefined is not a function\" error by doing this:

\n

js

\n
\"use strict\";\nundefined = function () {}; // TypeError: \"undefined\" is read-only\n
\n
\n

Valid cases

\n
\n

js

\n
\"use strict\";\nlet obj = Object.freeze({ name: \"Score\", points: 157 });\nobj = { name: obj.name, points: 0 }; // replacing it with a new object works\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Read-only\n

\n
\n", + "errors/is_not_iterable": "

TypeError: 'x' is not iterable

The JavaScript exception \"is not iterable\" occurs when the value which is given as the right-hand side of for...of, as argument of a function such as Promise.all or TypedArray.from, or as the right-hand side of an array destructuring assignment, is not an iterable object.

\n

Message

\n
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) (V8-based)\nTypeError: x is not iterable (Firefox)\nTypeError: undefined is not a function (near '...[x]...') (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

The value which is given as the right-hand side of for...of, or as argument of a function such as Promise.all or TypedArray.from, or as the right-hand side of an array destructuring assignment, is not an iterable object. An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol.

Examples

\n

Array destructuring a non-iterable

\n
\n
\n

js

\n
const myobj = { arrayOrObjProp1: {}, arrayOrObjProp2: [42] };\n\nconst {\n  arrayOrObjProp1: [value1],\n  arrayOrObjProp2: [value2],\n} = myobj; // TypeError: object is not iterable\n\nconsole.log(value1, value2);\n
\n

The non-iterable might turn to be undefined in some runtime environments.

\n

Iterating over Object properties

\n
\n

In JavaScript, Objects are not iterable unless they implement the iterable protocol. Therefore, you cannot use for...of to iterate over the properties of an object.

\n

js

\n
const obj = { France: \"Paris\", England: \"London\" };\nfor (const p of obj) {\n  // …\n} // TypeError: obj is not iterable\n
\n

Instead you have to use Object.keys or Object.entries, to iterate over the properties or entries of an object.

\n

js

\n
const obj = { France: \"Paris\", England: \"London\" };\n// Iterate over the property names:\nfor (const country of Object.keys(obj)) {\n  const capital = obj[country];\n  console.log(country, capital);\n}\n\nfor (const [country, capital] of Object.entries(obj)) {\n  console.log(country, capital);\n}\n
\n

Another option for this use case might be to use a Map:

\n

js

\n
const map = new Map();\nmap.set(\"France\", \"Paris\");\nmap.set(\"England\", \"London\");\n// Iterate over the property names:\nfor (const country of map.keys()) {\n  const capital = map.get(country);\n  console.log(country, capital);\n}\n\nfor (const capital of map.values()) {\n  console.log(capital);\n}\n\nfor (const [country, capital] of map.entries()) {\n  console.log(country, capital);\n}\n
\n
\n

Iterating over a generator

\n
\n

Generator functions are functions you call to produce an iterable object.

\n

js

\n
function* generate(a, b) {\n  yield a;\n  yield b;\n}\n\nfor (const x of generate) {\n  console.log(x);\n} // TypeError: generate is not iterable\n
\n

When they are not called, the Function object corresponding to the generator is callable, but not iterable. Calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator.

\n

js

\n
function* generate(a, b) {\n  yield a;\n  yield b;\n}\n\nfor (const x of generate(1, 2)) {\n  console.log(x);\n}\n
\n
\n

Iterating over a custom iterable

\n
\n

Custom iterables can be created by implementing the Symbol.iterator method. You must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method.

\n

js

\n
const myEmptyIterable = {\n  [Symbol.iterator]() {\n    return []; // [] is iterable, but it is not an iterator — it has no next method.\n  },\n};\n\nArray.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable\n
\n

Here is a correct implementation:

\n

js

\n
const myEmptyIterable = {\n  [Symbol.iterator]() {\n    return [][Symbol.iterator]();\n  },\n};\n\nArray.from(myEmptyIterable); // []\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/is_not_iterable\n

\n
\n", + "errors/more_arguments_needed": "

TypeError: More arguments needed

The JavaScript exception \"more arguments needed\" occurs when there is an error with how a function is called. More arguments need to be provided.

\n

Message

\n
TypeError: Object prototype may only be an Object or null: undefined (V8-based)\nTypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox)\nTypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox)\nTypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox)\nTypeError: Object prototype may only be an Object or null. (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n

There is an error with how a function is called. More arguments need to be provided.

Examples

\n

Required arguments not provided

\n
\n

The Object.create() method requires at least one argument and the Object.setPrototypeOf() method requires at least two arguments:

\n

js

\n
const obj = Object.create();\n// TypeError: Object.create requires at least 1 argument, but only 0 were passed\n\nconst obj2 = Object.setPrototypeOf({});\n// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed\n
\n

You can fix this by setting null as the prototype, for example:

\n

js

\n
const obj = Object.create(null);\n\nconst obj2 = Object.setPrototypeOf({}, null);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/More_arguments_needed\n

\n
\n", + "errors/unterminated_string_literal": "

SyntaxError: unterminated string literal

The JavaScript error \"unterminated string literal\" occurs when there is an unterminated string literal somewhere. String literals must be enclosed by single (') or double (\") quotes.

\n

Message

\n
SyntaxError: Unterminated string constant (Edge)\nSyntaxError: unterminated string literal (Firefox)\n

Error type

\n
SyntaxError

What went wrong?

\n
\n

There is an unterminated string literal somewhere. String literals must be enclosed by single (') or double (\") quotes. JavaScript makes no distinction between single-quoted strings and double-quoted strings. Escape sequences work in strings created with either single or double quotes. To fix this error, check if:

\n

Examples

\n

Multiple lines

\n
\n

You can't split a string across multiple lines like this in JavaScript:

\n

js

\n
const longString = \"This is a very long string which needs\n                    to wrap across multiple lines because\n                    otherwise my code is unreadable.\";\n// SyntaxError: unterminated string literal\n
\n

Instead, use the + operator, a backslash, or template literals. The + operator variant looks like this:

\n

js

\n
const longString =\n  \"This is a very long string which needs \" +\n  \"to wrap across multiple lines because \" +\n  \"otherwise my code is unreadable.\";\n
\n

Or you can use the backslash character (\"\\\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

\n

js

\n
const longString =\n  \"This is a very long string which needs \\\nto wrap across multiple lines because \\\notherwise my code is unreadable.\";\n
\n

Another possibility is to use template literals.

\n

js

\n
const longString = `This is a very long string which needs \nto wrap across multiple lines because \notherwise my code is unreadable.`;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal\n

\n
\n", + "errors/reduce_of_empty_array_with_no_initial_value": "

TypeError: Reduce of empty array with no initial value

The JavaScript exception \"reduce of empty array with no initial value\" occurs when a reduce function is used.

\n

Message

\n
TypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)\n

Error type

\n
TypeError

What went wrong?

\n
\n

In JavaScript, there are several reduce functions:

These functions optionally take an initialValue (which will be used as the first argument to the first call of the callback). However, if no initial value is provided, it will use the first element of the Array or TypedArray as the initial value. This error is raised when an empty array is provided because no initial value can be returned in that case.

\n

Examples

\n

Invalid cases

\n
\n

This problem appears frequently when combined with a filter (Array.prototype.filter(), TypedArray.prototype.filter()) which will remove all elements of the list. Thus leaving none to be used as the initial value.

\n

js

\n
const ints = [0, -1, -2, -3, -4, -5];\nints\n  .filter((x) => x > 0) // removes all elements\n  .reduce((x, y) => x + y); // no more elements to use for the initial value.\n
\n

Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:

\n

js

\n
const names = document.getElementsByClassName(\"names\");\nconst name_list = Array.prototype.reduce.call(\n  names,\n  (acc, name) => acc + \", \" + name,\n);\n
\n
\n

Valid cases

\n
\n

These problems can be solved in two different ways.

One way is to actually provide an initialValue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.

\n

js

\n
const ints = [0, -1, -2, -3, -4, -5];\nints\n  .filter((x) => x > 0) // removes all elements\n  .reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition\n
\n

Another way would be to handle the empty case, either before calling reduce, or in the callback after adding an unexpected dummy initial value.

\n

js

\n
const names = document.getElementsByClassName(\"names\");\n\nlet nameList1 = \"\";\nif (names.length >= 1) {\n  nameList1 = Array.prototype.reduce.call(\n    names,\n    (acc, name) => `${acc}, ${name}`,\n  );\n}\n// nameList1 === \"\" when names is empty.\n\nconst nameList2 = Array.prototype.reduce.call(\n  names,\n  (acc, name) => {\n    if (acc === \"\")\n      // initial value\n      return name;\n    return `${acc}, ${name}`;\n  },\n  \"\",\n);\n// nameList2 === \"\" when names is empty.\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value\n

\n
\n", + "errors/called_on_incompatible_type": "

TypeError: X.prototype.y called on incompatible type

The JavaScript exception \"called on incompatible target (or object)\" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function.

\n

Message

\n
TypeError: Method Set.prototype.add called on incompatible receiver undefined (V8-based)\nTypeError: Bind must be called on a function (V8-based)\nTypeError: Function.prototype.toString called on incompatible object (Firefox)\nTypeError: Function.prototype.bind called on incompatible target (Firefox)\nTypeError: Type error (Safari)\nTypeError: undefined is not an object (Safari)\n

Error type

\n
TypeError

What went wrong?

\n
\n

When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function.

This issue can arise when using the Function.prototype.call() or Function.prototype.apply() methods, and providing a this argument which does not have the expected type.

This issue can also happen when providing a function that is stored as a property of an object as an argument to another function. In this case, the object that stores the function won't be the this target of that function when it is called by the other function. To work-around this issue, you will either need to provide a lambda which is making the call, or use the Function.prototype.bind() function to force the this argument to the expected object.

\n

Examples

\n

Invalid cases

\n
\n

js

\n
const mySet = new Set();\n[\"bar\", \"baz\"].forEach(mySet.add);\n// mySet.add is a function, but \"mySet\" is not captured as this.\n\nconst myFun = function () {\n  console.log(this);\n};\n[\"bar\", \"baz\"].forEach(myFun.bind);\n// myFun.bind is a function, but \"myFun\" is not captured as this.\n
\n

Valid cases

\n
\n

js

\n
const mySet = new Set();\n[\"bar\", \"baz\"].forEach(mySet.add.bind(mySet));\n// This works due to binding \"mySet\" as this.\n\nconst myFun = function () {\n  console.log(this);\n};\n[\"bar\", \"baz\"].forEach((x) => myFun.bind(x));\n// This works using the \"bind\" function. It creates a lambda forwarding the argument.\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type\n

\n
\n", + "errors/cant_assign_to_property": "

TypeError: can't assign to property \"x\" on \"y\": not an object

The JavaScript strict mode exception \"can't assign to property\" occurs when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

\n

Message

\n
TypeError: Cannot create property 'x' on number '1' (V8-based)\nTypeError: can't assign to property \"x\" on 1: not an object (Firefox)\nTypeError: Attempted to assign to readonly property. (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n
\n

In strict mode, a TypeError is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

The problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a String or a Number is expected.

\n

Examples

\n

Invalid cases

\n
\n

js

\n
\"use strict\";\n\nconst foo = \"my string\";\n// The following line does nothing if not in strict mode.\nfoo.bar = {}; // TypeError: can't assign to property \"bar\" on \"my string\": not an object\n
\n

Fixing the issue

\n
\n

Either fix the code to prevent the primitive from being used in such places, or fix the issue by creating the object equivalent Object.

\n

js

\n
\"use strict\";\n\nconst foo = new String(\"my string\");\nfoo.bar = {};\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_assign_to_property\n

\n
\n", + "errors/cant_convert_bigint_to_number": "

TypeError: can't convert BigInt to number

The JavaScript exception \"can't convert BigInt to number\" occurs when an arithmetic operation involves a mix of BigInt and Number values.

\n

Message

\n
TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based)\nTypeError: BigInts have no unsigned right shift, use >> instead (V8-based)\nTypeError: can't convert BigInt to number (Firefox)\nTypeError: Invalid mix of BigInt and other type in addition/multiplication/…. (Safari)\nTypeError: BigInt does not support >>> operator (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n
\n

The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.

The error can also happen if the unsigned right shift operator (>>>) is used between two BigInts. In Firefox, the message is the same: \"can't convert BigInt to number\".

\n

Examples

\n

Mixing numbers and BigInts in operations

\n
\n
\n

js

\n
const sum = 1n + 1;\n// TypeError: can't convert BigInt to number\n
\n

Instead, explicitly coerce one side to a BigInt or number.

\n

js

\n
const sum = 1n + BigInt(1);\nconst sum2 = Number(1n) + 1;\n
\n
\n

Using unsigned right shift on BigInts

\n
\n
\n

js

\n
const a = 4n >>> 2n;\n// TypeError: can't convert BigInt to number\n
\n

Use normal right shift instead.

\n

js

\n
const a = 4n >> 2n;\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_convert_BigInt_to_number\n

\n
\n", + "errors/cant_convert_x_to_bigint": "

TypeError: can't convert x to BigInt

The JavaScript exception \"x can't be converted to BigInt\" occurs when attempting to convert a Symbol, null, or undefined value to a BigInt, or if an operation expecting a BigInt parameter receives a number.

\n

Message

\n
TypeError: Cannot convert null to a BigInt (V8-based)\nTypeError: can't convert null to BigInt (Firefox)\nTypeError: Invalid argument type in ToBigInt operation (Safari)\n

Error type

\n

TypeError.

What went wrong?

\n
\n

When using the BigInt() function to convert a value to a BigInt, the value would first be converted to a primitive. Then, if it's not one of BigInt, string, number, and boolean, the error is thrown.

Some operations, like BigInt.asIntN, require the parameter to be a BigInt. Passing in a number in this case will also throw this error.

\n

Examples

\n

Using BigInt() on invalid values

\n
\n
\n

js

\n
const a = BigInt(null);\n// TypeError: can't convert null to BigInt\nconst b = BigInt(undefined);\n// TypeError: can't convert undefined to BigInt\nconst c = BigInt(Symbol(\"1\"));\n// TypeError: can't convert Symbol(\"1\") to BigInt\n
\n
\n

js

\n
const a = BigInt(1);\nconst b = BigInt(true);\nconst c = BigInt(\"1\");\nconst d = BigInt(Symbol(\"1\").description);\n
\n

Note: Simply coercing the value to a string or number using String() or Number() before passing it to BigInt() is usually not sufficient to avoid all errors. If the string is not a valid integer number string, a SyntaxError is thrown; if the number is not an integer (most notably, NaN), a RangeError is thrown. If the range of input is unknown, properly validate it before using BigInt().

\n

Passing a number to a function expecting a BigInt

\n
\n
\n

js

\n
const a = BigInt.asIntN(4, 8);\n// TypeError: can't convert 8 to BigInt\nconst b = new BigInt64Array(3).fill(3);\n// TypeError: can't convert 3 to BigInt\n
\n
\n

js

\n
const a = BigInt.asIntN(4, 8n);\nconst b = new BigInt64Array(3).fill(3n);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_convert_x_to_BigInt\n

\n
\n", + "errors/cant_define_property_object_not_extensible": "

TypeError: can't define property \"x\": \"obj\" is not extensible

The JavaScript exception \"can't define property \"x\": \"obj\" is not extensible\" occurs when Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

\n

Message

\n
TypeError: Cannot add property x, object is not extensible (V8-based)\nTypeError: Cannot define property x, object is not extensible (V8-based)\nTypeError: can't define property \"x\": Object is not extensible (Firefox)\nTypeError: Attempting to define property on object that is not extensible. (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

Usually, an object is extensible and new properties can be added to it. However, in this case Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

Examples

\n

Adding new properties to a non-extensible objects

\n
\n

In strict mode, attempting to add new properties to a non-extensible object throws a TypeError. In sloppy mode, the addition of the \"x\" property is silently ignored.

\n

js

\n
\"use strict\";\n\nconst obj = {};\nObject.preventExtensions(obj);\n\nobj.x = \"foo\";\n// TypeError: can't define property \"x\": Object is not extensible\n
\n

In both, strict mode and sloppy mode, a call to Object.defineProperty() throws when adding a new property to a non-extensible object.

\n

js

\n
const obj = {};\nObject.preventExtensions(obj);\n\nObject.defineProperty(obj, \"x\", { value: \"foo\" });\n// TypeError: can't define property \"x\": Object is not extensible\n
\n

To fix this error, you will either need to remove the call to Object.preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

\n

js

\n
\"use strict\";\n\nconst obj = {};\nobj.x = \"foo\"; // add property first and only then prevent extensions\n\nObject.preventExtensions(obj);\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible\n

\n
\n", + "errors/non_configurable_array_element": "

TypeError: can't delete non-configurable array element

The JavaScript exception \"can't delete non-configurable array element\" occurs when it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.

\n

Message

\n
TypeError: Cannot delete property '1' of [object Array] (V8-based)\nTypeError: can't delete non-configurable array element (Firefox)\nTypeError: Unable to delete property. (Safari)\n

Error type

\n
TypeError

What went wrong?

\n
\n

It was attempted to shorten the length of an array, but one of the array's elements is non-configurable. When shortening an array, the elements beyond the new array length will be deleted, which failed in this situation.

The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

Usually, properties in an object created by an array initializer are configurable. However, for example, when using Object.defineProperty(), the property isn't configurable by default.

\n

Examples

\n

Non-configurable properties created by Object.defineProperty

\n
\n

The Object.defineProperty() creates non-configurable properties by default if you haven't specified them as configurable.

\n

js

\n
\"use strict\";\nconst arr = [];\nObject.defineProperty(arr, 0, { value: 0 });\nObject.defineProperty(arr, 1, { value: \"1\" });\n\narr.length = 1;\n// TypeError: can't delete non-configurable array element\n
\n

You will need to set the elements as configurable, if you intend to shorten the array.

\n

js

\n
\"use strict\";\nconst arr = [];\nObject.defineProperty(arr, 0, { value: 0, configurable: true });\nObject.defineProperty(arr, 1, { value: \"1\", configurable: true });\n\narr.length = 1;\n
\n
\n

Sealed Arrays

\n
\n

The Object.seal() function marks all existing elements as non-configurable.

\n

js

\n
\"use strict\";\nconst arr = [1, 2, 3];\nObject.seal(arr);\n\narr.length = 1;\n// TypeError: can't delete non-configurable array element\n
\n

You either need to remove the Object.seal() call, or make a copy of it. In case of a copy, shortening the copy of the array does not modify the original array length.

\n

js

\n
\"use strict\";\nconst arr = [1, 2, 3];\nObject.seal(arr);\n\n// Copy the initial array to shorten the copy\nconst copy = Array.from(arr);\ncopy.length = 1;\n// arr.length === 3\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Non_configurable_array_element\n

\n
\n", + "errors/cant_redefine_property": "

TypeError: can't redefine non-configurable property \"x\"

The JavaScript exception \"can't redefine non-configurable property\" occurs when it was attempted to redefine a property, but that property is non-configurable.

\n

Message

\n
TypeError: Cannot redefine property: \"x\" (V8-based)\nTypeError: can't redefine non-configurable property \"x\" (Firefox)\nTypeError: Attempting to change value of a readonly property. (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

It was attempted to redefine a property, but that property is non-configurable. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. Usually, properties in an object created by an object initializer are configurable. However, for example, when using Object.defineProperty(), the property isn't configurable by default.

Examples

\n

Non-configurable properties created by Object.defineProperty

\n
\n

The Object.defineProperty() creates non-configurable properties if you haven't specified them as configurable.

\n

js

\n
const obj = Object.create({});\nObject.defineProperty(obj, \"foo\", { value: \"bar\" });\n\nObject.defineProperty(obj, \"foo\", { value: \"baz\" });\n// TypeError: can't redefine non-configurable property \"foo\"\n
\n

You will need to set the \"foo\" property to configurable, if you intend to redefine it later in the code.

\n

js

\n
const obj = Object.create({});\nObject.defineProperty(obj, \"foo\", { value: \"bar\", configurable: true });\nObject.defineProperty(obj, \"foo\", { value: \"baz\", configurable: true });\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_redefine_property\n

\n
\n", + "errors/in_operator_no_object": "

TypeError: cannot use 'in' operator to search for 'x' in 'y'

The JavaScript exception \"right-hand side of 'in' should be an object\" occurs when the in operator was used to search in strings, or in numbers, or other primitive types. It can only be used to check if a property is in an object.

\n

Message

\n
TypeError: Cannot use 'in' operator to search for 'x' in 'y' (V8-based & Firefox)\nTypeError: right-hand side of 'in' should be an object, got null (Firefox)\nTypeError: \"y\" is not an Object. (evaluating '\"x\" in \"y\"') (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

The in operator can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types.

Examples

\n

Searching in strings

\n
\n

Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator.

\n

js

\n
\"Hello\" in \"Hello World\";\n// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'\n
\n

Instead you will need to use String.prototype.includes(), for example.

\n

js

\n
\"Hello World\".includes(\"Hello\");\n// true\n
\n
\n

The operand can't be null or undefined

\n
\n

Make sure the object you are inspecting isn't actually null or undefined.

\n

js

\n
const foo = null;\n\"bar\" in foo;\n// TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome)\n// TypeError: right-hand side of 'in' should be an object, got null (Firefox)\n
\n

The in operator always expects an object.

\n

js

\n
const foo = { baz: \"bar\" };\n\"bar\" in foo; // false\n\n\"PI\" in Math; // true\n\"pi\" in Math; // false\n
\n
\n

Searching in arrays

\n
\n

Be careful when using the in operator to search in Array objects. The in operator checks the index number, not the value at that index.

\n

js

\n
const trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\n3 in trees; // true\n\"oak\" in trees; // false\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/in_operator_no_object\n

\n
\n", + "errors/cyclic_object_value": "

TypeError: cyclic object value

The JavaScript exception \"cyclic object value\" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly.

\n

Message

\n
TypeError: Converting circular structure to JSON (V8-based)\nTypeError: cyclic object value (Firefox)\nTypeError: JSON.stringify cannot serialize cyclic structures. (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

The JSON format per se doesn't support object references (although an IETF draft exists), hence JSON.stringify() doesn't try to solve them and fails accordingly.

Examples

\n

Circular references

\n
\n

In a circular structure like the following

\n

js

\n
const circularReference = { otherData: 123 };\ncircularReference.myself = circularReference;\n
\n

JSON.stringify() will fail

\n

js

\n
JSON.stringify(circularReference);\n// TypeError: cyclic object value\n
\n

To serialize circular references you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

The snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of JSON.stringify():

\n

js

\n
function getCircularReplacer() {\n  const ancestors = [];\n  return function (key, value) {\n    if (typeof value !== \"object\" || value === null) {\n      return value;\n    }\n    // `this` is the object that value is contained in,\n    // i.e., its direct parent.\n    while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n      ancestors.pop();\n    }\n    if (ancestors.includes(value)) {\n      return \"[Circular]\";\n    }\n    ancestors.push(value);\n    return value;\n  };\n}\n\nJSON.stringify(circularReference, getCircularReplacer());\n// {\"otherData\":123,\"myself\":\"[Circular]\"}\n\nconst o = {};\nconst notCircularReference = [o, o];\nJSON.stringify(notCircularReference, getCircularReplacer());\n// [{},{}]\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value\n

\n
\n", + "errors/invalid_right_hand_side_instanceof_operand": "

TypeError: invalid 'instanceof' operand 'x'

The JavaScript exception \"invalid 'instanceof' operand\" occurs when the right-hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable.

\n

Message

\n
TypeError: Right-hand side of 'instanceof' is not an object (V8-based)\nTypeError: Right-hand side of 'instanceof' is not callable (V8-based)\nTypeError: invalid 'instanceof' operand \"x\" (Firefox)\nTypeError: ({}) is not a function (Firefox)\nTypeError: Right hand side of instanceof is not an object (Safari)\nTypeError: {} is not a function. (evaluating '\"x\" instanceof {}') (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

The instanceof operator expects the right-hand-side operands to be a constructor object, i.e. an object which has a prototype property and is callable. It can also be an object with a Symbol.hasInstance method.

Examples

\n

instanceof vs. typeof

\n
\n
\n

js

\n
\"test\" instanceof \"\"; // TypeError: invalid 'instanceof' operand \"\"\n42 instanceof 0; // TypeError: invalid 'instanceof' operand 0\n\nfunction Foo() {}\nconst f = Foo(); // Foo() is called and returns undefined\nconst x = new Foo();\n\nx instanceof f; // TypeError: invalid 'instanceof' operand f\nx instanceof x; // TypeError: x is not a function\n
\n

To fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation.

\n

js

\n
typeof \"test\" === \"string\"; // true\ntypeof 42 === \"number\"; // true\n\nfunction Foo() {}\nconst f = Foo; // Do not call Foo.\nconst x = new Foo();\n\nx instanceof f; // true\nx instanceof Foo; // true\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand\n

\n
\n", + "errors/array_sort_argument": "

TypeError: invalid Array.prototype.sort argument

The JavaScript exception \"invalid Array.prototype.sort argument\" occurs when the argument of Array.prototype.sort() isn't either undefined or a function which compares its operands.

\n

Message

\n
TypeError: The comparison function must be either a function or undefined (V8-based)\nTypeError: invalid Array.prototype.sort argument (Firefox)\nTypeError: Array.prototype.sort requires the comparator argument to be a function or undefined (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

The argument of Array.prototype.sort() is expected to be either undefined or a function which compares its operands.

Examples

\n

Invalid cases

\n
\n

js

\n
[1, 3, 2].sort(5); // TypeError\n
\n

Valid cases

\n
\n

js

\n
[1, 3, 2].sort(); // [1, 2, 3]\n[1, 3, 2].sort((a, b) => a - b); // [1, 2, 3]\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Array_sort_argument\n

\n
\n", + "errors/invalid_const_assignment": "

TypeError: invalid assignment to const \"x\"

The JavaScript exception \"invalid assignment to const\" occurs when it was attempted to alter a constant value. JavaScript const declarations can't be re-assigned or redeclared.

\n

Message

\n
TypeError: Assignment to constant variable. (V8-based)\nTypeError: invalid assignment to const 'x' (Firefox)\nTypeError: Attempted to assign to readonly property. (Safari)\n

Error type

\n
TypeError

What went wrong?

\n

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword.

Examples

\n

Invalid redeclaration

\n
\n

Assigning a value to the same constant name in the same block-scope will throw.

\n

js

\n
const COLUMNS = 80;\n\n// …\n\nCOLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'\n
\n
\n

Fixing the error

\n
\n

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

Rename

If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.

\n

js

\n
const COLUMNS = 80;\nconst WIDE_COLUMNS = 120;\n
\n

const, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var.

\n

js

\n
let columns = 80;\n\n// …\n\ncolumns = 120;\n
\n

Scoping

Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?

\n

js

\n
const COLUMNS = 80;\n\nfunction setupBigScreenEnvironment() {\n  const COLUMNS = 120;\n}\n
\n
\n

const and immutability

\n
\n

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:

\n

js

\n
const obj = { foo: \"bar\" };\nobj = { foo: \"baz\" }; // TypeError: invalid assignment to const `obj'\n
\n

But you can mutate the properties in a variable:

\n

js

\n
obj.foo = \"baz\";\nobj; // { foo: \"baz\" }\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_const_assignment\n

\n
\n", + "errors/cant_delete": "

TypeError: property \"x\" is non-configurable and can't be deleted

The JavaScript exception \"property is non-configurable and can't be deleted\" occurs when it was attempted to delete a property, but that property is non-configurable.

\n

Message

\n
TypeError: Cannot delete property 'x' of #<Object> (V8-based)\nTypeError: property \"x\" is non-configurable and can't be deleted (Firefox)\nTypeError: Unable to delete property. (Safari)\n

Error type

\n

TypeError in strict mode only.

What went wrong?

\n
\n

It was attempted to delete a property, but that property is non-configurable. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

This error happens only in strict mode code. In non-strict code, the operation returns false.

\n

Examples

\n

Attempting to delete non-configurable properties

\n
\n

Non-configurable properties are not super common, but they can be created using Object.defineProperty() or Object.freeze().

\n

js

\n
\"use strict\";\nconst obj = Object.freeze({ name: \"Elsa\", score: 157 });\ndelete obj.score; // TypeError\n
\n
\n

js

\n
\"use strict\";\nconst obj = {};\nObject.defineProperty(obj, \"foo\", { value: 2, configurable: false });\ndelete obj.foo; // TypeError\n
\n
\n

js

\n
\"use strict\";\nconst frozenArray = Object.freeze([0, 1, 2]);\nfrozenArray.pop(); // TypeError\n
\n

There are also a few non-configurable properties built into JavaScript. Maybe you tried to delete a mathematical constant.

\n

js

\n
\"use strict\";\ndelete Math.PI; // TypeError\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete\n

\n
\n", + "errors/getter_only": "

TypeError: setting getter-only property \"x\"

The JavaScript strict mode-only exception \"setting getter-only property\" occurs when there is an attempt to set a new value to a property for which only a getter is specified.

\n

Message

\n
TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)\nTypeError: setting getter-only property \"x\" (Firefox)\nTypeError: Attempted to assign to readonly property. (Safari)\n

Error type

\n

TypeError in strict mode only.

What went wrong?

\n

There is an attempt to set a new value to a property for which only a getter is specified. While this will be silently ignored in non-strict mode, it will throw a TypeError in strict mode.

Examples

\n

Property with no setter

\n
\n

The example below shows how to set a getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. For more details see also the Object.defineProperty() page.

\n

js

\n
\"use strict\";\n\nfunction Archiver() {\n  const temperature = null;\n  Object.defineProperty(this, \"temperature\", {\n    get() {\n      console.log(\"get!\");\n      return temperature;\n    },\n  });\n}\n\nconst arc = new Archiver();\narc.temperature; // 'get!'\n\narc.temperature = 30;\n// TypeError: setting getter-only property \"temperature\"\n
\n

To fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this:

\n

js

\n
\"use strict\";\n\nfunction Archiver() {\n  let temperature = null;\n  const archive = [];\n\n  Object.defineProperty(this, \"temperature\", {\n    get() {\n      console.log(\"get!\");\n      return temperature;\n    },\n    set(value) {\n      temperature = value;\n      archive.push({ val: temperature });\n    },\n  });\n\n  this.getArchive = function () {\n    return archive;\n  };\n}\n\nconst arc = new Archiver();\narc.temperature; // 'get!'\narc.temperature = 11;\narc.temperature = 13;\narc.getArchive(); // [{ val: 11 }, { val: 13 }]\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only\n

\n
\n", + "errors/malformed_uri": "

URIError: malformed URI sequence

The JavaScript exception \"malformed URI sequence\" occurs when URI encoding or decoding wasn't successful.

\n

Message

\n
URIError: URI malformed (V8-based)\nURIError: malformed URI sequence (Firefox)\nURIError: String contained an illegal UTF-16 sequence. (Safari)\n

Error type

\n
URIError

What went wrong?

\n

URI encoding or decoding wasn't successful. An argument given to either the decodeURI, encodeURI, encodeURIComponent, or decodeURIComponent function was not valid, so that the function was unable encode or decode properly.

Examples

\n

Encoding

\n
\n

Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. An URIError will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example:

\n

js

\n
encodeURI(\"\\uD800\");\n// \"URIError: malformed URI sequence\"\n\nencodeURI(\"\\uDFFF\");\n// \"URIError: malformed URI sequence\"\n
\n

A high-low pair is OK. For example:

\n

js

\n
encodeURI(\"\\uD800\\uDFFF\");\n// \"%F0%90%8F%BF\"\n
\n
\n

Decoding

\n
\n

Decoding replaces each escape sequence in the encoded URI component with the character that it represents. If there isn't such a character, an error will be thrown:

\n

js

\n
decodeURIComponent(\"%E0%A4%A\");\n// \"URIError: malformed URI sequence\"\n
\n

With proper input, this should usually look like something like this:

\n

js

\n
decodeURIComponent(\"JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\");\n// \"JavaScript_шеллы\"\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Malformed_URI\n

\n
\n", + "errors/already_has_pragma": "

Warning: -file- is being assigned a //# sourceMappingURL, but already has one

The JavaScript warning \"-file- is being assigned a //# sourceMappingURL, but already has one.\" occurs when a source map has been specified more than once for a given JavaScript source.

\n

Message

\n
Warning: -file- is being assigned a //# sourceMappingURL, but already has one.\n

Error type

\n

A warning. JavaScript execution won't be halted.

What went wrong?

\n
\n

A source map has been specified more than once for a given JavaScript source.

JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the JavaScript file.

\n

Examples

\n

Setting source maps

\n
\n

Setting a source map by using a comment in the file:

\n

js

\n
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map\n
\n

Or, alternatively, you can set a header to your JavaScript file:

\n

http

\n
X-SourceMap: /path/to/file.js.map\n
\n
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Already_has_pragma\n

\n
\n", + "global_objects/typedarray/includes": "

TypedArray.prototype.includes()

The includes() method of TypedArray instances determines whether a typed array includes a certain value among its entries, returning true or false as appropriate. This method has the same algorithm as Array.prototype.includes().

\n

Try it

\n

Syntax

\n
\n

js

\n
includes(searchElement)\nincludes(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

The value to search for.

\nfromIndex Optional\n

Zero-based index at which to start searching, converted to an integer.

Return value

\n

A boolean value which is true if the value searchElement is found within the typed array (or the part of the typed array indicated by the index fromIndex, if specified).

Description

\n

See Array.prototype.includes() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using includes()

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\nuint8.includes(2); // true\nuint8.includes(4); // false\nuint8.includes(3, 3); // false\n\n// NaN handling (only true for Float32 and Float64)\nnew Uint8Array([NaN]).includes(NaN); // false, since the NaN passed to the constructor gets converted to 0\nnew Float32Array([NaN]).includes(NaN); // true;\nnew Float64Array([NaN]).includes(NaN); // true;\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.includes
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
includes471443No341047474334105.01.06.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/includes\n

\n
\n", + "global_objects/typedarray/indexof": "

TypedArray.prototype.indexOf()

The indexOf() method of TypedArray instances returns the first index at which a given element can be found in the typed array, or -1 if it is not present. This method has the same algorithm as Array.prototype.indexOf().

\n

Try it

\n

Syntax

\n
\n

js

\n
indexOf(searchElement)\nindexOf(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

Element to locate in the typed array.

\nfromIndex Optional\n

Zero-based index at which to start searching, converted to an integer.

Return value

\n

The first index of searchElement in the typed array; -1 if not found.

Description

\n

See Array.prototype.indexOf() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using indexOf()

\n
\n

js

\n
const uint8 = new Uint8Array([2, 5, 9]);\nuint8.indexOf(2); // 0\nuint8.indexOf(7); // -1\nuint8.indexOf(9, 2); // 2\nuint8.indexOf(2, -1); // -1\nuint8.indexOf(2, -3); // 0\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.indexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
indexOf4512
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).indexOf(0, -0) will now always return +0.
No329.14545
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).indexOf(0, -0) will now always return +0.
329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf\n

\n
\n", + "global_objects/typedarray/lastindexof": "

TypedArray.prototype.lastIndexOf()

The lastIndexOf() method of TypedArray instances returns the last index at which a given element can be found in the typed array, or -1 if it is not present. The typed array is searched backwards, starting at fromIndex. This method has the same algorithm as Array.prototype.lastIndexOf().

\n

Try it

\n

Syntax

\n
\n

js

\n
lastIndexOf(searchElement)\nlastIndexOf(searchElement, fromIndex)\n
\n

Parameters

\n
searchElement

Element to locate in the typed array.

\nfromIndex Optional\n

Zero-based index at which to start searching backwards, converted to an integer.

Return value

\n

The last index of searchElement in the typed array; -1 if not found.

Description

\n

See Array.prototype.lastIndexOf() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using lastIndexOf()

\n
\n

js

\n
const uint8 = new Uint8Array([2, 5, 9, 2]);\nuint8.lastIndexOf(2); // 3\nuint8.lastIndexOf(7); // -1\nuint8.lastIndexOf(2, 3); // 3\nuint8.lastIndexOf(2, 2); // 0\nuint8.lastIndexOf(2, -2); // 0\nuint8.lastIndexOf(2, -1); // 3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.lastindexof
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
lastIndexOf4512
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).lastIndexOf(0, -0) will now always return +0.
No32104545
37Starting with Firefox 47, this method will no longer return -0. For example, new Uint8Array([0]).lastIndexOf(0, -0) will now always return +0.
32105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/lastIndexOf\n

\n
\n", + "global_objects/typedarray/tolocalestring": "

TypedArray.prototype.toLocaleString()

The toLocaleString() method of TypedArray instances returns a string representing the elements of the typed array. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma \",\"). This method has the same algorithm as Array.prototype.toLocaleString().

\n

Try it

\n

Syntax

\n
\n

js

\n
toLocaleString()\ntoLocaleString(locales)\ntoLocaleString(locales, options)\n
\n

Parameters

\n
\nlocales Optional\n

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

\noptions Optional\n

An object with configuration properties. See Number.prototype.toLocaleString().

Return value

\n

A string representing the elements of the typed array.

Description

\n

See Array.prototype.toLocaleString() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using toLocaleString()

\n
\n

js

\n
const uint = new Uint32Array([2000, 500, 8123, 12, 4212]);\n\nuint.toLocaleString();\n// if run in a de-DE locale\n// \"2.000,500,8.123,12,4.212\"\n\nuint.toLocaleString(\"en-US\");\n// \"2,000,500,8,123,12,4,212\"\n\nuint.toLocaleString(\"ja-JP\", { style: \"currency\", currency: \"JPY\" });\n// \"¥2,000,¥500,¥8,123,¥12,¥4,212\"\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.tolocalestring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toLocaleString712511011.65.1≤3718511251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toLocaleString\n

\n
\n", + "global_objects/typedarray/tostring": "

TypedArray.prototype.toString()

The toString() method of TypedArray instances returns a string representing the specified typed array and its elements. This method has the same algorithm as Array.prototype.toString().

\n

Try it

\n

Syntax

\n
\n

js

\n
toString()\n
\n

Parameters

\n

None.

Return value

\n

A string representing the elements of the typed array.

Description

\n

See Array.prototype.toString() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Converting a typed array to a string

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\n// Explicit conversion\nconsole.log(uint8.toString()); // 1,2,3\n// Implicit conversion\nconsole.log(`${uint8}`); // 1,2,3\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.tostring
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toString712511011.65.1≤3718511251.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toString\n

\n
\n", + "global_objects/typedarray/@@species": "

TypedArray[@@species]

\n

The TypedArray[@@species] static accessor property returns the constructor used to construct return values from typed array methods.

Warning: The existence of @@species allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

\n
\n

Syntax

\n
\n

js

\n
TypedArray[Symbol.species]\n
\n

Return value

\n

The value of the constructor (this) on which get @@species was called. The return value is used to construct return values from typed array methods that create new typed arrays.

Description

\n
\n

The @@species accessor property returns the default constructor for typed array objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

\n

js

\n
// Hypothetical underlying implementation for illustration\nclass TypedArray {\n  static get [Symbol.species]() {\n    return this;\n  }\n}\n
\n

Because of this polymorphic implementation, @@species of derived subclasses would also return the constructor itself by default.

\n

js

\n
class SubTypedArray extends Int8Array {}\nSubTypedArray[Symbol.species] === SubTypedArray; // true\n
\n

When calling typed array methods that do not mutate the existing array but return a new array instance (for example, filter() and map()), the array's constructor[@@species] will be accessed. The returned constructor will be used to construct the return value of the typed array method.

However, unlike Array[@@species], when using @@species to create new typed arrays, the language will make sure that the newly created array is a proper typed array and has the same content type as the original array — for example, you can't create a BigInt64Array from a Float64Array, or create a non-BigInt array from a BigInt array. Doing so throws a TypeError.

\n

js

\n
class BadArray extends Int8Array {\n  static get [Symbol.species]() {\n    return Array;\n  }\n}\nnew BadArray(1).map(() => 0); // TypeError: Method %TypedArray%.prototype.map called on incompatible receiver [object Array]\n\nclass BadArray2 extends Int8Array {\n  static get [Symbol.species]() {\n    return BigInt64Array;\n  }\n}\nnew BadArray2(1).map(() => 0n); // TypeError: TypedArray.prototype.map constructed typed array of different content type from |this|\n
\n

Note: Due to a bug in both SpiderMonkey and V8, the content type match is not checked. Only Safari will throw a TypeError in the second example.

\n

Examples

\n

Species in ordinary objects

\n
\n

The @@species property returns the default constructor function, which is one of the typed array constructors itself for any given typed array constructor.

\n

js

\n
Int8Array[Symbol.species]; // function Int8Array()\nUint8Array[Symbol.species]; // function Uint8Array()\nFloat32Array[Symbol.species]; // function Float32Array()\n
\n
\n

Species in derived objects

\n
\n

In an instance of a custom TypedArray subclass, such as MyTypedArray, the MyTypedArray species is the MyTypedArray constructor. However, you might want to overwrite this, in order to return a parent typed array object in your derived class methods:

\n

js

\n
class MyTypedArray extends Uint8Array {\n  // Overwrite MyTypedArray species to the parent Uint8Array constructor\n  static get [Symbol.species]() {\n    return Uint8Array;\n  }\n}\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-%typedarray%-@@species
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
@@species511348No381051514841105.01.06.5.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@species\n

\n
\n", + "global_objects/typedarray/filter": "

TypedArray.prototype.filter()

The filter() method of TypedArray instances creates a copy of a portion of a given typed array, filtered down to just the elements from the given typed array that pass the test implemented by the provided function. This method has the same algorithm as Array.prototype.filter().

\n

Try it

\n

Syntax

\n
\n

js

\n
filter(callbackFn)\nfilter(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to keep the element in the resulting typed array, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array filter() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

A copy of the given typed array containing just the elements that pass the test. If no elements pass the test, an empty typed array is returned.

Description

\n

See Array.prototype.filter() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Filtering out all small values

\n
\n

The following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed.

\n

js

\n
function isBigEnough(element, index, array) {\n  return element >= 10;\n}\nnew Uint8Array([12, 5, 8, 130, 44]).filter(isBigEnough);\n// Uint8Array [ 12, 130, 44 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.filter
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
filter451238No329.1454538329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/filter\n

\n
\n", + "global_objects/typedarray/from": "

TypedArray.from()

The TypedArray.from() static method creates a new typed array from an array-like or iterable object. This method is nearly the same as Array.from().

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
TypedArray.from(arrayLike, mapFn)\nTypedArray.from(arrayLike, mapFn, thisArg)\n
\n

Where TypedArray is one of:

\n

Parameters

\n
arrayLike

An iterable or array-like object to convert to a typed array.

\nmapFn Optional\n

A function to call on every element of the typed array. If provided, every value to be added to the array is first passed through this function, and mapFn's return value is added to the typed array instead. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

\nthisArg Optional\n

Value to use as this when executing mapFn.

Return value

\n

A new TypedArray instance.

Description

\n
\n

See Array.from() for more details.

There are some subtle distinctions between Array.from() and TypedArray.from() (note: the this value mentioned below is the this value that TypedArray.from() was called with, not the thisArg argument used to invoke mapFn):

\n

Examples

\n

From an iterable object (Set)

\n
\n

js

\n
const s = new Set([1, 2, 3]);\nUint8Array.from(s);\n// Uint8Array [ 1, 2, 3 ]\n
\n

From a string

\n
\n

js

\n
Int16Array.from(\"123\");\n// Int16Array [ 1, 2, 3 ]\n
\n

Use with arrow function and map

\n
\n

Using an arrow function as the map function to manipulate the elements

\n

js

\n
Float32Array.from([1, 2, 3], (x) => x + x);\n// Float32Array [ 2, 4, 6 ]\n
\n
\n

Generate a sequence of numbers

\n
\n

js

\n
Uint8Array.from({ length: 5 }, (v, k) => k);\n// Uint8Array [ 0, 1, 2, 3, 4 ]\n
\n

Calling from() on non-TypedArray constructors

\n
\n

The this value of from() must be a constructor that returns a TypedArray instance.

\n

js

\n
function NotArray(len) {\n  console.log(\"NotArray called with length\", len);\n}\n\nInt8Array.from.call({}, []); // TypeError: #<Object> is not a constructor\nInt8Array.from.call(NotArray, []);\n// NotArray called with length 0\n// TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray>\n
\n
\n

js

\n
function NotArray2(len) {\n  console.log(\"NotArray2 called with length\", len);\n  return new Uint8Array(len);\n}\nconsole.log(Int8Array.from.call(NotArray2, [1, 2, 3]));\n// NotArray2 called with length 3\n// Uint8Array(3) [ 1, 2, 3 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.from
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
from451238No321045453832105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from\n

\n
\n", + "global_objects/typedarray/of": "

TypedArray.of()

The TypedArray.of() static method creates a new typed array from a variable number of arguments. This method is nearly the same as Array.of().

\n

Try it

\n

Syntax

\n
\n
\n

js

\n
TypedArray.of()\nTypedArray.of(element1)\nTypedArray.of(element1, element2)\nTypedArray.of(element1, element2, /* …, */ elementN)\n
\n

Where TypedArray is one of:

\n

Parameters

\n
\nelement1, …, elementN\n

Elements used to create the typed array.

Return value

\n

A new TypedArray instance.

Description

\n
\n

See Array.of() for more details. There are some subtle distinctions between Array.of() and TypedArray.of():

\n

Examples

\n

Using of()

\n
\n

js

\n
Uint8Array.of(1); // Uint8Array [ 1 ]\nInt8Array.of(\"1\", \"2\", \"3\"); // Int8Array [ 1, 2, 3 ]\nFloat32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ]\nInt16Array.of(undefined); // Int16Array [ 0 ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.of
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
of451238No329.1454538329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/of\n

\n
\n", + "global_objects/typedarray/buffer": "

TypedArray.prototype.buffer

The buffer accessor property of TypedArray instances returns the ArrayBuffer or SharedArrayBuffer referenced by this typed array at construction time.

\n

Try it

\n

Description

\n
\n

The buffer property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when the TypedArray is constructed and cannot be changed. TypedArray is one of the TypedArray objects.

Because a typed array is a view of a buffer, the underlying buffer may be longer than the typed array itself.

\n

Examples

\n

Using the buffer property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst uint16 = new Uint16Array(buffer);\nuint16.buffer; // ArrayBuffer { byteLength: 8 }\n
\n

Accessing the underlying buffer from a sliced array view

\n
\n

js

\n
const buffer = new ArrayBuffer(1024);\nconst arr = new Uint8Array(buffer, 64, 128);\nconsole.log(arr.byteLength); // 128\nconsole.log(arr.buffer.byteLength); // 1024\nconsole.log(arr.buffer === buffer); // true\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-%typedarray%.prototype.buffer
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
buffer71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/buffer\n

\n
\n", + "global_objects/typedarray/bytelength": "

TypedArray.prototype.byteLength

The byteLength accessor property of TypedArray instances returns the length (in bytes) of this typed array.

\n

Try it

\n

Description

\n

The byteLength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when a TypedArray is constructed and cannot be changed. If the TypedArray is not specifying a byteOffset or a length, the length of the referenced ArrayBuffer will be returned. TypedArray is one of the TypedArray objects.

Examples

\n

Using the byteLength property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\n\nconst uint8 = new Uint8Array(buffer);\nuint8.byteLength; // 8 (matches the byteLength of the buffer)\n\nconst uint8newLength = new Uint8Array(buffer, 1, 5);\nuint8newLength.byteLength; // 5 (as specified when constructing the Uint8Array)\n\nconst uint8offSet = new Uint8Array(buffer, 2);\nuint8offSet.byteLength; // 6 (due to the offset of the constructed Uint8Array)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-%typedarray%.prototype.bytelength
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteLength71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength\n

\n
\n", + "global_objects/typedarray/byteoffset": "

TypedArray.prototype.byteOffset

The byteOffset accessor property of TypedArray instances returns the offset (in bytes) of this typed array from the start of its ArrayBuffer or SharedArrayBuffer.

\n

Description

\n

The byteOffset property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when a TypedArray is constructed and cannot be changed. TypedArray is one of the TypedArray objects.

Examples

\n

Using the byteOffset property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\n\nconst uint8array1 = new Uint8Array(buffer);\nuint8array1.byteOffset; // 0 (no offset specified)\n\nconst uint8array2 = new Uint8Array(buffer, 3);\nuint8array2.byteOffset; // 3 (as specified when constructing Uint8Array)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-%typedarray%.prototype.byteoffset
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
byteOffset71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset\n

\n
\n", + "global_objects/typedarray/length": "

TypedArray.prototype.length

The length accessor property of TypedArray instances returns the length (in elements) of this typed array.

\n

Try it

\n

Description

\n

The length property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. The value is established when a TypedArray is constructed and cannot be changed. If the TypedArray is not specifying a byteOffset or a length, the length of the referenced ArrayBuffer will be returned. TypedArray is one of the TypedArray objects.

Examples

\n

Using the length property

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\n\nlet uint8 = new Uint8Array(buffer);\nuint8.length; // 8 (matches the length of the buffer)\n\nuint8 = new Uint8Array(buffer, 1, 5);\nuint8.length; // 5 (as specified when constructing the Uint8Array)\n\nuint8 = new Uint8Array(buffer, 2);\nuint8.length; // 6 (due to the offset of the constructed Uint8Array)\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-get-%typedarray%.prototype.length
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
length71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/length\n

\n
\n", + "global_objects/typedarray/at": "

TypedArray.prototype.at()

The at() method of TypedArray instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the typed array. This method has the same algorithm as Array.prototype.at().

\n

Try it

\n

Syntax

\n
\n

js

\n
at(index)\n
\n

Parameters

\n
index

Zero-based index of the typed array element to be returned, converted to an integer. Negative index counts back from the end of the typed array — if index < 0, index + array.length is accessed.

Return value

\n

The element in the typed array matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.

Description

\n

See Array.prototype.at() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Return the last value of a typed array

\n
\n

The following example provides a function which returns the last element found in a specified array.

\n

js

\n
const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);\n\n// A function which returns the last item of a given array\nfunction returnLast(arr) {\n  return arr.at(-1);\n}\n\nconst lastItem = returnLast(uint8);\nconsole.log(lastItem); // 18\n
\n
\n

Comparing methods

\n
\n

Here we compare different ways to select the penultimate (last but one) item of a TypedArray. Whilst all below methods are valid, it highlights the succinctness and readability of the at() method.

\n

js

\n
// Our typed array with values\nconst uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);\n\n// Using length property\nconst lengthWay = uint8[uint8.length - 2];\nconsole.log(lengthWay); // 11\n\n// Using slice() method. Note an array is returned\nconst sliceWay = uint8.slice(-2, -1);\nconsole.log(sliceWay[0]); // 11\n\n// Using at() method\nconst atWay = uint8.at(-2);\nconsole.log(atWay); // 11\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.at
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
at929290No7815.49292906515.416.0No16.6.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/at\n

\n
\n", + "global_objects/typedarray/copywithin": "

TypedArray.prototype.copyWithin()

The copyWithin() method of TypedArray instances shallow copies part of this typed array to another location in the same typed array and returns this typed array without modifying its length. This method has the same algorithm as Array.prototype.copyWithin().

\n

Try it

\n

Syntax

\n
\n

js

\n
copyWithin(target, start)\ncopyWithin(target, start, end)\n
\n

Parameters

\n
target

Zero-based index at which to copy the sequence to, converted to an integer. This corresponds to where the element at start will be copied to, and all elements between start and end are copied to succeeding indices.

start

Zero-based index at which to start copying elements from, converted to an integer.

\nend Optional\n

Zero-based index at which to end copying elements from, converted to an integer. copyWithin() copies up to but not including end.

Return value

\n

The modified typed array.

Description

\n

See Array.prototype.copyWithin() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using copyWithin()

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst uint8 = new Uint8Array(buffer);\nuint8.set([1, 2, 3]);\nconsole.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]\nuint8.copyWithin(3, 0, 3);\nconsole.log(uint8); // Uint8Array [ 1, 2, 3, 1, 2, 3, 0, 0 ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.copywithin
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
copyWithin451234No329.1454534329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin\n

\n
\n", + "global_objects/typedarray/every": "

TypedArray.prototype.every()

The every() method of TypedArray instances tests whether all elements in the typed array pass the test implemented by the provided function. It returns a Boolean value. This method has the same algorithm as Array.prototype.every().

\n

Try it

\n

Syntax

\n
\n

js

\n
every(callbackFn)\nevery(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array every() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

true unless callbackFn returns a falsy value for a typed array element, in which case false is immediately returned.

Description

\n

See Array.prototype.every() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Testing size of all typed array elements

\n
\n

The following example tests whether all elements in the typed array are bigger than 9.

\n

js

\n
function isBigEnough(element, index, array) {\n  return element >= 10;\n}\nnew Uint8Array([12, 5, 8, 130, 44]).every(isBigEnough); // false\nnew Uint8Array([12, 54, 18, 130, 44]).every(isBigEnough); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.every
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
every451237No329.1454537329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/every\n

\n
\n", + "global_objects/typedarray/fill": "

TypedArray.prototype.fill()

The fill() method of TypedArray instances changes all elements within a range of indices in a typed array to a static value. It returns the modified typed array. This method has the same algorithm as Array.prototype.fill().

\n

Try it

\n

Syntax

\n
\n

js

\n
fill(value)\nfill(value, start)\nfill(value, start, end)\n
\n

Parameters

\n
value

Value to fill the typed array with.

\nstart Optional\n

Zero-based index at which to start filling, converted to an integer.

\nend Optional\n

Zero-based index at which to end filling, converted to an integer. fill() fills up to but not including end.

Return value

\n

The modified typed array, filled with value.

Description

\n

See Array.prototype.fill() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using fill()

\n
\n

js

\n
new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4]\nnew Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4]\nnew Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3]\nnew Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3]\nnew Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.fill
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
fill451237No329.1454537329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/fill\n

\n
\n", + "global_objects/typedarray/find": "

TypedArray.prototype.find()

The find() method of TypedArray instances returns the first element in the provided typed array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. This method has the same algorithm as Array.prototype.find().

\n

Try it

\n

Syntax

\n
\n

js

\n
find(callbackFn)\nfind(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array find() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The first element in the typed array that satisfies the provided testing function. Otherwise, undefined is returned.

Description

\n

See Array.prototype.find() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Find a prime number in a typed array

\n
\n

The following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number).

\n

js

\n
function isPrime(element, index, array) {\n  let start = 2;\n  while (start <= Math.sqrt(element)) {\n    if (element % start++ < 1) {\n      return false;\n    }\n  }\n  return element > 1;\n}\n\nconst uint8 = new Uint8Array([4, 5, 8, 12]);\nconsole.log(uint8.find(isPrime)); // 5\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.find
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
find451237No329.1454537329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/find\n

\n
\n", + "global_objects/typedarray/findindex": "

TypedArray.prototype.findIndex()

The findIndex() method of TypedArray instances returns the index of the first element in a typed array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method has the same algorithm as Array.prototype.findIndex().

\n

Try it

\n

Syntax

\n
\n

js

\n
findIndex(callbackFn)\nfindIndex(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array findIndex() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The index of the first element in the typed array that passes the test. Otherwise, -1.

Description

\n

See Array.prototype.findIndex() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Find the index of a prime number in a typed array

\n
\n

The following example finds the index of an element in the typed array that is a prime number (or returns -1 if there is no prime number).

\n

js

\n
function isPrime(element, index, array) {\n  let start = 2;\n  while (start <= Math.sqrt(element)) {\n    if (element % start++ < 1) {\n      return false;\n    }\n  }\n  return element > 1;\n}\n\nconst uint8 = new Uint8Array([4, 6, 8, 12]);\nconst uint16 = new Uint16Array([4, 6, 7, 12]);\n\nconsole.log(uint8.findIndex(isPrime)); // -1, not found\nconsole.log(uint16.findIndex(isPrime)); // 2\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.findindex
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findIndex451237No329.1454537329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/findIndex\n

\n
\n", + "global_objects/typedarray/findlast": "

TypedArray.prototype.findLast()

The findLast() method of TypedArray instances iterates the typed array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned. This method has the same algorithm as Array.prototype.findLast().

\n

Try it

\n

Syntax

\n
\n

js

\n
findLast(callbackFn)\nfindLast(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array findLast() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The last (highest-index) element in the typed array that satisfies the provided testing function; undefined if no matching element is found.

Description

\n

See Array.prototype.findLast() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Find the last prime number in a typed array

\n
\n

The following example returns the value of the last element in the typed array that is a prime number, or undefined if there is no prime number.

\n

js

\n
function isPrime(element) {\n  if (element % 2 === 0 || element < 2) {\n    return false;\n  }\n  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {\n    if (element % factor === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\nlet uint8 = new Uint8Array([4, 6, 8, 12]);\nconsole.log(uint8.findLast(isPrime)); // undefined (no primes in array)\nuint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]);\nconsole.log(uint8.findLast(isPrime)); // 11\n
\n
\n

All elements are visited and may be modified by the callback

\n
\n

The following examples show that all elements are visited, and that the value passed to the callback is their value when visited:

\n

js

\n
// Declare array with no elements at indexes 2, 3, and 4\n// The missing elements will be initialized to zero.\nconst uint8 = new Uint8Array([0, 1, , , , 5, 6]);\n\n// Iterate through the elements in reverse order.\n// Note that all elements are visited.\nuint8.findLast((value, index) => {\n  console.log(`Visited index ${index} with value ${value}`);\n});\n\n// Shows all indexes, including deleted\nuint8.findLast((value, index) => {\n  // Modify element 3 on first iteration\n  if (index === 6) {\n    console.log(\"Set uint8[3] to 44\");\n    uint8[3] = 44;\n  }\n  // Element 3 is still visited but will have a new value.\n  console.log(`Visited index ${index} with value ${value}`);\n});\n// Visited index 6 with value 6\n// Visited index 5 with value 5\n// Visited index 4 with value 0\n// Visited index 3 with value 0\n// Visited index 2 with value 0\n// Visited index 1 with value 1\n// Visited index 0 with value 0\n// Set uint8[3] to 44\n// Visited index 6 with value 6\n// Visited index 5 with value 5\n// Visited index 4 with value 0\n// Visited index 3 with value 44\n// Visited index 2 with value 0\n// Visited index 1 with value 1\n// Visited index 0 with value 0\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.findlast
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findLast9797104No8315.497971046815.418.01.16No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/findLast\n

\n
\n", + "global_objects/typedarray/findlastindex": "

TypedArray.prototype.findLastIndex()

The findLastIndex() method of TypedArray instances iterates the typed array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method has the same algorithm as Array.prototype.findLastIndex().

\n

Try it

\n

Syntax

\n
\n

js

\n
findLastIndex(callbackFn)\nfindLastIndex(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array findLastIndex() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

The index of the last (highest-index) element in the typed array that passes the test. Otherwise -1 if no matching element is found.

Description

\n

See Array.prototype.findLastIndex() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Find the index of the last prime number in a typed array

\n
\n

The following example returns the index of the last element in the typed array that is a prime number, or -1 if there is no prime number.

\n

js

\n
function isPrime(element) {\n  if (element % 2 === 0 || element < 2) {\n    return false;\n  }\n  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {\n    if (element % factor === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\nlet uint8 = new Uint8Array([4, 6, 8, 12]);\nconsole.log(uint8.findLastIndex(isPrime));\n// -1 (no primes in array)\nuint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]);\nconsole.log(uint8.findLastIndex(isPrime));\n// 5\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.findlastindex
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
findLastIndex9797104No8315.497971046815.418.01.16No
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/findLastIndex\n

\n
\n", + "global_objects/typedarray/foreach": "

TypedArray.prototype.forEach()

The forEach() method of TypedArray instances executes a provided function once for each typed array element. This method has the same algorithm as Array.prototype.forEach().

\n

Try it

\n

Syntax

\n
\n

js

\n
forEach(callbackFn)\nforEach(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. Its return value is discarded. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array forEach() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

None (undefined).

Description

\n

See Array.prototype.forEach() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Logging the contents of a typed array

\n
\n

The following code logs a line for each element in a typed array:

\n

js

\n
function logArrayElements(element, index, array) {\n  console.log(`a[${index}] = ${element}`);\n}\n\nnew Uint8Array([0, 1, 2, 3]).forEach(logArrayElements);\n// Logs:\n// a[0] = 0\n// a[1] = 1\n// a[2] = 2\n// a[3] = 3\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.foreach
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
forEach451238No321045453832105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/forEach\n

\n
\n", + "global_objects/typedarray/join": "

TypedArray.prototype.join()

The join() method of TypedArray instances creates and returns a new string by concatenating all of the elements in this typed array, separated by commas or a specified separator string. If the typed array has only one item, then that item will be returned without using the separator. This method has the same algorithm as Array.prototype.join().

\n

Try it

\n

Syntax

\n
\n

js

\n
join()\njoin(separator)\n
\n

Parameters

\n
\nseparator Optional\n

A string to separate each pair of adjacent elements of the typed array. If omitted, the typed array elements are separated with a comma (\",\").

Return value

\n

A string with all typed array elements joined. If array.length is 0, the empty string is returned.

Description

\n

See Array.prototype.join() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using join()

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\nuint8.join(); // '1,2,3'\nuint8.join(\" / \"); // '1 / 2 / 3'\nuint8.join(\"\"); // '123'\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.join
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
join451237No329.1454537329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/join\n

\n
\n", + "global_objects/typedarray/map": "

TypedArray.prototype.map()

The map() method of TypedArray instances creates a new typed array populated with the results of calling a provided function on every element in the calling typed array. This method has the same algorithm as Array.prototype.map().

\n

Try it

\n

Syntax

\n
\n

js

\n
map(callbackFn)\nmap(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. Its return value is added as a single element in the new typed array. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array map() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

A new typed array with each element being the result of the callback function.

Description

\n

See Array.prototype.map() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Mapping a typed array to a typed array of square roots

\n
\n

The following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.

\n

js

\n
const numbers = new Uint8Array([1, 4, 9]);\nconst roots = numbers.map(Math.sqrt);\n// roots is now: Uint8Array [1, 2, 3],\n// numbers is still Uint8Array [1, 4, 9]\n
\n
\n

Mapping a typed array of numbers using a function containing an argument

\n
\n

The following code shows how map() works when a function requiring one argument is used with it. The argument will automatically be assigned to each element of the typed array as map() loops through the original typed array.

\n

js

\n
const numbers = new Uint8Array([1, 4, 9]);\nconst doubles = numbers.map((num) => num * 2);\n// doubles is now Uint8Array [2, 8, 18]\n// numbers is still Uint8Array [1, 4, 9]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.map
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
map451238No329.1454538329.35.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/map\n

\n
\n", + "global_objects/typedarray/reduce": "

TypedArray.prototype.reduce()

The reduce() method of TypedArray instances executes a user-supplied \"reducer\" callback function on each element of the typed array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the typed array is a single value. This method has the same algorithm as Array.prototype.reduce().

\n

Try it

\n

Syntax

\n
\n

js

\n
reduce(callbackFn)\nreduce(callbackFn, initialValue)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:

accumulator

The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].

currentValue

The value of the current element. On the first call, its value is array[0] if initialValue is specified; otherwise its value is array[1].

currentIndex

The index position of currentValue in the typed array. On the first call, its value is 0 if initialValue is specified, otherwise 1.

array

The typed array reduce() was called upon.

\ninitialValue Optional\n

A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the typed array as currentValue. If initialValue is not specified, accumulator is initialized to the first value in the typed array, and callbackFn starts executing with the second value in the typed array as currentValue. In this case, if the typed array is empty (so that there's no first value to return as accumulator), an error is thrown.

Return value

\n

The value that results from running the \"reducer\" callback function to completion over the entire typed array.

Exceptions

\n
TypeError

Thrown if the typed array contains no elements and initialValue is not provided.

Description

\n

See Array.prototype.reduce() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Sum up all values within an array

\n
\n

js

\n
const total = new Uint8Array([0, 1, 2, 3]).reduce((a, b) => a + b);\n// total === 6\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.reduce
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reduce451237No321045453732105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/reduce\n

\n
\n", + "global_objects/typedarray/reduceright": "

TypedArray.prototype.reduceRight()

The reduceRight() method of TypedArray instances applies a function against an accumulator and each value of the typed array (from right-to-left) to reduce it to a single value. This method has the same algorithm as Array.prototype.reduceRight().

\n

Try it

\n

Syntax

\n
\n

js

\n
reduceRight(callbackFn)\nreduceRight(callbackFn, initialValue)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduceRight(). The function is called with the following arguments:

accumulator

The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is the last element of the typed array.

currentValue

The value of the current element. On the first call, its value is the last element if initialValue is specified; otherwise its value is the second-to-last element.

currentIndex

The index position of currentValue in the typed array. On the first call, its value is array.length - 1 if initialValue is specified, otherwise array.length - 2.

array

The typed array reduceRight() was called upon.

\ninitialValue Optional\n

Value to use as accumulator to the first call of the callbackFn. If no initial value is supplied, the last element in the typed array will be used and skipped. Calling reduceRight() on an empty typed array without an initial value creates a TypeError.

Return value

\n

The value that results from the reduction.

Description

\n

See Array.prototype.reduceRight() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Sum up all values within an array

\n
\n

js

\n
const total = new Uint8Array([0, 1, 2, 3]).reduceRight((a, b) => a + b);\n// total === 6\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.reduceright
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reduceRight451237No321045453732105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/reduceRight\n

\n
\n", + "global_objects/typedarray/reverse": "

TypedArray.prototype.reverse()

The reverse() method of TypedArray instances reverses a typed array in place and returns the reference to the same typed array, the first typed array element now becoming the last, and the last typed array element becoming the first. In other words, elements order in the typed array will be turned towards the direction opposite to that previously stated. This method has the same algorithm as Array.prototype.reverse().

\n

Try it

\n

Syntax

\n
\n

js

\n
reverse()\n
\n

Parameters

\n

None.

Return value

\n

The reference to the original typed array, now reversed. Note that the typed array is reversed in place, and no copy is made.

Description

\n

See Array.prototype.reverse() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using reverse()

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\nuint8.reverse();\n\nconsole.log(uint8); // Uint8Array [3, 2, 1]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.reverse
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
reverse451237No321045453732105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/reverse\n

\n
\n", + "global_objects/typedarray/set": "

TypedArray.prototype.set()

The set() method of TypedArray instances stores multiple values in the typed array, reading input values from a specified array.

\n

Try it

\n

Syntax

\n
\n

js

\n
set(array)\nset(array, targetOffset)\n\nset(typedarray)\nset(typedarray, targetOffset)\n
\n

Parameters

\n
array

The array from which to copy values. All values from the source array are copied into the target array, unless the length of the source array plus the target offset exceeds the length of the target array, in which case an exception is thrown.

typedarray

If the source array is a typed array, the two arrays may share the same underlying ArrayBuffer; the JavaScript engine will intelligently copy the source range of the buffer to the destination range.

\ntargetOffset Optional\n

The offset into the target array at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0).

Return value

\n

None (undefined).

Exceptions

\n
RangeError

Thrown in one of the following cases:

  • An element will be stored beyond the end of the typed array, either because targetOffset is too large or because array or typedarray is too large.
  • \ntargetOffset is negative.

Examples

\n

Using set()

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst uint8 = new Uint8Array(buffer);\n\nuint8.set([1, 2, 3], 3);\n\nconsole.log(uint8); // Uint8Array [ 0, 0, 0, 1, 2, 3, 0, 0 ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.set
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
set71241011.65.14184124.21.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set\n

\n
\n", + "global_objects/typedarray/slice": "

TypedArray.prototype.slice()

The slice() method of TypedArray instances returns a copy of a portion of a typed array into a new typed array object selected from start to end (end not included) where start and end represent the index of items in that typed array. The original typed array will not be modified. This method has the same algorithm as Array.prototype.slice().

\n

Try it

\n

Syntax

\n
\n

js

\n
slice()\nslice(start)\nslice(start, end)\n
\n

Parameters

\n
\nstart Optional\n

Zero-based index at which to start extraction, converted to an integer.

\nend Optional\n

Zero-based index at which to end extraction, converted to an integer. slice() extracts up to but not including end.

Return value

\n

A new typed array containing the extracted elements.

Description

\n

See Array.prototype.slice() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Return a portion of an existing typed array

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\nuint8.slice(1); // Uint8Array [ 2, 3 ]\nuint8.slice(2); // Uint8Array [ 3 ]\nuint8.slice(-2); // Uint8Array [ 2, 3 ]\nuint8.slice(0, 1); // Uint8Array [ 1 ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.slice
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
slice451238No321045453832105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice\n

\n
\n", + "global_objects/typedarray/some": "

TypedArray.prototype.some()

The some() method of TypedArray instances tests whether at least one element in the typed array passes the test implemented by the provided function. It returns true if, in the typed array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the typed array. This method has the same algorithm as Array.prototype.some().

\n

Try it

\n

Syntax

\n
\n

js

\n
some(callbackFn)\nsome(callbackFn, thisArg)\n
\n

Parameters

\n
callbackFn

A function to execute for each element in the typed array. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

element

The current element being processed in the typed array.

index

The index of the current element being processed in the typed array.

array

The typed array some() was called upon.

\nthisArg Optional\n

A value to use as this when executing callbackFn. See iterative methods.

Return value

\n

false unless callbackFn returns a truthy value for a typed array element, in which case true is immediately returned.

Description

\n

See Array.prototype.some() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Testing size of all typed array elements

\n
\n

The following example tests whether any element in the typed array is bigger than 10.

\n

js

\n
function isBiggerThan10(element, index, array) {\n  return element > 10;\n}\nnew Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false\nnew Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.some
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
some451237No321045453732105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/some\n

\n
\n", + "global_objects/typedarray/sort": "

TypedArray.prototype.sort()

The sort() method of TypedArray instances sorts the elements of a typed array in place and returns the reference to the same typed array, now sorted. This method has the same algorithm as Array.prototype.sort(), except that it sorts the values numerically instead of as strings by default.

\n

Try it

\n

Syntax

\n
\n

js

\n
sort()\nsort(compareFn)\n
\n

Parameters

\n
\ncompareFn Optional\n

A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if a is less than b, positive if a is greater than b, and zero if they are equal. NaN is treated as 0. The function is called with the following arguments:

a

The first element for comparison. Will never be undefined.

b

The second element for comparison. Will never be undefined.

If omitted, the typed array elements are sorted according to numeric value.

Return value

\n

The reference to the original typed array, now sorted. Note that the typed array is sorted in place, and no copy is made.

Description

\n

See Array.prototype.sort() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using sort()

\n
\n

For more examples, see also the Array.prototype.sort() method.

\n

js

\n
let numbers = new Uint8Array([40, 1, 5, 200]);\nnumbers.sort();\n// Uint8Array [ 1, 5, 40, 200 ]\n// Unlike plain Arrays, a compare function is not required\n// to sort the numbers numerically.\n\n// Regular Arrays require a compare function to sort numerically:\nnumbers = [40, 1, 5, 200];\nnumbers.sort();\n// [1, 200, 40, 5]\n\nnumbers.sort((a, b) => a - b); // compare numbers\n// [ 1, 5, 40, 200 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.sort
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
sort451246No321045454632105.01.04.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/sort\n

\n
\n", + "global_objects/typedarray/subarray": "

TypedArray.prototype.subarray()

The subarray() method of TypedArray instances returns a new typed array on the same ArrayBuffer store and with the same element types as for this typed array. The begin offset is inclusive and the end offset is exclusive.

\n

Try it

\n

Syntax

\n
\n

js

\n
subarray()\nsubarray(begin)\nsubarray(begin, end)\n
\n

Parameters

\n
\nbegin Optional\n

Element to begin at. The offset is inclusive. The whole array will be included in the new view if this value is not specified.

\nend Optional\n

Element to end at. The offset is exclusive. If not specified, all elements from the one specified by begin to the end of the array are included in the new view.

Return value

\n

A new TypedArray object.

Description

\n
\n

The range specified by begin and end is clamped to the valid index range for the current array; if the computed length of the new array would be negative, it's clamped to zero. If either begin or end is negative, it refers to an index from the end of the array instead of from the beginning.

Also note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa.

\n

Examples

\n

Using the subarray() method

\n
\n

js

\n
const buffer = new ArrayBuffer(8);\nconst uint8 = new Uint8Array(buffer);\nuint8.set([1, 2, 3]);\n\nconsole.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]\n\nconst sub = uint8.subarray(0, 4);\n\nconsole.log(sub); // Uint8Array [ 1, 2, 3, 0 ]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.subarray
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
subarray71241011.65.14184124.21.01.00.12.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray\n

\n
\n", + "global_objects/typedarray/toreversed": "

TypedArray.prototype.toReversed()

The toReversed() method of TypedArray instances is the copying counterpart of the reverse() method. It returns a new typed array with the elements in reversed order. This method has the same algorithm as Array.prototype.toReversed().

\n

Syntax

\n
\n

js

\n
toReversed()\n
\n

Parameters

\n

None.

Return value

\n

A new typed array containing the elements in reversed order.

Description

\n

See Array.prototype.toReversed() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using toReversed()

\n
\n

js

\n
const uint8 = new Uint8Array([1, 2, 3]);\nconst reversedUint8 = uint8.toReversed();\nconsole.log(reversedUint8); // Uint8Array [3, 2, 1]\nconsole.log(uint8); // Uint8Array [1, 2, 3]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.toreversed
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toReversed110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toReversed\n

\n
\n", + "global_objects/typedarray/tosorted": "

TypedArray.prototype.toSorted()

The toSorted() method of TypedArray instances is the copying version of the sort() method. It returns a new typed array with the elements sorted in ascending order. This method has the same algorithm as Array.prototype.toSorted(), except that it sorts the values numerically instead of as strings by default.

\n

Syntax

\n
\n

js

\n
toSorted()\ntoSorted(compareFn)\n
\n

Parameters

\n
\ncompareFn Optional\n

Specifies a function that defines the sort order. If omitted, the typed array elements are sorted according to numeric value.

a

The first element for comparison.

b

The second element for comparison.

Return value

\n

A new typed array with the elements sorted in ascending order.

Description

\n

See Array.prototype.toSorted() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Sorting an array

\n
\n

For more examples, see also the Array.prototype.sort() method.

\n

js

\n
const numbers = new Uint8Array([40, 1, 5, 200]);\nconst numberSorted = numbers.toSorted();\nconsole.log(numberSorted); // Uint8Array [ 1, 5, 40, 200 ]\n// Unlike plain Arrays, a compare function is not required\n// to sort the numbers numerically.\nconsole.log(numbers); // Uint8Array [ 40, 1, 5, 200 ]\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.tosorted
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
toSorted110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toSorted\n

\n
\n", + "global_objects/typedarray/with": "

TypedArray.prototype.with()

The with() method of TypedArray instances is the copying version of using the bracket notation to change the value of a given index. It returns a new typed array with the element at the given index replaced with the given value. This method has the same algorithm as Array.prototype.with().

\n

Syntax

\n
\n

js

\n
arrayInstance.with(index, value)\n
\n

Parameters

\n
index

Zero-based index at which to change the typed array, converted to an integer.

value

Any value to be assigned to the given index.

Return value

\n

A new typed array with the element at index replaced with value.

Exceptions

\n
RangeError

Thrown if index >= array.length or index < -array.length.

Description

\n

See Array.prototype.with() for more details. This method is not generic and can only be called on typed array instances.

Examples

\n

Using with()

\n
\n

js

\n
const arr = new Uint8Array([1, 2, 3, 4, 5]);\nconsole.log(arr.with(2, 6)); // Uint8Array [1, 2, 6, 4, 5]\nconsole.log(arr); // Uint8Array [1, 2, 3, 4, 5]\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.with
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
with110110115No9616110110115741621.01.3120.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/with\n

\n
\n", + "regular_expressions/quantifier": "

Quantifier: *, +, ?, {n}, {n,}, {n,m}

A quantifier repeats an atom a certain number of times. The quantifier is placed after the atom it applies to.

\n

Syntax

\n
\n

regex

\n
// Greedy\natom?\natom*\natom+\natom{count}\natom{min,}\natom{min,max}\n\n// Non-greedy\natom??\natom*?\natom+?\natom{count}?\natom{min,}?\natom{min,max}?\n
\n

Parameters

\n
atom

A single atom.

count

A non-negative integer. The number of times the atom should be repeated.

min

A non-negative integer. The minimum number of times the atom can be repeated.

\nmax Optional\n

A non-negative integer. The maximum number of times the atom can be repeated. If omitted, the atom can be repeated as many times as needed.

Description

\n
\n

A quantifier is placed after an atom to repeat it a certain number of times. It cannot appear on its own. Each quantifier is able to specify a minimum and maximum number that a pattern must be repeated for.

Quantifier Minimum Maximum
? 0 1
* 0 Infinity
+ 1 Infinity
{count} count count
{min,} min Infinity
{min,max} min max

For the {count}, {min,}, and {min,max} syntaxes, there cannot be white spaces around the numbers — otherwise, it becomes a literal pattern.

\n

js

\n
const re = /a{1, 3}/;\nre.test(\"aa\"); // false\nre.test(\"a{1, 3}\"); // true\n
\n

This behavior is fixed in Unicode-aware mode, where braces cannot appear literally without escaping. The ability to use { and } literally without escaping is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/a{1, 3}/u; // SyntaxError: Invalid regular expression: Incomplete quantifier\n
\n

It is a syntax error if the minimum is greater than the maximum.

\n

js

\n
/a{3,2}/; // SyntaxError: Invalid regular expression: numbers out of order in {} quantifier\n
\n

Quantifiers can cause capturing groups to match multiple times. See the capturing groups page for more information on the behavior in this case.

Each repeated match doesn't have to be the same string.

\n

js

\n
/[ab]*/.exec(\"aba\"); // ['aba']\n
\n

Quantifiers are greedy by default, which means they try to match as many times as possible until the maximum is reached, or until it's not possible to match further. You can make a quantifier non-greedy by adding a ? after it. In this case, the quantifier will try to match as few times as possible, only matching more times if it's impossible to match the rest of the pattern with this many repetitions.

\n

js

\n
/a*/.exec(\"aaa\"); // ['aaa']; the entire input is consumed\n/a*?/.exec(\"aaa\"); // ['']; it's possible to consume no characters and still match successfully\n/^a*?$/.exec(\"aaa\"); // ['aaa']; it's not possible to consume fewer characters and still match successfully\n
\n

However, as soon as the regex successfully matches the string at some index, it will not try subsequent indices, although that may result in fewer characters being consumed.

\n

js

\n
/a*?$/.exec(\"aaa\"); // ['aaa']; the match already succeeds at the first character, so the regex never attempts to start matching at the second character\n
\n

Greedy quantifiers may try fewer repetitions if it's otherwise impossible to match the rest of the pattern.

\n

js

\n
/[ab]+[abc]c/.exec(\"abbc\"); // ['abbc']\n
\n

In this example, [ab]+ first greedily matches \"abb\", but [abc]c is not able to match the rest of the pattern (\"c\"), so the quantifier is reduced to match only \"ab\".

Greedy quantifiers avoid matching infinitely many empty strings. If the minimum number of matches is reached and no more characters are being consumed by the atom at this position, the quantifier stops matching. This is why /(a*)*/.exec(\"b\") does not result in an infinite loop.

Greedy quantifiers try to match as many times as possible; it does not maximize the length of the match. For example, /(aa|aabaac|ba)*/.exec(\"aabaac\") matches \"aa\" and then \"ba\" instead of \"aabaac\".

Quantifiers apply to a single atom. If you want to quantify a longer pattern or a disjunction, you must group it. Quantifiers cannot be applied to assertions.

\n

js

\n
/^*/; // SyntaxError: Invalid regular expression: nothing to repeat\n
\n

In Unicode-aware mode, lookahead assertions can be quantified. This is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/(?=a)?b/.test(\"b\"); // true; the lookahead is matched 0 time\n
\n
\n

Examples

\n

Removing HTML tags

\n
\n

The following example removes HTML tags enclosed in angle brackets. Note the use of ? to avoid consuming too many characters at once.

\n

js

\n
function stripTags(str) {\n  return str.replace(/<.+?>/g, \"\");\n}\n\nstripTags(\"<p><em>lorem</em> <strong>ipsum</strong></p>\"); // 'lorem ipsum'\n
\n

The same effect can be achieved with a greedy match, but not allowing the repeated pattern to match >.

\n

js

\n
function stripTags(str) {\n  return str.replace(/<[^>]+>/g, \"\");\n}\n\nstripTags(\"<p><em>lorem</em> <strong>ipsum</strong></p>\"); // 'lorem ipsum'\n
\n

Warning: This is for demonstration only — it doesn't handle > in attribute values. Use a proper HTML sanitizer like the HTML sanitizer API instead.

\n

Locating Markdown paragraphs

\n
\n

In Markdown, paragraphs are separated by one or more blank lines. The following example counts all paragraphs in a string by matching two or more line breaks.

\n

js

\n
function countParagraphs(str) {\n  return str.match(/(?:\\r?\\n){2,}/g).length + 1;\n}\n\ncountParagraphs(`\nParagraph 1\n\nParagraph 2\nContaining some line breaks, but still the same paragraph\n\nAnother paragraph\n`); // 3\n
\n

Warning: This is for demonstration only — it doesn't handle line breaks in code blocks or other Markdown block elements like headings. Use a proper Markdown parser instead.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Quantifier
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Quantifier11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier\n

\n
\n", + "regular_expressions/word_boundary_assertion": "

Word boundary assertion: \\b, \\B

A word boundary assertion checks if the current position in the string is a word boundary. A word boundary is where the next character is a word character and the previous character is not a word character, or vice versa.

\n

Syntax

\n
\n

regex

\n
\\b\n\\B\n
\n

Description

\n
\n

\\b asserts that the current position in the string is a word boundary. \\B negates the assertion: it asserts that the current position is not a word boundary. Both are assertions, so unlike other character escapes or character class escapes, \\b and \\B don't consume any characters.

A word character includes the following:

Word characters are also matched by the \\w character class escape.

Out-of-bounds input positions are considered non-word characters. For example, the following are successful matches:

\n

js

\n
/\\ba/.exec(\"abc\");\n/c\\b/.exec(\"abc\");\n\n/\\B /.exec(\" abc\");\n/ \\B/.exec(\"abc \");\n
\n
\n

Examples

\n

Detecting words

\n
\n

The following example detects if a string contains the word \"thanks\" or \"thank you\":

\n

js

\n
function hasThanks(str) {\n  return /\\b(thanks|thank you)\\b/i.test(str);\n}\n\nhasThanks(\"Thanks! You helped me a lot.\"); // true\nhasThanks(\"Just want to say thank you for all your work.\"); // true\nhasThanks(\"Thanksgiving is around the corner.\"); // false\n
\n

Warning: Not all languages have clearly defined word boundaries. If you are working with languages like Chinese or Thai, where there are no whitespace separators, use a more advanced library like Intl.Segmenter to search for words instead.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Assertion
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Word_boundary_assertion11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion\n

\n
\n", + "regular_expressions/named_backreference": "

Named backreference: \\k<name>

A named backreference refers to the submatch of a previous named capturing group and matches the same text as that group. For unnamed capturing groups, you need to use the normal backreference syntax.

\n

Syntax

\n
\n

regex

\n
\\k<name>\n
\n

Parameters

\n
name

The name of the group. Must be a valid identifier and refer to an existent named capturing group.

Description

\n
\n

Named backreferences are very similar to normal backreferences: it refers to the text matched by a capturing group and matches the same text. The difference is that you refer to the capturing group by name instead of by number. This makes the regular expression more readable and easier to refactor and maintain.

In Unicode-unaware mode, the sequence \\k only starts a named backreference if the regex contains at least one named capturing group. Otherwise, it is an identity escape and is the same as the literal character k. This is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/\\k/.test(\"k\"); // true\n
\n
\n

Examples

\n

Pairing quotes

\n
\n

The following function matches the title='xxx' and title=\"xxx\" patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group ([2]) returns the string between the matching quote characters:

\n

js

\n
function parseTitle(metastring) {\n  return metastring.match(/title=(?<quote>[\"'])(.*?)\\k<quote>/)[2];\n}\n\nparseTitle('title=\"foo\"'); // 'foo'\nparseTitle(\"title='foo' lang='en'\"); // 'foo'\nparseTitle('title=\"Named capturing groups\\' advantages\"'); // \"Named capturing groups' advantages\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-AtomEscape
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Named_backreference647978No5111.16464794711.39.01.010.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference\n

\n
\n", + "regular_expressions/named_capturing_group": "

Named capturing group: (?<name>...)

A named capturing group is a particular kind of capturing group that allows to give a name to the group. The group's matching result can later be identified by this name instead of by its index in the pattern.

\n

Syntax

\n
\n

regex

\n
(?<name>pattern)\n
\n

Parameters

\n
pattern

A pattern consisting of anything you may use in a regex literal, including a disjunction.

name

The name of the group. Must be a valid identifier.

Description

\n
\n

Named capturing groups can be used just like capturing groups — they also have their match index in the result array, and they can be referenced through \\1, \\2, etc. The only difference is that they can be additionally referenced by their name. The information of the capturing group's match can be accessed through:

All names must be unique within the same pattern. Multiple named capturing groups with the same name result in a syntax error.

\n

js

\n
/(?<name>)(?<name>)/; // SyntaxError: Invalid regular expression: Duplicate capture group name\n
\n

This restriction is relaxed if the duplicate named capturing groups are not in the same disjunction alternative, so for any string input, only one named capturing group can actually be matched. This is a much newer feature, so check browser compatibility before using it.

\n

js

\n
/(?<year>\\d{4})-\\d{2}|\\d{2}-(?<year>\\d{4})/;\n// Works; \"year\" can either come before or after the hyphen\n
\n

Named capturing groups will all be present in the result. If a named capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding property on the groups object has value undefined.

\n

js

\n
/(?<ab>ab)|(?<cd>cd)/.exec(\"cd\").groups; // [Object: null prototype] { ab: undefined, cd: 'cd' }\n
\n

You can get the start and end indices of each named capturing group in the input string by using the d flag. In addition to accessing them on the indices property on the array returned by exec(), you can also access them by their names on indices.groups.

Compared to unnamed capturing groups, named capturing groups have the following advantages:

\n

Examples

\n

Using named capturing groups

\n
\n

The following example parses a timestamp and an author name from a Git log entry (output with git log --format=%ct,%an -- filename):

\n

js

\n
function parseLog(entry) {\n  const { author, timestamp } = /^(?<timestamp>\\d+),(?<author>.+)$/.exec(\n    entry,\n  ).groups;\n  return `${author} committed on ${new Date(\n    parseInt(timestamp) * 1000,\n  ).toLocaleString()}`;\n}\n\nparseLog(\"1560979912,Caroline\"); // \"Caroline committed on 6/19/2019, 5:31:52 PM\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Atom
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Named_capturing_group647978No5111.16464794711.39.01.010.0.0
duplicate_named_capturing_groupsNoNoNoNoNopreviewNoNoNoNoNoNoNoNo
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group\n

\n
\n", + "regular_expressions/backreference": "

Backreference: \\1, \\2

A backreference refers to the submatch of a previous capturing group and matches the same text as that group. For named capturing groups, you may prefer to use the named backreference syntax.

\n

Syntax

\n
\n
\n

regex

\n
\\N\n
\n

Note: N is not a literal character.

\n

Parameters

\n
N

A positive integer referring to the number of a capturing group.

Description

\n
\n

A backreference is a way to match the same text as previously matched by a capturing group. Capturing groups count from 1, so the first capturing group's result can be referenced with \\1, the second with \\2, and so on. \\0 is a character escape for the NUL character.

In case-insensitive matching, the backreference may match text with different casing from the original text.

\n

js

\n
/(b)\\1/i.test(\"bB\"); // true\n
\n

The backreference must refer to an existent capturing group. If the number it specifies is greater than the total number of capturing groups, a syntax error is thrown.

\n

js

\n
/(a)\\2/u; // SyntaxError: Invalid regular expression: Invalid escape\n
\n

In Unicode-unaware mode, invalid backreferences become a legacy octal escape sequence. This is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/(a)\\2/.test(\"a\\x02\"); // true\n
\n

If the referenced capturing group is unmatched (for example, because it belongs to an unmatched alternative in a disjunction), or the group hasn't matched yet (for example, because it lies to the right of the backreference), the backreference always succeeds (as if it matches the empty string).

\n

js

\n
/(?:a|(b))\\1c/.test(\"ac\"); // true\n/\\1(a)/.test(\"a\"); // true\n
\n
\n

Examples

\n

Pairing quotes

\n
\n

The following function matches the title='xxx' and title=\"xxx\" patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group ([2]) returns the string between the matching quote characters:

\n

js

\n
function parseTitle(metastring) {\n  return metastring.match(/title=([\"'])(.*?)\\1/)[2];\n}\n\nparseTitle('title=\"foo\"'); // 'foo'\nparseTitle(\"title='foo' lang='en'\"); // 'foo'\nparseTitle('title=\"Named capturing groups\\' advantages\"'); // \"Named capturing groups' advantages\"\n
\n
\n

Matching duplicate words

\n
\n

The following function finds duplicate words in a string (which are usually typos). Note that it uses the \\w character class escape, which only matches English letters but not any accented letters or other alphabets. If you want more generic matching, you may want to split the string by whitespace and iterate over the resulting array.

\n

js

\n
function findDuplicates(text) {\n  return text.match(/\\b(\\w+)\\s+\\1\\b/i)?.[1];\n}\n\nfindDuplicates(\"foo foo bar\"); // 'foo'\nfindDuplicates(\"foo bar foo\"); // undefined\nfindDuplicates(\"Hello hello\"); // 'Hello'\nfindDuplicates(\"Hello hellos\"); // undefined\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-DecimalEscape
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Backreference11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference\n

\n
\n", + "regular_expressions/input_boundary_assertion": "

Input boundary assertion: ^, $

An input boundary assertion checks if the current position in the string is an input boundary. An input boundary is the start or end of the string; or, if the m flag is set, the start or end of a line.

\n

Syntax

\n
\n

regex

\n
^\n$\n
\n

Description

\n
\n

^ asserts that the current position is the start of input. $ asserts that the current position is the end of input. Both are assertions, so they don't consume any characters.

More precisely, ^ asserts that the character to the left is out of bounds of the string; $ asserts that the character to the right is out of bounds of the string. If the m flag is set, ^ also matches if the character to the left is a line terminator character, and $ also matches if the character to the right is a line terminator.

Unless the m flag is set, the ^ and $ assertions only make sense when placed at the boundaries of the pattern, because any other characters to the left or right of them would necessarily cause the assertion to fail.

The y flag doesn't change the meaning of these assertions — see also anchored sticky flag.

\n

Examples

\n

Removing trailing slashes

\n
\n

The following example removes trailing slashes from a URL string:

\n

js

\n
function removeTrailingSlash(url) {\n  return url.replace(/\\/$/, \"\");\n}\n\nremoveTrailingSlash(\"https://example.com/\"); // \"https://example.com\"\nremoveTrailingSlash(\"https://example.com/docs/\"); // \"https://example.com/docs\"\n
\n
\n

Matching file extensions

\n
\n

The following example checks file types by matching the file extension, which always comes at the end of the string:

\n

js

\n
function isImage(filename) {\n  return /\\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);\n}\n\nisImage(\"image.png\"); // true\nisImage(\"image.jpg\"); // true\nisImage(\"image.pdf\"); // false\n
\n
\n

Matching entire input

\n
\n

Sometimes you want to make sure that your regex matches the entire input, not just a substring of the input. For example, if you are determining if a string is a valid identifier, you can add input boundary assertions to both ends of the pattern:

\n

js

\n
function isValidIdentifier(str) {\n  return /^[$_\\p{ID_Start}][$_\\p{ID_Continue}]*$/u.test(str);\n}\n\nisValidIdentifier(\"foo\"); // true\nisValidIdentifier(\"$1\"); // true\nisValidIdentifier(\"1foo\"); // false\nisValidIdentifier(\"  foo  \"); // false\n
\n

This function is useful when doing codegen (generating code using code), because you can use valid identifiers differently from other string properties, such as dot notation instead of bracket notation:

\n

js

\n
const variables = [\"foo\", \"foo:bar\", \"  foo  \"];\n\nfunction toAssignment(key) {\n  if (isValidIdentifier(key)) {\n    return `globalThis.${key} = undefined;`;\n  }\n  // JSON.stringify() escapes quotes and other special characters\n  return `globalThis[${JSON.stringify(key)}] = undefined;`;\n}\n\nconst statements = variables.map(toAssignment).join(\"\\n\");\n\nconsole.log(statements);\n// globalThis.foo = undefined;\n// globalThis[\"foo:bar\"] = undefined;\n// globalThis[\"  foo  \"] = undefined;\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Assertion
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Input_boundary_assertion11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion\n

\n
\n", + "regular_expressions/lookahead_assertion": "

Lookahead assertion: (?=...), (?!...)

A lookahead assertion \"looks ahead\": it attempts to match the subsequent input with the given pattern, but it does not consume any of the input — if the match is successful, the current position in the input stays the same.

\n

Syntax

\n
\n

regex

\n
(?=pattern)\n(?!pattern)\n
\n

Parameters

\n
pattern

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description

\n
\n

A regular expression generally matches from left to right. This is why lookahead and lookbehind assertions are called as such — lookahead asserts what's on the right, and lookbehind asserts what's on the left.

In order for a (?=pattern) assertion to succeed, the pattern must match the text after the current position, but the current position is not changed. The (?!pattern) form negates the assertion — it succeeds if the pattern does not match at the current position.

The pattern can contain capturing groups. See the capturing groups page for more information on the behavior in this case.

Unlike other regular expression operators, there's no backtracking into a lookahead — this behavior is inherited from Perl. This only matters when the pattern contains capturing groups and the pattern following the lookahead contains backreferences to those captures. For example:

\n

js

\n
/(?=(a+))a*b\\1/.exec(\"baabac\"); // ['aba', 'a']\n// Not ['aaba', 'a']\n
\n

The matching of the pattern above happens as follows:

  1. The lookahead (a+) succeeds before the first \"a\" in \"baabac\", and \"aa\" is captured because the quantifier is greedy.
  2. \na*b matches the \"b\" in \"baabac\".
  3. \n\\1 does not match the following string, because that requires 2 \"a\"s, but only 1 is available. So the matcher backtracks, but it doesn't go into the lookahead, so the capturing group cannot be reduced to 1 \"a\", and the entire match fails at this point.
  4. \nexec() re-attempts matching at the next position — before the second \"a\". This time, the lookahead matches \"a\", and a*b matches \"b\". The backreference \\1 matches the captured \"a\", and the match succeeds.

If the regex is able to backtrack into the lookahead and revise the choice made in there, then the match would succeed at step 3 by (a+) matching the first \"a\" (instead of the first two \"a\"s) and a*b matching \"ab\", without even re-attempting the next input position.

Negative lookaheads can contain capturing groups as well, but backreferences only make sense within the pattern, because if matching continues, pattern would necessarily be unmatched (otherwise the assertion fails). This means outside of the pattern, backreferences to those capturing groups in negative lookaheads always succeed. For example:

\n

js

\n
/(.*?)a(?!(a+)b\\2c)\\2(.*)/.exec(\"baaabaac\"); // ['baaabaac', 'ba', undefined, 'abaac']\n
\n

The matching of the pattern above happens as follows:

  1. The (.*?) pattern is non-greedy, so it starts by matching nothing. However, the next character is a, which fails to match \"b\" in the input.
  2. The (.*?) pattern matches \"b\" so that the a in the pattern matches the first \"a\" in \"baaabaac\".
  3. At this position, the lookahead succeeds to match, because if (a+) matches \"aa\", then (a+)b\\2c matches \"aabaac\". This causes the assertion to fail, so the matcher backtracks.
  4. The (.*?) pattern matches the \"ba\" so that the a in the pattern matches the second \"a\" in \"baaabaac\".
  5. At this position, the lookahead fails to match, because the remaining input does not follow the pattern \"any number of \"a\"s, a \"b\", the same number of \"a\"s, a c\". This causes the assertion to succeed.
  6. However, because nothing was matched within the assertion, the \\2 backreference has no value, so it matches the empty string. This causes the rest of the input to be consumed by the (.*) at the end.

Normally, assertions cannot be quantified. However, in Unicode-unaware mode, lookahead assertions can be quantified. This is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/(?=a)?b/.test(\"b\"); // true; the lookahead is matched 0 time\n
\n
\n

Examples

\n

Matching strings without consuming them

\n
\n

Sometimes it's useful to validate that the matched string is followed by something without returning that as the result. The following example matches a string that is followed by a comma/period, but the punctuation is not included in the result:

\n

js

\n
function getFirstSubsentence(str) {\n  return /^.*?(?=[,.])/.exec(str)?.[0];\n}\n\ngetFirstSubsentence(\"Hello, world!\"); // \"Hello\"\ngetFirstSubsentence(\"Thank you.\"); // \"Thank you\"\n
\n

A similar effect can be achieved by capturing the submatch you are interested in.

\n

Pattern subtraction and intersection

\n
\n

Using lookahead, you can match a string multiple times with different patterns, which allows you to express complex relationships like subtraction (is X but not Y) and intersection (is both X and Y).

The following example matches any identifier that's not a reserved word (only showing three reserved words here for brevity; more reserved words can be added to this disjunction). The [$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]* syntax describes exactly the set of identifier strings in the language spec; you can read more about identifiers in lexical grammar and the \\p escape in Unicode character class escape.

\n

js

\n
function isValidIdentifierName(str) {\n  const re =\n    /^(?!(?:break|case|catch)$)[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*$/u;\n  return re.test(str);\n}\n\nisValidIdentifierName(\"break\"); // false\nisValidIdentifierName(\"foo\"); // true\nisValidIdentifierName(\"cases\"); // true\n
\n

The following example matches a string that's both ASCII and can be used as an identifier part:

\n

js

\n
function isASCIIIDPart(char) {\n  return /^(?=\\p{ASCII}$)\\p{ID_Start}$/u.test(char);\n}\n\nisASCIIIDPart(\"a\"); // true\nisASCIIIDPart(\"α\"); // false\nisASCIIIDPart(\":\"); // false\n
\n

If you are doing intersection and subtraction with finitely many characters, you may want to use the character set intersection syntax enabled with the v flag.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Assertion
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Lookahead_assertion11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion\n

\n
\n", + "regular_expressions/lookbehind_assertion": "

Lookbehind assertion: (?<=...), (?<!...)

A lookbehind assertion \"looks behind\": it attempts to match the previous input with the given pattern, but it does not consume any of the input — if the match is successful, the current position in the input stays the same. It matches each atom in its pattern in the reverse order.

\n

Syntax

\n
\n

regex

\n
(?<=pattern)\n(?<!pattern)\n
\n

Parameters

\n
pattern

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description

\n
\n

A regular expression generally matches from left to right. This is why lookahead and lookbehind assertions are called as such — lookahead asserts what's on the right, and lookbehind asserts what's on the left.

In order for a (?<=pattern) assertion to succeed, the pattern must match the input immediately to the left of the current position, but the current position is not changed before matching the subsequent input. The (?<!pattern) form negates the assertion — it succeeds if the pattern does not match the input immediately to the left of the current position.

Lookbehind generally has the same semantics as lookahead — however, within a lookbehind assertion, the regular expression matches backwards. For example,

\n

js

\n
/(?<=([ab]+)([bc]+))$/.exec(\"abc\"); // ['', 'a', 'bc']\n// Not ['', 'ab', 'c']\n
\n

If the lookbehind matches from left to right, it should first greedily match [ab]+, which makes the first group capture \"ab\", and the remaining \"c\" is captured by [bc]+. However, because [bc]+ is matched first, it greedily grabs \"bc\", leaving only \"a\" for [ab]+.

This behavior is reasonable — the matcher does not know where to start the match (because the lookbehind may not be fixed-length), but it does know where to end (at the current position). Therefore, it starts from the current position and works backwards. (Regexes in some other languages forbid non-fixed-length lookbehind to avoid this issue.)

For quantified capturing groups inside the lookbehind, the match furthest to the left of the input string — instead of the one on the right — is captured because of backward matching. See the capturing groups page for more information. Backreferences inside the lookbehind must appear on the left of the group it's referring to, also due to backward matching. However, disjunctions are still attempted left-to-right.

\n

Examples

\n

Matching strings without consuming them

\n
\n

Similar to lookaheads, lookbehinds can be used to match strings without consuming them so that only useful information is extracted. For example, the following regex matches the number in a price label:

\n

js

\n
function getPrice(label) {\n  return /(?<=\\$)\\d+(?:\\.\\d*)?/.exec(label)?.[0];\n}\n\ngetPrice(\"$10.53\"); // \"10.53\"\ngetPrice(\"10.53\"); // undefined\n
\n

A similar effect can be achieved by capturing the submatch you are interested in.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Assertion
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Lookbehind_assertion627978No4916.46262794616.48.01.08.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion\n

\n
\n", + "regular_expressions/capturing_group": "

Capturing group: (...)

\n

A capturing group groups a subpattern, allowing you to apply a quantifier to the entire group or use disjunctions within it. It memorizes information about the subpattern match, so that you can refer back to it later with a backreference, or access the information through the match results.

If you don't need the result of the subpattern match, use a non-capturing group instead, which improves performance and avoids refactoring hazards.

\n
\n

Syntax

\n
\n

regex

\n
(pattern)\n
\n

Parameters

\n
pattern

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Description

\n
\n

A capturing group acts like the grouping operator in JavaScript expressions, allowing you to use a subpattern as a single atom.

Capturing groups are numbered by the order of their opening parentheses. The first capturing group is numbered 1, the second 2, and so on. Named capturing groups are also capturing groups and are numbered together with other (unnamed) capturing groups. The information of the capturing group's match can be accessed through:

Note: Even in exec()'s result array, capturing groups are accessed by numbers 1, 2, etc., because the 0 element is the entire match. \\0 is not a backreference, but a character escape for the NUL character.

Capturing groups in the regex source code correspond to their results one-to-one. If a capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding result is undefined.

\n

js

\n
/(ab)|(cd)/.exec(\"cd\"); // ['cd', undefined, 'cd']\n
\n

Capturing groups can be quantified. In this case, the match information corresponding to this group is the last match of the group.

\n

js

\n
/([ab])+/.exec(\"abc\"); // ['ab', 'b']; because \"b\" comes after \"a\", this result overwrites the previous one\n
\n

Capturing groups can be used in lookahead and lookbehind assertions. Because lookbehind assertions match their atoms backwards, the final match corresponding to this group is the one that appears to the left end of the string. However, the indices of the match groups still correspond to their relative locations in the regex source.

\n

js

\n
/c(?=(ab))/.exec(\"cab\"); // ['c', 'ab']\n/(?<=(a)(b))c/.exec(\"abc\"); // ['c', 'a', 'b']\n/(?<=([ab])+)c/.exec(\"abc\"); // ['c', 'a']; because \"a\" is seen by the lookbehind after the lookbehind has seen \"b\"\n
\n

Capturing groups can be nested, in which case the outer group is numbered first, then the inner group, because they are ordered by their opening parentheses. If a nested group is repeated by a quantifier, then each time the group matches, the subgroups' results are all overwritten, sometimes with undefined.

\n

js

\n
/((a+)?(b+)?(c))*/.exec(\"aacbbbcac\"); // ['aacbbbcac', 'ac', 'a', undefined, 'c']\n
\n

In the example above, the outer group is matched three times:

  1. Matches \"aac\", with subgroups \"aa\", undefined, and \"c\".
  2. Matches \"bbbc\", with subgroups undefined, \"bbb\", and \"c\".
  3. Matches \"ac\", with subgroups \"a\", undefined, and \"c\".

The \"bbb\" result from the second match is not preserved, because the third match overwrites it with undefined.

You can get the start and end indices of each capturing group in the input string by using the d flag. This creates an extra indices property on the array returned by exec().

You can optionally specify a name to a capturing group, which helps avoid pitfalls related to group positions and indexing. See Named capturing groups for more information.

Parentheses have other purposes in different regex syntaxes. For example, they also enclose lookahead and lookbehind assertions. Because these syntaxes all start with ?, and ? is a quantifier which normally cannot occur directly after (, this does not lead to ambiguities.

\n

Examples

\n

Matching date

\n
\n

The following example matches a date in the format YYYY-MM-DD:

\n

js

\n
function parseDate(input) {\n  const parts = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(input);\n  if (!parts) {\n    return null;\n  }\n  return parts.slice(1).map((p) => parseInt(p, 10));\n}\n\nparseDate(\"2019-01-01\"); // [2019, 1, 1]\nparseDate(\"2019-06-19\"); // [2019, 6, 19]\n
\n
\n

Pairing quotes

\n
\n

The following function matches the title='xxx' and title=\"xxx\" patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group ([2]) returns the string between the matching quote characters:

\n

js

\n
function parseTitle(metastring) {\n  return metastring.match(/title=([\"'])(.*?)\\1/)[2];\n}\n\nparseTitle('title=\"foo\"'); // 'foo'\nparseTitle(\"title='foo' lang='en'\"); // 'foo'\nparseTitle('title=\"Named capturing groups\\' advantages\"'); // \"Named capturing groups' advantages\"\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Atom
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Capturing_group11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group\n

\n
\n", + "regular_expressions/character_class": "

Character class: [...], [^...]

A character class matches any character in or not in a custom set of characters. When the v flag is enabled, it can also be used to match finite-length strings.

\n

Syntax

\n
\n

regex

\n
[]\n[abc]\n[A-Z]\n\n[^]\n[^abc]\n[^A-Z]\n\n// `v` mode only\n[operand1&&operand2]\n[operand1--operand2]\n[\\q{substring}]\n
\n

Parameters

\n
\noperand1, operand2\n

Can be a single character, another square-bracket-enclosed character class, a character class escape, a Unicode character class escape, or a string using the \\q syntax.

substring

A literal string.

Description

\n
\n

A character class specifies a list of characters between square brackets and matches any character in the list. The v flag drastically changes how character classes are parsed and interpreted. The following syntaxes are available in both v mode and non-v mode:

These syntaxes can occur any number of times, and the character sets they represent are unioned. For example, /[a-zA-Z0-9]/ matches any letter or digit.

The ^ prefix in a character class creates a complement class. For example, [^abc] matches any character except a, b, or c. The ^ character is a literal character when it appears in the middle of a character class — for example, [a^b] matches the characters a, ^, and b.

The lexical grammar does a very rough parse of regex literals, so that it does not end the regex literal at a / character which appears within a character class. This means /[/]/ is valid without needing to escape the /.

The boundaries of a character range must not specify more than one character, which happens if you use a character class escape. For example:

\n

js

\n
/[\\s-9]/u; // SyntaxError: Invalid regular expression: Invalid character class\n
\n

In Unicode-unaware mode, character ranges where one boundary is a character class makes the - become a literal character. This is a deprecated syntax for web compatibility, and you should not rely on it.

\n

js

\n
/[\\s-9]/.test(\"-\"); // true\n
\n

In Unicode-unaware mode, regexes are interpreted as a sequence of BMP characters. Therefore, surrogate pairs in character classes represent two characters instead of one.

\n

js

\n
/[😄]/.test(\"\\ud83d\"); // true\n/[😄]/u.test(\"\\ud83d\"); // false\n\n/[😄-😛]/.test(\"😑\"); // SyntaxError: Invalid regular expression: /[😄-😛]/: Range out of order in character class\n/[😄-😛]/u.test(\"😑\"); // true\n
\n

Even if the pattern ignores case, the case of the two ends of a range is significant in determining which characters belong to the range. For example, the pattern /[E-F]/i only matches E, F, e, and f, while the pattern /[E-f]/i matches all uppercase and lowercase ASCII letters (because it spans over E–Z and a–f), as well as [, \\, ], ^, _, and `.

\n

Non-v-mode character class

\n
\n

Non-v-mode character classes interpret most character literally and have less restrictions about the characters they can contain. For example, . is the literal dot character, not the wildcard. The only characters that cannot appear literally are \\, ], and -.

\n

v-mode character class

\n
\n

The basic idea of character classes in v mode remains the same: you can still use most characters literally, use - to denote character ranges, and use escape sequences. One of the most important features of the v flag is set notation within character classes. As previously mentioned, normal character classes can express unions by concatenating two ranges, such as using [A-Z0-9] to mean \"the union of the set [A-Z] and the set [0-9]\". However, there's no easy way to represent other operations with character sets, such as intersection and difference.

With the v flag, intersection is expressed with &&, and subtraction with --. The absence of both implies union. The two operands of && or -- can be a character, character escape, character class escape, or even another character class. For example, to express \"a word character that's not an underscore\", you can use [\\w--_]. You cannot mix operators on the same level. For example, [\\w&&[A-z]--_] is a syntax error. However, because you can nest character classes, you can be explicit by writing [\\w&&[[A-z]--_]] or [[\\w&&[A-z]]--_] (which both mean [A-Za-z]). Similarly, [AB--C] is invalid and you need to write [A[B--C]] (which just means [AB]).

In v mode, the Unicode character class escape \\p can match finite-length strings, such as emojis. For symmetry, regular character classes can also match more than one character. To write a \"string literal\" in a character class, you wrap the string in \\q{...}. The only regex syntax supported here is disjunction — apart from this, \\q must completely enclose literals (including escaped characters). This ensures that character classes can only match finite-length strings with finitely many possibilities.

Because the character class syntax is now more sophisticated, more characters are reserved and forbidden from appearing literally.

Complement character classes [^...] cannot possibly be able to match strings longer than one character. For example, [\\q{ab|c}] is valid and matches the string \"ab\", but [^\\q{ab|c}] is invalid because it's unclear how many characters should be consumed. The check is done by checking if all \\q contain single characters and all \\p specify character properties — for unions, all operands must be purely characters; for intersections, at least one operand must be purely characters; for subtraction, the leftmost operand must be purely characters. The check is syntactic without looking at the actual character set being specified, which means although /[^\\q{ab|c}--\\q{ab}]/v is equivalent to /[^c]/v, it's still rejected.

\n

Complement classes and case-insensitive matching

\n
\n

In non-v-mode, complement character classes [^...] are implemented by simply inverting the match result — that is, [^...] matches whenever [...] doesn't match, and vice versa. However, the other complement classes, such as \\P{...} and \\W, work by eagerly constructing the set consisting of all characters without the specified property. They seem to produce the same behavior, but are made more complex when combined with case-insensitive matching.

Consider the following two regexes:

\n

js

\n
const r1 = /\\p{Lowercase_Letter}/iu;\nconst r2 = /[^\\P{Lowercase_Letter}]/iu;\n
\n

The r2 is a double negation and seems to be equivalent with r1. But in fact, r1 matches all lower- and upper-case ASCII letters, while r2 matches none. To illustrate how it works, pretend that we are only dealing with ASCII characters, not the entire Unicode character set, and r1 and r2 are specified as below:

\n

js

\n
const r1 = /[a-z]/iu;\nconst r2 = /[^A-Z]/iu;\n
\n

Recall that case-insensitive matching happens by folding both the pattern and the input to the same case (see ignoreCase for more details). For r1, the character class a-z stays the same after case folding, while both upper- and lower-case ASCII string inputs are folded to lower-case, so r1 is able to match both \"A\" and \"a\". For r2, the character class A-Z is folded to a-z; however, ^ negates the match result, so that [^A-Z] in effect only matches upper-case strings. However, both upper- and lower-case ASCII string inputs are still folded to lower-case, causing r2 to match nothing.

In v mode, this behavior is fixed — [^...] also eagerly constructs the complement class instead of negating the match result. This makes [^\\P{Lowercase_Letter}] and \\p{Lowercase_Letter} are strictly equivalent.

\n

Examples

\n

Matching hexadecimal digits

\n
\n

The following function determines whether a string contains a valid hexadecimal number:

\n

js

\n
function isHexadecimal(str) {\n  return /^[0-9A-F]+$/i.test(str);\n}\n\nisHexadecimal(\"2F3\"); // true\nisHexadecimal(\"beef\"); // true\nisHexadecimal(\"undefined\"); // false\n
\n
\n

Using intersection

\n
\n

The following function matches Greek letters.

\n

js

\n
function greekLetters(str) {\n  return str.match(/[\\p{Script_Extensions=Greek}&&\\p{Letter}]/gv);\n}\n\n// 𐆊 is U+1018A GREEK ZERO SIGN\ngreekLetters(\"π𐆊P0零αAΣ\"); // [ 'π', 'α', 'Σ' ]\n
\n
\n

Using subtraction

\n
\n

The following function matches all non-ASCII numbers.

\n

js

\n
function nonASCIINumbers(str) {\n  return str.match(/[\\p{Decimal_Number}--[0-9]]/gv);\n}\n\n// 𑜹 is U+11739 AHOM DIGIT NINE\nnonASCIINumbers(\"𐆊0零1𝟜𑜹a\"); // [ '𝟜', '𑜹' ]\n
\n
\n

Matching strings

\n
\n

The following function matches all line terminator sequences, including the line terminator characters and the sequence \\r\\n (CRLF).

\n

js

\n
function getLineTerminators(str) {\n  return str.match(/[\\r\\n\\u2028\\u2029\\q{\\r\\n}]/gv);\n}\n\ngetLineTerminators(`\nA poem\\r\nIs split\\r\\n\nInto many\nStanzas\n`); // [ '\\r', '\\r\\n', '\\n' ]\n
\n

This example is exactly equivalent to /(?:\\r|\\n|\\u2028|\\u2029|\\r\\n)/gu or /(?:[\\r\\n\\u2028\\u2029]|\\r\\n)/gu, except shorter.

The most useful case of \\q{} is when doing subtraction and intersection. Previously, this was possible with multiple lookaheads. The following function matches flags that are not one of the American, Chinese, Russian, British, and French flags.

\n

js

\n
function notUNSCPermanentMember(flag) {\n  return /^[\\p{RGI_Emoji_Flag_Sequence}--\\q{🇺🇸|🇨🇳|🇷🇺|🇬🇧|🇫🇷}]$/v.test(flag);\n}\n\nnotUNSCPermanentMember(\"🇺🇸\"); // false\nnotUNSCPermanentMember(\"🇩🇪\"); // true\n
\n

This example is mostly equivalent to /^(?!🇺🇸|🇨🇳|🇷🇺|🇬🇧|🇫🇷)\\p{RGI_Emoji_Flag_Sequence}$/v, except perhaps more performant.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-CharacterClass
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Character_class11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class\n

\n
\n", + "regular_expressions/character_class_escape": "

Character class escape: \\d, \\D, \\w, \\W, \\s, \\S

A character class escape is an escape sequence that represents a set of characters.

\n

Syntax

\n
\n
\n

regex

\n
\\d, \\D\n\\s, \\S\n\\w, \\W\n
\n

Note: , is not part of the syntax.

\n

Description

\n
\n

Unlike character escapes, character class escapes represent a predefined set of characters, much like a character class. The following character classes are supported:

\\d

Matches any digit character. Equivalent to [0-9].

\\w

Matches any word character, where a word character includes letters (A–Z, a–z), numbers (0–9), and underscore (_). If the regex is Unicode-aware and the i flag is set, it also matches other Unicode characters that get canonicalized to one of the characters above through case folding.

\\s

Matches any whitespace or line terminator character.

The uppercase forms \\D, \\W, and \\S create complement character classes for \\d, \\w, and \\s, respectively. They match any character that is not in the set of characters matched by the lowercase form.

Unicode character class escapes start with \\p and \\P, but they are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the p or P character.

Character class escapes can be used in character classes. However, they cannot be used as boundaries of character ranges, which is only allowed as a deprecated syntax for web compatibility, and you should not rely on it.

\n

Examples

\n

Splitting by whitespace

\n
\n

The following example splits a string into an array of words, supporting all kinds of whitespace separators:

\n

js

\n
function splitWords(str) {\n  return str.split(/\\s+/);\n}\n\nsplitWords(`Look at the stars\nLook  how they\\tshine for you`);\n// ['Look', 'at', 'the', 'stars', 'Look', 'how', 'they', 'shine', 'for', 'you']\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-CharacterClassEscape
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Character_class_escape11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape\n

\n
\n", + "regular_expressions/literal_character": "

Literal character: a, b

A literal character specifies exactly itself to be matched in the input text.

\n

Syntax

\n
\n

regex

\n
c\n
\n

Parameters

\n
c

A single character that is not one of the syntax characters described below.

Description

\n
\n

In regular expressions, most characters can appear literally. They are usually the most basic building blocks of patterns. For example, here is a pattern from the Removing HTML tags example:

\n

js

\n
const pattern = /<.+?>/g;\n
\n

In this example, ., +, and ? are called syntax characters. They have special meanings in regular expressions. The rest of the characters in the pattern (< and >) are literal characters. They match themselves in the input text: the left and right angle brackets.

The following characters are syntax characters in regular expressions, and they cannot appear as literal characters:

Within character classes, more characters can appear literally. For more information, see the Character class page. For example \\. and [.] both match a literal .. In v-mode character classes, however, there are a different set of characters reserved as syntax characters. To be most comprehensive, below is a table of ASCII characters and whether they may appear escaped or unescaped in different contexts, where \"✅\" means the character represents itself, \"❌\" means it throws a syntax error, and \"⚠️\" means the character is valid but means something other than itself.

Characters Outside character classes in u or v mode In u-mode character classes In v-mode character classes
Unescaped Escaped Unescaped Escaped Unescaped Escaped
123456789 \"'
ACEFGHIJKLMN
OPQRTUVXYZ_
aceghijklmop
quxyz
!#%&,:;<=>@`~
]
()[{}
*+?
/
0DSWbdfnrstvw ⚠️ ⚠️ ⚠️
B ⚠️
$. ⚠️
| ⚠️
- ✅⚠️ ❌⚠️
^ ⚠️ ✅⚠️ ✅⚠️
\\ ❌⚠️ ❌⚠️ ❌⚠️

Note: The characters that can both be escaped and unescaped in v-mode character classes are exactly those forbidden as \"double punctuators\". See v-mode character classes for more information.

Whenever you want to match a syntax character literally, you need to escape it with a backslash (\\). For example, to match a literal * in a pattern, you need to write \\* in the pattern. Using syntax characters as literal characters either leads to unexpected results or causes syntax errors — for example, /*/ is not a valid regular expression because the quantifier is not preceded by a pattern. In Unicode-unaware mode, ], {, and } may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a deprecated syntax for web compatibility, and you should not rely on it.

Regular expression literals cannot be specified with certain non-syntax literal characters. / cannot appear as a literal character in a regular expression literal, because / is used as the delimiter of the literal itself. You need to escape it as \\/ if you want to match a literal /. Line terminators cannot appear as literal characters in a regular expression literal either, because a literal cannot span multiple lines. You need to use a character escape like \\n instead. There are no such restrictions when using the RegExp() constructor, although string literals have their own escaping rules (for example, \"\\\\\" actually denotes a single backslash character, so new RegExp(\"\\\\*\") and /\\*/ are equivalent).

In Unicode-unaware mode, the pattern is interpreted as a sequence of UTF-16 code units. This means surrogate pairs actually represent two literal characters. This causes unexpected behaviors when paired with other features:

\n

js

\n
/^[😄]$/.test(\"😄\"); // false, because the pattern is interpreted as /^[\\ud83d\\udc04]$/\n/^😄+$/.test(\"😄😄\"); // false, because the pattern is interpreted as /^\\ud83d\\udc04+$/\n
\n

In Unicode-aware mode, the pattern is interpreted as a sequence of Unicode code points, and surrogate pairs do not get split. Therefore, you should always prefer to use the u flag.

\n

Examples

\n

Using literal characters

\n
\n

The following example is copied from Character escape. The a and b characters are literal characters in the pattern, and \\n is an escaped character because it cannot appear literally in a regular expression literal.

\n

js

\n
const pattern = /a\\nb/;\nconst string = `a\nb`;\nconsole.log(pattern.test(string)); // true\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-PatternCharacter
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Literal_character11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character\n

\n
\n", + "regular_expressions/non-capturing_group": "

Non-capturing group: (?:...)

A non-capturing group groups a subpattern, allowing you to apply a quantifier to the entire group or use disjunctions within it. It acts like the grouping operator in JavaScript expressions, and unlike capturing groups, it does not memorize the matched text, allowing for better performance and avoiding confusion when the pattern also contains useful capturing groups.

\n

Syntax

\n
\n

regex

\n
(?:pattern)\n
\n

Parameters

\n
pattern

A pattern consisting of anything you may use in a regex literal, including a disjunction.

Examples

\n

Grouping a subpattern and applying a quantifier

\n
\n

In the following example, we test if a file path ends with styles.css or styles.[a hex hash].css. Because the entire \\.[\\da-f]+ part is optional, in order to apply the ? quantifier to it, we need to group it into a new atom. Using a non-capturing group improves performance by not creating the extra match information that we don't need.

\n

js

\n
function isStylesheet(path) {\n  return /styles(?:\\.[\\da-f]+)?\\.css$/.test(path);\n}\n\nisStylesheet(\"styles.css\"); // true\nisStylesheet(\"styles.1234.css\"); // true\nisStylesheet(\"styles.cafe.css\"); // true\nisStylesheet(\"styles.1234.min.css\"); // false\n
\n
\n

Grouping a disjunction

\n
\n

A disjunction has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it. You are advised to use a non-capturing group unless you rely on the matched text of the disjunction. The following example matches file extensions, using the same code as the input boundary assertion article:

\n

js

\n
function isImage(filename) {\n  return /\\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);\n}\n\nisImage(\"image.png\"); // true\nisImage(\"image.jpg\"); // true\nisImage(\"image.pdf\"); // false\n
\n
\n

Avoiding refactoring hazards

\n
\n

Capturing groups are accessed by their position in the pattern. If you add or remove a capturing group, you must also update the positions of the other capturing groups, if you are accessing them through match results or backreferences. This can be a source of bugs, especially if most groups are purely for syntactic purposes (to apply quantifiers or to group disjunctions). Using non-capturing groups avoids this problem, and allows the indices of actual capturing groups to be easily tracked.

For example, suppose we have a function that matches the title='xxx' pattern in a string (example taken from capturing group). To ensure the quotes match, we use a backreference to refer to the first quote.

\n

js

\n
function parseTitle(metastring) {\n  return metastring.match(/title=([\"'])(.*?)\\1/)[2];\n}\n\nparseTitle('title=\"foo\"'); // 'foo'\n
\n

If we later decided to add name='xxx' as an alias for title=, we will need to group the disjunction in another group:

\n

js

\n
function parseTitle(metastring) {\n  // Oops — the backreference and index access are now off by one!\n  return metastring.match(/(title|name)=([\"'])(.*?)\\1/)[2];\n}\n\nparseTitle('name=\"foo\"'); // Cannot read properties of null (reading '2')\n// Because \\1 now refers to the \"name\" string, which isn't found at the end.\n
\n

Instead of locating all places where we are referring to the capturing groups' indices and updating them one-by-one, it's better to avoid using a capturing group:

\n

js

\n
function parseTitle(metastring) {\n  // Do not capture the title|name disjunction\n  // because we don't use its value\n  return metastring.match(/(?:title|name)=([\"'])(.*?)\\1/)[2];\n}\n\nparseTitle('name=\"foo\"'); // 'foo'\n
\n

Named capturing groups are another way to avoid refactoring hazards. It allows capturing groups to accessed by a custom name, which is unaffected when other capturing groups are added or removed.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Atom
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Non-capturing_group11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group\n

\n
\n", + "regular_expressions/wildcard": "

Wildcard: .

A wildcard matches all characters except line terminators. It also matches line terminators if the s flag is set.

\n

Syntax

\n
\n

regex

\n
.\n
\n

Description

\n
\n

. matches any character except line terminators. If the s flag is set, . also matches line terminators.

The exact character set matched by . depends on whether the regex is Unicode-aware. If it is Unicode-aware, . matches any Unicode code point; otherwise, it matches any UTF-16 code unit. For example:

\n

js

\n
/../.test(\"😄\"); // true; matches two UTF-16 code units as a surrogate pair\n/../u.test(\"😄\"); // false; input only has one Unicode character\n
\n
\n

Examples

\n

Usage with quantifiers

\n
\n

Wildcards are often used with quantifiers to match any character sequence, until the next character of interest is found. For example, the following example extracts the title of a Markdown page in the form # Title:

\n

js

\n
function parseTitle(entry) {\n  // Use multiline mode because the title may not be at the start of\n  // the file. Note that the m flag does not make . match line\n  // terminators, so the title must be on a single line\n  // Return text matched by the first capturing group.\n  return /^#[ \\t]+(.+)$/m.exec(entry)?.[1];\n}\n\nparseTitle(\"# Hello world\"); // \"Hello world\"\nparseTitle(\"## Subsection\"); // undefined\nparseTitle(`\n---\nslug: Web/JavaScript/Reference/Regular_expressions/Wildcard\n---\n\n# Wildcard: .\n\nA **wildcard** matches all characters except line terminators.\n`); // \"Wildcard: .\"\n
\n
\n

Matching code block content

\n
\n

The following example matches the content of a code block enclosed by three backticks in Markdown. It uses the s flag to make . match line terminators, because the content of a code block may span multiple lines:

\n

js

\n
function parseCodeBlock(entry) {\n  return /^```.*?^(.+?)\\n```/ms.exec(entry)?.[1];\n}\n\nparseCodeBlock(`\n\\`\\`\\`js\nconsole.log(\"Hello world\");\n\\`\\`\\`\n`); // \"console.log(\"Hello world\");\"\n\nparseCodeBlock(`\nA \\`try...catch\\` statement must have the blocks enclosed in curly braces.\n\n\\`\\`\\`js example-bad\ntry\n  doSomething();\ncatch (e)\n  console.log(e);\n\\`\\`\\`\n`); // \"try\\n  doSomething();\\ncatch (e)\\n  console.log(e);\"\n
\n

Warning: These examples are for demonstration only. If you want to parse Markdown, use a dedicated Markdown parser because there are many edge cases to consider.

\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Atom
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Wildcard11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Wildcard\n

\n
\n", + "regular_expressions/disjunction": "

Disjunction: |

A disjunction specifies multiple alternatives. Any alternative matching the input causes the entire disjunction to be matched.

\n

Syntax

\n
\n

regex

\n
alternative1|alternative2\nalternative1|alternative2|alternative3|…\n
\n

Parameters

\n
alternativeN

One alternative pattern, composed of a sequence of atoms and assertions. Successfully matching one alternative causes the entire disjunction to be matched.

Description

\n
\n

The | regular expression operator separates two or more alternatives. The pattern first tries to match the first alternative; if it fails, it tries to match the second one, and so on. For example, the following matches \"a\" instead of \"ab\", because the first alternative already matches successfully:

\n

js

\n
/a|ab/.exec(\"abc\"); // ['a']\n
\n

The | operator has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it.

When a grouped disjunction has more expressions after it, the matching begins by selecting the first alternative and attempting to match the rest of the regular expression. If the rest of the regular expression fails to match, the matcher tries the next alternative instead. For example,

\n

js

\n
/(?:(a)|(ab))(?:(c)|(bc))/.exec(\"abc\"); // ['abc', 'a', undefined, undefined, 'bc']\n// Not ['abc', undefined, 'ab', 'c', undefined]\n
\n

This is because by selecting a in the first alternative, it's possible to select bc in the second alternative and result in a successful match. This process is called backtracking, because the matcher first goes beyond the disjunction and then comes back to it when subsequent matching fails.

Note also that any capturing parentheses inside an alternative that's not matched produce undefined in the resulting array.

An alternative can be empty, in which case it matches the empty string (in other words, always matches).

Alternatives are always attempted left-to-right, regardless of the direction of matching (which is reversed in a lookbehind).

\n

Examples

\n

Matching file extensions

\n
\n

The following example matches file extensions, using the same code as the input boundary assertion article:

\n

js

\n
function isImage(filename) {\n  return /\\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);\n}\n\nisImage(\"image.png\"); // true\nisImage(\"image.jpg\"); // true\nisImage(\"image.pdf\"); // false\n
\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Language Specification
# prod-Disjunction
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
Disjunction11214514.418410.111.01.00.10.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction\n

\n
\n", + "global_objects/intl/segmenter/segment/segments/containing": "

Segments.prototype.containing()

The containing() method of Segments instances returns an object describing the segment in the string that includes the code unit at the specified index.

\n

Try it

\n

Syntax

\n
\n

js

\n
containing(codeUnitIndex)\n
\n

Parameters

\n
\ncodeUnitIndex Optional\n

A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to 0.

Return value

\n
\n

An object describing the segment of the original string with the following properties, or undefined if the supplied index value is out of bounds.

segment

A string containing the segment extracted from the original input string.

index

The code unit index in the original input string at which the segment begins.

input

The complete input string that was segmented.

isWordLike

A boolean value only if granularity is \"word\"; otherwise, undefined. If granularity is \"word\", then isWordLike is true when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, false.

\n

Examples

\n
\n

js

\n
// ┃0 1 2 3 4 5┃6┃7┃8┃9  ← code unit index\n// ┃A l l o n s┃-┃y┃!┃   ← code unit\nconst input = \"Allons-y!\";\n\nconst segmenter = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\nconst segments = segmenter.segment(input);\n\nlet current = segments.containing();\n// { index: 0, segment: \"Allons\", isWordLike: true }\n\ncurrent = segments.containing(4);\n// { index: 0, segment: \"Allons\", isWordLike: true }\n\ncurrent = segments.containing(6);\n// { index: 6, segment: \"-\", isWordLike: false }\n\ncurrent = segments.containing(current.index + current.segment.length);\n// { index: 7, segment: \"y\", isWordLike: true }\n\ncurrent = segments.containing(current.index + current.segment.length);\n// { index: 8, segment: \"!\", isWordLike: false }\n\ncurrent = segments.containing(current.index + current.segment.length);\n// undefined\n
\n

Specifications

\n
\n\n\n
Specification
ECMAScript Internationalization API Specification
# sec-%segmentsprototype%.containing
\n

Browser compatibility

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on IOSSamsung InternetDenoNode.js
containing8787NoNo7314.18787No6214.514.01.816.0.0
\n

See also

\n
\n

\n © 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing\n

\n
\n" +} diff --git a/src/sidebar/index.json b/src/sidebar/index.json new file mode 100644 index 0000000..2bdb9a0 --- /dev/null +++ b/src/sidebar/index.json @@ -0,0 +1,4213 @@ +{ + "entries": [ + { "name": "Addition", "path": "operators/addition", "type": "Operators" }, + { + "name": "Addition assignment", + "path": "operators/addition_assignment", + "type": "Operators" + }, + { + "name": "AggregateError", + "path": "global_objects/aggregateerror", + "type": "Errors" + }, + { + "name": "AggregateError.aggregateError", + "path": "global_objects/aggregateerror/aggregateerror", + "type": "Errors" + }, + { + "name": "AggregateError.errors", + "path": "global_objects/aggregateerror/errors", + "type": "Errors" + }, + { "name": "arguments", "path": "functions/arguments", "type": "Function" }, + { + "name": "arguments.@@iterator", + "path": "functions/arguments/@@iterator", + "type": "Function" + }, + { + "name": "arguments.callee", + "path": "functions/arguments/callee", + "type": "Function" + }, + { + "name": "arguments.length", + "path": "functions/arguments/length", + "type": "Function" + }, + { "name": "Array", "path": "global_objects/array", "type": "Array" }, + { + "name": "Array.@@iterator", + "path": "global_objects/array/@@iterator", + "type": "Array" + }, + { + "name": "Array.@@species", + "path": "global_objects/array/@@species", + "type": "Array" + }, + { + "name": "array.@@unscopables", + "path": "global_objects/array/@@unscopables", + "type": "Array" + }, + { + "name": "Array.array", + "path": "global_objects/array/array", + "type": "Array" + }, + { "name": "array.at", "path": "global_objects/array/at", "type": "Array" }, + { + "name": "array.concat", + "path": "global_objects/array/concat", + "type": "Array" + }, + { + "name": "Array.copyWithin", + "path": "global_objects/array/copywithin", + "type": "Array" + }, + { + "name": "array.entries", + "path": "global_objects/array/entries", + "type": "Array" + }, + { + "name": "array.every", + "path": "global_objects/array/every", + "type": "Array" + }, + { + "name": "array.fill", + "path": "global_objects/array/fill", + "type": "Array" + }, + { + "name": "array.filter", + "path": "global_objects/array/filter", + "type": "Array" + }, + { + "name": "array.find", + "path": "global_objects/array/find", + "type": "Array" + }, + { + "name": "Array.findIndex", + "path": "global_objects/array/findindex", + "type": "Array" + }, + { + "name": "Array.findLast", + "path": "global_objects/array/findlast", + "type": "Array" + }, + { + "name": "Array.findLastIndex", + "path": "global_objects/array/findlastindex", + "type": "Array" + }, + { + "name": "array.flat", + "path": "global_objects/array/flat", + "type": "Array" + }, + { + "name": "Array.flatMap", + "path": "global_objects/array/flatmap", + "type": "Array" + }, + { + "name": "Array.forEach", + "path": "global_objects/array/foreach", + "type": "Array" + }, + { + "name": "Array.from", + "path": "global_objects/array/from", + "type": "Array" + }, + { + "name": "Array.fromAsync", + "path": "global_objects/array/fromasync", + "type": "Array" + }, + { + "name": "array.includes", + "path": "global_objects/array/includes", + "type": "Array" + }, + { + "name": "Array.indexOf", + "path": "global_objects/array/indexof", + "type": "Array" + }, + { + "name": "Array.isArray", + "path": "global_objects/array/isarray", + "type": "Array" + }, + { + "name": "array.join", + "path": "global_objects/array/join", + "type": "Array" + }, + { + "name": "array.keys", + "path": "global_objects/array/keys", + "type": "Array" + }, + { + "name": "Array.lastIndexOf", + "path": "global_objects/array/lastindexof", + "type": "Array" + }, + { + "name": "Array.length", + "path": "global_objects/array/length", + "type": "Array" + }, + { + "name": "array.map", + "path": "global_objects/array/map", + "type": "Array" + }, + { "name": "Array.of", "path": "global_objects/array/of", "type": "Array" }, + { + "name": "array.pop", + "path": "global_objects/array/pop", + "type": "Array" + }, + { + "name": "array.push", + "path": "global_objects/array/push", + "type": "Array" + }, + { + "name": "array.reduce", + "path": "global_objects/array/reduce", + "type": "Array" + }, + { + "name": "Array.reduceRight", + "path": "global_objects/array/reduceright", + "type": "Array" + }, + { + "name": "array.reverse", + "path": "global_objects/array/reverse", + "type": "Array" + }, + { + "name": "array.shift", + "path": "global_objects/array/shift", + "type": "Array" + }, + { + "name": "array.slice", + "path": "global_objects/array/slice", + "type": "Array" + }, + { + "name": "array.some", + "path": "global_objects/array/some", + "type": "Array" + }, + { + "name": "array.sort", + "path": "global_objects/array/sort", + "type": "Array" + }, + { + "name": "array.splice", + "path": "global_objects/array/splice", + "type": "Array" + }, + { + "name": "Array.toLocaleString", + "path": "global_objects/array/tolocalestring", + "type": "Array" + }, + { + "name": "Array.toReversed", + "path": "global_objects/array/toreversed", + "type": "Array" + }, + { + "name": "Array.toSorted", + "path": "global_objects/array/tosorted", + "type": "Array" + }, + { + "name": "Array.toSpliced", + "path": "global_objects/array/tospliced", + "type": "Array" + }, + { + "name": "Array.toString", + "path": "global_objects/array/tostring", + "type": "Array" + }, + { + "name": "array.unshift", + "path": "global_objects/array/unshift", + "type": "Array" + }, + { + "name": "array.values", + "path": "global_objects/array/values", + "type": "Array" + }, + { + "name": "array.with", + "path": "global_objects/array/with", + "type": "Array" + }, + { + "name": "ArrayBuffer", + "path": "global_objects/arraybuffer", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.@@species", + "path": "global_objects/arraybuffer/@@species", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.arrayBuffer", + "path": "global_objects/arraybuffer/arraybuffer", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.byteLength", + "path": "global_objects/arraybuffer/bytelength", + "type": "ArrayBuffer" + }, + { + "name": "arrayBuffer.detached", + "path": "global_objects/arraybuffer/detached", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.isView", + "path": "global_objects/arraybuffer/isview", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.maxByteLength", + "path": "global_objects/arraybuffer/maxbytelength", + "type": "ArrayBuffer" + }, + { + "name": "arrayBuffer.resizable", + "path": "global_objects/arraybuffer/resizable", + "type": "ArrayBuffer" + }, + { + "name": "arrayBuffer.resize", + "path": "global_objects/arraybuffer/resize", + "type": "ArrayBuffer" + }, + { + "name": "arrayBuffer.slice", + "path": "global_objects/arraybuffer/slice", + "type": "ArrayBuffer" + }, + { + "name": "arrayBuffer.transfer", + "path": "global_objects/arraybuffer/transfer", + "type": "ArrayBuffer" + }, + { + "name": "ArrayBuffer.transferToFixedLength", + "path": "global_objects/arraybuffer/transfertofixedlength", + "type": "ArrayBuffer" + }, + { + "name": "Arrow functions", + "path": "functions/arrow_functions", + "type": "Function" + }, + { + "name": "Assignment", + "path": "operators/assignment", + "type": "Operators" + }, + { + "name": "async function", + "path": "statements/async_function", + "type": "Statements" + }, + { + "name": "async function", + "path": "operators/async_function", + "type": "Operators" + }, + { + "name": "async function*", + "path": "statements/async_function*", + "type": "Statements" + }, + { + "name": "async function*", + "path": "operators/async_function*", + "type": "Operators" + }, + { + "name": "AsyncFunction", + "path": "global_objects/asyncfunction", + "type": "Function" + }, + { + "name": "AsyncFunction.asyncFunction", + "path": "global_objects/asyncfunction/asyncfunction", + "type": "Function" + }, + { + "name": "AsyncGenerator", + "path": "global_objects/asyncgenerator", + "type": "Global Objects" + }, + { + "name": "AsyncGenerator.next", + "path": "global_objects/asyncgenerator/next", + "type": "AsyncGenerator" + }, + { + "name": "AsyncGenerator.return", + "path": "global_objects/asyncgenerator/return", + "type": "AsyncGenerator" + }, + { + "name": "AsyncGenerator.throw", + "path": "global_objects/asyncgenerator/throw", + "type": "AsyncGenerator" + }, + { + "name": "AsyncGeneratorFunction", + "path": "global_objects/asyncgeneratorfunction", + "type": "Function" + }, + { + "name": "AsyncGeneratorFunction.asyncGeneratorFunction", + "path": "global_objects/asyncgeneratorfunction/asyncgeneratorfunction", + "type": "Function" + }, + { + "name": "AsyncIterator", + "path": "global_objects/asynciterator", + "type": "Global Objects" + }, + { + "name": "AsyncIterator.@@asyncIterator", + "path": "global_objects/asynciterator/@@asynciterator", + "type": "AsyncIterator" + }, + { "name": "Atomics", "path": "global_objects/atomics", "type": "Atomics" }, + { + "name": "Atomics.add", + "path": "global_objects/atomics/add", + "type": "Atomics" + }, + { + "name": "Atomics.and", + "path": "global_objects/atomics/and", + "type": "Atomics" + }, + { + "name": "Atomics.compareExchange", + "path": "global_objects/atomics/compareexchange", + "type": "Atomics" + }, + { + "name": "Atomics.exchange", + "path": "global_objects/atomics/exchange", + "type": "Atomics" + }, + { + "name": "Atomics.isLockFree", + "path": "global_objects/atomics/islockfree", + "type": "Atomics" + }, + { + "name": "Atomics.load", + "path": "global_objects/atomics/load", + "type": "Atomics" + }, + { + "name": "Atomics.notify", + "path": "global_objects/atomics/notify", + "type": "Atomics" + }, + { + "name": "Atomics.or", + "path": "global_objects/atomics/or", + "type": "Atomics" + }, + { + "name": "Atomics.store", + "path": "global_objects/atomics/store", + "type": "Atomics" + }, + { + "name": "Atomics.sub", + "path": "global_objects/atomics/sub", + "type": "Atomics" + }, + { + "name": "Atomics.wait", + "path": "global_objects/atomics/wait", + "type": "Atomics" + }, + { + "name": "Atomics.waitAsync", + "path": "global_objects/atomics/waitasync", + "type": "Atomics" + }, + { + "name": "Atomics.xor", + "path": "global_objects/atomics/xor", + "type": "Atomics" + }, + { "name": "await", "path": "operators/await", "type": "Operators" }, + { + "name": "BigInt", + "path": "global_objects/bigint", + "type": "Global Objects" + }, + { + "name": "BigInt.asIntN", + "path": "global_objects/bigint/asintn", + "type": "BigInt" + }, + { + "name": "BigInt.asUintN", + "path": "global_objects/bigint/asuintn", + "type": "BigInt" + }, + { + "name": "BigInt.bigInt", + "path": "global_objects/bigint/bigint", + "type": "BigInt" + }, + { + "name": "BigInt.toLocaleString", + "path": "global_objects/bigint/tolocalestring", + "type": "BigInt" + }, + { + "name": "BigInt.toString", + "path": "global_objects/bigint/tostring", + "type": "BigInt" + }, + { + "name": "BigInt.valueOf", + "path": "global_objects/bigint/valueof", + "type": "BigInt" + }, + { + "name": "BigInt64Array", + "path": "global_objects/bigint64array", + "type": "Global Objects" + }, + { + "name": "BigInt64Array.bigInt64Array", + "path": "global_objects/bigint64array/bigint64array", + "type": "BigInt64Array" + }, + { + "name": "BigUint64Array", + "path": "global_objects/biguint64array", + "type": "Global Objects" + }, + { + "name": "BigUint64Array.bigUint64Array", + "path": "global_objects/biguint64array/biguint64array", + "type": "BigUint64Array" + }, + { + "name": "Bitwise AND", + "path": "operators/bitwise_and", + "type": "Operators" + }, + { + "name": "Bitwise AND assignment", + "path": "operators/bitwise_and_assignment", + "type": "Operators" + }, + { + "name": "Bitwise NOT", + "path": "operators/bitwise_not", + "type": "Operators" + }, + { + "name": "Bitwise OR", + "path": "operators/bitwise_or", + "type": "Operators" + }, + { + "name": "Bitwise OR assignment", + "path": "operators/bitwise_or_assignment", + "type": "Operators" + }, + { + "name": "Bitwise XOR", + "path": "operators/bitwise_xor", + "type": "Operators" + }, + { + "name": "Bitwise XOR assignment", + "path": "operators/bitwise_xor_assignment", + "type": "Operators" + }, + { "name": "block", "path": "statements/block", "type": "Statements" }, + { "name": "Boolean", "path": "global_objects/boolean", "type": "Boolean" }, + { + "name": "Boolean.boolean", + "path": "global_objects/boolean/boolean", + "type": "Boolean" + }, + { + "name": "Boolean.toString", + "path": "global_objects/boolean/tostring", + "type": "Boolean" + }, + { + "name": "Boolean.valueOf", + "path": "global_objects/boolean/valueof", + "type": "Boolean" + }, + { "name": "break", "path": "statements/break", "type": "Statements" }, + { "name": "class", "path": "operators/class", "type": "Operators" }, + { "name": "class", "path": "statements/class", "type": "Statements" }, + { "name": "Classes", "path": "classes", "type": "Classes" }, + { + "name": "Comma operator", + "path": "operators/comma_operator", + "type": "Operators" + }, + { + "name": "Conditional operator", + "path": "operators/conditional_operator", + "type": "Operators" + }, + { "name": "const", "path": "statements/const", "type": "Statements" }, + { "name": "constructor", "path": "classes/constructor", "type": "Classes" }, + { "name": "continue", "path": "statements/continue", "type": "Statements" }, + { + "name": "DataView", + "path": "global_objects/dataview", + "type": "DataView" + }, + { + "name": "dataView.buffer", + "path": "global_objects/dataview/buffer", + "type": "DataView" + }, + { + "name": "DataView.byteLength", + "path": "global_objects/dataview/bytelength", + "type": "DataView" + }, + { + "name": "DataView.byteOffset", + "path": "global_objects/dataview/byteoffset", + "type": "DataView" + }, + { + "name": "DataView.dataView", + "path": "global_objects/dataview/dataview", + "type": "DataView" + }, + { + "name": "DataView.getBigInt64", + "path": "global_objects/dataview/getbigint64", + "type": "DataView" + }, + { + "name": "DataView.getBigUint64", + "path": "global_objects/dataview/getbiguint64", + "type": "DataView" + }, + { + "name": "DataView.getFloat32", + "path": "global_objects/dataview/getfloat32", + "type": "DataView" + }, + { + "name": "DataView.getFloat64", + "path": "global_objects/dataview/getfloat64", + "type": "DataView" + }, + { + "name": "DataView.getInt16", + "path": "global_objects/dataview/getint16", + "type": "DataView" + }, + { + "name": "DataView.getInt32", + "path": "global_objects/dataview/getint32", + "type": "DataView" + }, + { + "name": "DataView.getInt8", + "path": "global_objects/dataview/getint8", + "type": "DataView" + }, + { + "name": "DataView.getUint16", + "path": "global_objects/dataview/getuint16", + "type": "DataView" + }, + { + "name": "DataView.getUint32", + "path": "global_objects/dataview/getuint32", + "type": "DataView" + }, + { + "name": "DataView.getUint8", + "path": "global_objects/dataview/getuint8", + "type": "DataView" + }, + { + "name": "DataView.setBigInt64", + "path": "global_objects/dataview/setbigint64", + "type": "DataView" + }, + { + "name": "DataView.setBigUint64", + "path": "global_objects/dataview/setbiguint64", + "type": "DataView" + }, + { + "name": "DataView.setFloat32", + "path": "global_objects/dataview/setfloat32", + "type": "DataView" + }, + { + "name": "DataView.setFloat64", + "path": "global_objects/dataview/setfloat64", + "type": "DataView" + }, + { + "name": "DataView.setInt16", + "path": "global_objects/dataview/setint16", + "type": "DataView" + }, + { + "name": "DataView.setInt32", + "path": "global_objects/dataview/setint32", + "type": "DataView" + }, + { + "name": "DataView.setInt8", + "path": "global_objects/dataview/setint8", + "type": "DataView" + }, + { + "name": "DataView.setUint16", + "path": "global_objects/dataview/setuint16", + "type": "DataView" + }, + { + "name": "DataView.setUint32", + "path": "global_objects/dataview/setuint32", + "type": "DataView" + }, + { + "name": "DataView.setUint8", + "path": "global_objects/dataview/setuint8", + "type": "DataView" + }, + { "name": "Date", "path": "global_objects/date", "type": "Date" }, + { + "name": "Date.@@toPrimitive", + "path": "global_objects/date/@@toprimitive", + "type": "Date" + }, + { "name": "Date.date", "path": "global_objects/date/date", "type": "Date" }, + { + "name": "Date.getDate", + "path": "global_objects/date/getdate", + "type": "Date" + }, + { + "name": "Date.getDay", + "path": "global_objects/date/getday", + "type": "Date" + }, + { + "name": "Date.getFullYear", + "path": "global_objects/date/getfullyear", + "type": "Date" + }, + { + "name": "Date.getHours", + "path": "global_objects/date/gethours", + "type": "Date" + }, + { + "name": "Date.getMilliseconds", + "path": "global_objects/date/getmilliseconds", + "type": "Date" + }, + { + "name": "Date.getMinutes", + "path": "global_objects/date/getminutes", + "type": "Date" + }, + { + "name": "Date.getMonth", + "path": "global_objects/date/getmonth", + "type": "Date" + }, + { + "name": "Date.getSeconds", + "path": "global_objects/date/getseconds", + "type": "Date" + }, + { + "name": "Date.getTime", + "path": "global_objects/date/gettime", + "type": "Date" + }, + { + "name": "Date.getTimezoneOffset", + "path": "global_objects/date/gettimezoneoffset", + "type": "Date" + }, + { + "name": "Date.getUTCDate", + "path": "global_objects/date/getutcdate", + "type": "Date" + }, + { + "name": "Date.getUTCDay", + "path": "global_objects/date/getutcday", + "type": "Date" + }, + { + "name": "Date.getUTCFullYear", + "path": "global_objects/date/getutcfullyear", + "type": "Date" + }, + { + "name": "Date.getUTCHours", + "path": "global_objects/date/getutchours", + "type": "Date" + }, + { + "name": "Date.getUTCMilliseconds", + "path": "global_objects/date/getutcmilliseconds", + "type": "Date" + }, + { + "name": "Date.getUTCMinutes", + "path": "global_objects/date/getutcminutes", + "type": "Date" + }, + { + "name": "Date.getUTCMonth", + "path": "global_objects/date/getutcmonth", + "type": "Date" + }, + { + "name": "Date.getUTCSeconds", + "path": "global_objects/date/getutcseconds", + "type": "Date" + }, + { + "name": "Date.getYear", + "path": "global_objects/date/getyear", + "type": "Date" + }, + { "name": "Date.now", "path": "global_objects/date/now", "type": "Date" }, + { + "name": "Date.parse", + "path": "global_objects/date/parse", + "type": "Date" + }, + { + "name": "Date.setDate", + "path": "global_objects/date/setdate", + "type": "Date" + }, + { + "name": "Date.setFullYear", + "path": "global_objects/date/setfullyear", + "type": "Date" + }, + { + "name": "Date.setHours", + "path": "global_objects/date/sethours", + "type": "Date" + }, + { + "name": "Date.setMilliseconds", + "path": "global_objects/date/setmilliseconds", + "type": "Date" + }, + { + "name": "Date.setMinutes", + "path": "global_objects/date/setminutes", + "type": "Date" + }, + { + "name": "Date.setMonth", + "path": "global_objects/date/setmonth", + "type": "Date" + }, + { + "name": "Date.setSeconds", + "path": "global_objects/date/setseconds", + "type": "Date" + }, + { + "name": "Date.setTime", + "path": "global_objects/date/settime", + "type": "Date" + }, + { + "name": "Date.setUTCDate", + "path": "global_objects/date/setutcdate", + "type": "Date" + }, + { + "name": "Date.setUTCFullYear", + "path": "global_objects/date/setutcfullyear", + "type": "Date" + }, + { + "name": "Date.setUTCHours", + "path": "global_objects/date/setutchours", + "type": "Date" + }, + { + "name": "Date.setUTCMilliseconds", + "path": "global_objects/date/setutcmilliseconds", + "type": "Date" + }, + { + "name": "Date.setUTCMinutes", + "path": "global_objects/date/setutcminutes", + "type": "Date" + }, + { + "name": "Date.setUTCMonth", + "path": "global_objects/date/setutcmonth", + "type": "Date" + }, + { + "name": "Date.setUTCSeconds", + "path": "global_objects/date/setutcseconds", + "type": "Date" + }, + { + "name": "Date.setYear", + "path": "global_objects/date/setyear", + "type": "Date" + }, + { + "name": "Date.toDateString", + "path": "global_objects/date/todatestring", + "type": "Date" + }, + { + "name": "Date.toISOString", + "path": "global_objects/date/toisostring", + "type": "Date" + }, + { + "name": "Date.toJSON", + "path": "global_objects/date/tojson", + "type": "Date" + }, + { + "name": "Date.toLocaleDateString", + "path": "global_objects/date/tolocaledatestring", + "type": "Date" + }, + { + "name": "Date.toLocaleString", + "path": "global_objects/date/tolocalestring", + "type": "Date" + }, + { + "name": "Date.toLocaleTimeString", + "path": "global_objects/date/tolocaletimestring", + "type": "Date" + }, + { + "name": "Date.toString", + "path": "global_objects/date/tostring", + "type": "Date" + }, + { + "name": "Date.toTimeString", + "path": "global_objects/date/totimestring", + "type": "Date" + }, + { + "name": "Date.toUTCString", + "path": "global_objects/date/toutcstring", + "type": "Date" + }, + { "name": "Date.UTC", "path": "global_objects/date/utc", "type": "Date" }, + { + "name": "Date.valueOf", + "path": "global_objects/date/valueof", + "type": "Date" + }, + { "name": "debugger", "path": "statements/debugger", "type": "Statements" }, + { + "name": "decodeURI", + "path": "global_objects/decodeuri", + "type": "Global Objects" + }, + { + "name": "decodeURIComponent", + "path": "global_objects/decodeuricomponent", + "type": "Global Objects" + }, + { "name": "Decrement", "path": "operators/decrement", "type": "Operators" }, + { + "name": "Default parameters", + "path": "functions/default_parameters", + "type": "Function" + }, + { "name": "delete", "path": "operators/delete", "type": "Operators" }, + { + "name": "Destructuring assignment", + "path": "operators/destructuring_assignment", + "type": "Operators" + }, + { "name": "Division", "path": "operators/division", "type": "Operators" }, + { + "name": "Division assignment", + "path": "operators/division_assignment", + "type": "Operators" + }, + { + "name": "do...while", + "path": "statements/do...while", + "type": "Statements" + }, + { "name": "Empty", "path": "statements/empty", "type": "Statements" }, + { + "name": "encodeURI", + "path": "global_objects/encodeuri", + "type": "Global Objects" + }, + { + "name": "encodeURIComponent", + "path": "global_objects/encodeuricomponent", + "type": "Global Objects" + }, + { "name": "Equality", "path": "operators/equality", "type": "Operators" }, + { "name": "Error", "path": "global_objects/error", "type": "Errors" }, + { + "name": "Error.cause", + "path": "global_objects/error/cause", + "type": "Errors" + }, + { + "name": "Error.columnNumber", + "path": "global_objects/error/columnnumber", + "type": "Errors" + }, + { + "name": "Error.error", + "path": "global_objects/error/error", + "type": "Errors" + }, + { + "name": "Error.fileName", + "path": "global_objects/error/filename", + "type": "Errors" + }, + { + "name": "Error.lineNumber", + "path": "global_objects/error/linenumber", + "type": "Errors" + }, + { + "name": "Error.message", + "path": "global_objects/error/message", + "type": "Errors" + }, + { + "name": "error.name", + "path": "global_objects/error/name", + "type": "Errors" + }, + { + "name": "error.stack", + "path": "global_objects/error/stack", + "type": "Errors" + }, + { + "name": "Error.toString", + "path": "global_objects/error/tostring", + "type": "Errors" + }, + { "name": "Errors", "path": "errors", "type": "Errors" }, + { + "name": "Errors: Already has pragma", + "path": "errors/already_has_pragma", + "type": "Errors" + }, + { + "name": "Errors: Array sort argument", + "path": "errors/array_sort_argument", + "type": "Errors" + }, + { + "name": "Errors: Bad await", + "path": "errors/bad_await", + "type": "Errors" + }, + { + "name": "Errors: Bad break", + "path": "errors/bad_break", + "type": "Errors" + }, + { + "name": "Errors: Bad continue", + "path": "errors/bad_continue", + "type": "Errors" + }, + { + "name": "Errors: Bad radix", + "path": "errors/bad_radix", + "type": "Errors" + }, + { + "name": "Errors: Bad regexp flag", + "path": "errors/bad_regexp_flag", + "type": "Errors" + }, + { + "name": "Errors: Bad return", + "path": "errors/bad_return", + "type": "Errors" + }, + { + "name": "Errors: BigInt division by zero", + "path": "errors/bigint_division_by_zero", + "type": "Errors" + }, + { + "name": "Errors: BigInt negative exponent", + "path": "errors/bigint_negative_exponent", + "type": "Errors" + }, + { + "name": "Errors: Called on incompatible type", + "path": "errors/called_on_incompatible_type", + "type": "Errors" + }, + { + "name": "Errors: Cant access lexical declaration before init", + "path": "errors/cant_access_lexical_declaration_before_init", + "type": "Errors" + }, + { + "name": "Errors: Cant assign to property", + "path": "errors/cant_assign_to_property", + "type": "Errors" + }, + { + "name": "Errors: Cant be converted to BigInt because it isnt an integer", + "path": "errors/cant_be_converted_to_bigint_because_it_isnt_an_integer", + "type": "Errors" + }, + { + "name": "Errors: Cant convert BigInt to number", + "path": "errors/cant_convert_bigint_to_number", + "type": "Errors" + }, + { + "name": "Errors: Cant convert x to BigInt", + "path": "errors/cant_convert_x_to_bigint", + "type": "Errors" + }, + { + "name": "Errors: Cant define property object not extensible", + "path": "errors/cant_define_property_object_not_extensible", + "type": "Errors" + }, + { + "name": "Errors: Cant delete", + "path": "errors/cant_delete", + "type": "Errors" + }, + { + "name": "Errors: Cant redefine property", + "path": "errors/cant_redefine_property", + "type": "Errors" + }, + { + "name": "Errors: Cant use nullish coalescing unparenthesized", + "path": "errors/cant_use_nullish_coalescing_unparenthesized", + "type": "Errors" + }, + { + "name": "Errors: Cyclic object value", + "path": "errors/cyclic_object_value", + "type": "Errors" + }, + { + "name": "Errors: Delete in strict mode", + "path": "errors/delete_in_strict_mode", + "type": "Errors" + }, + { + "name": "Errors: Deprecated caller or arguments usage", + "path": "errors/deprecated_caller_or_arguments_usage", + "type": "Errors" + }, + { + "name": "Errors: Deprecated octal", + "path": "errors/deprecated_octal", + "type": "Errors" + }, + { + "name": "Errors: Deprecated source map pragma", + "path": "errors/deprecated_source_map_pragma", + "type": "Errors" + }, + { + "name": "Errors: Either be both static or non-static", + "path": "errors/either_be_both_static_or_non-static", + "type": "Errors" + }, + { + "name": "Errors: Equal as assign", + "path": "errors/equal_as_assign", + "type": "Errors" + }, + { + "name": "Errors: Getter only", + "path": "errors/getter_only", + "type": "Errors" + }, + { + "name": "Errors: Hash outside class", + "path": "errors/hash_outside_class", + "type": "Errors" + }, + { + "name": "Errors: Identifier after number", + "path": "errors/identifier_after_number", + "type": "Errors" + }, + { + "name": "Errors: Illegal character", + "path": "errors/illegal_character", + "type": "Errors" + }, + { + "name": "Errors: in operator no object", + "path": "errors/in_operator_no_object", + "type": "Errors" + }, + { + "name": "Errors: Invalid array length", + "path": "errors/invalid_array_length", + "type": "Errors" + }, + { + "name": "Errors: Invalid assignment left-hand side", + "path": "errors/invalid_assignment_left-hand_side", + "type": "Errors" + }, + { + "name": "Errors: Invalid BigInt syntax", + "path": "errors/invalid_bigint_syntax", + "type": "Errors" + }, + { + "name": "Errors: Invalid const assignment", + "path": "errors/invalid_const_assignment", + "type": "Errors" + }, + { + "name": "Errors: Invalid date", + "path": "errors/invalid_date", + "type": "Errors" + }, + { + "name": "Errors: Invalid for-in initializer", + "path": "errors/invalid_for-in_initializer", + "type": "Errors" + }, + { + "name": "Errors: Invalid for-of initializer", + "path": "errors/invalid_for-of_initializer", + "type": "Errors" + }, + { + "name": "Errors: invalid right hand side instanceof operand", + "path": "errors/invalid_right_hand_side_instanceof_operand", + "type": "Errors" + }, + { + "name": "Errors: is not iterable", + "path": "errors/is_not_iterable", + "type": "Errors" + }, + { + "name": "Errors: JSON bad parse", + "path": "errors/json_bad_parse", + "type": "Errors" + }, + { + "name": "Errors: Label not found", + "path": "errors/label_not_found", + "type": "Errors" + }, + { + "name": "Errors: Malformed URI", + "path": "errors/malformed_uri", + "type": "Errors" + }, + { + "name": "Errors: Missing bracket after list", + "path": "errors/missing_bracket_after_list", + "type": "Errors" + }, + { + "name": "Errors: Missing colon after property id", + "path": "errors/missing_colon_after_property_id", + "type": "Errors" + }, + { + "name": "Errors: Missing curly after function body", + "path": "errors/missing_curly_after_function_body", + "type": "Errors" + }, + { + "name": "Errors: Missing curly after property list", + "path": "errors/missing_curly_after_property_list", + "type": "Errors" + }, + { + "name": "Errors: Missing formal parameter", + "path": "errors/missing_formal_parameter", + "type": "Errors" + }, + { + "name": "Errors: Missing initializer in const", + "path": "errors/missing_initializer_in_const", + "type": "Errors" + }, + { + "name": "Errors: Missing name after dot operator", + "path": "errors/missing_name_after_dot_operator", + "type": "Errors" + }, + { + "name": "Errors: Missing parenthesis after argument list", + "path": "errors/missing_parenthesis_after_argument_list", + "type": "Errors" + }, + { + "name": "Errors: Missing parenthesis after condition", + "path": "errors/missing_parenthesis_after_condition", + "type": "Errors" + }, + { + "name": "Errors: Missing semicolon before statement", + "path": "errors/missing_semicolon_before_statement", + "type": "Errors" + }, + { + "name": "Errors: More arguments needed", + "path": "errors/more_arguments_needed", + "type": "Errors" + }, + { + "name": "Errors: Negative repetition count", + "path": "errors/negative_repetition_count", + "type": "Errors" + }, + { + "name": "Errors: No non-null object", + "path": "errors/no_non-null_object", + "type": "Errors" + }, + { + "name": "Errors: No properties", + "path": "errors/no_properties", + "type": "Errors" + }, + { + "name": "Errors: No variable name", + "path": "errors/no_variable_name", + "type": "Errors" + }, + { + "name": "Errors: Non configurable array element", + "path": "errors/non_configurable_array_element", + "type": "Errors" + }, + { + "name": "Errors: Not a constructor", + "path": "errors/not_a_constructor", + "type": "Errors" + }, + { + "name": "Errors: Not a function", + "path": "errors/not_a_function", + "type": "Errors" + }, + { + "name": "Errors: Not a valid code point", + "path": "errors/not_a_valid_code_point", + "type": "Errors" + }, + { + "name": "Errors: Not defined", + "path": "errors/not_defined", + "type": "Errors" + }, + { + "name": "Errors: Precision range", + "path": "errors/precision_range", + "type": "Errors" + }, + { + "name": "Errors: Property access denied", + "path": "errors/property_access_denied", + "type": "Errors" + }, + { + "name": "Errors: Read-only", + "path": "errors/read-only", + "type": "Errors" + }, + { + "name": "Errors: Redeclared parameter", + "path": "errors/redeclared_parameter", + "type": "Errors" + }, + { + "name": "Errors: Reduce of empty array with no initial value", + "path": "errors/reduce_of_empty_array_with_no_initial_value", + "type": "Errors" + }, + { + "name": "Errors: Reserved identifier", + "path": "errors/reserved_identifier", + "type": "Errors" + }, + { + "name": "Errors: Resulting string too large", + "path": "errors/resulting_string_too_large", + "type": "Errors" + }, + { + "name": "Errors: Stmt after return", + "path": "errors/stmt_after_return", + "type": "Errors" + }, + { + "name": "Errors: Strict non simple params", + "path": "errors/strict_non_simple_params", + "type": "Errors" + }, + { + "name": "Errors: Too much recursion", + "path": "errors/too_much_recursion", + "type": "Errors" + }, + { + "name": "Errors: Undeclared var", + "path": "errors/undeclared_var", + "type": "Errors" + }, + { + "name": "Errors: Undefined prop", + "path": "errors/undefined_prop", + "type": "Errors" + }, + { + "name": "Errors: Unexpected token", + "path": "errors/unexpected_token", + "type": "Errors" + }, + { + "name": "Errors: Unexpected type", + "path": "errors/unexpected_type", + "type": "Errors" + }, + { + "name": "Errors: Unnamed function statement", + "path": "errors/unnamed_function_statement", + "type": "Errors" + }, + { + "name": "Errors: Unparenthesized unary expr lhs exponentiation", + "path": "errors/unparenthesized_unary_expr_lhs_exponentiation", + "type": "Errors" + }, + { + "name": "Errors: Unterminated string literal", + "path": "errors/unterminated_string_literal", + "type": "Errors" + }, + { + "name": "escape", + "path": "global_objects/escape", + "type": "Global Objects" + }, + { "name": "eval", "path": "global_objects/eval", "type": "Global Objects" }, + { + "name": "EvalError", + "path": "global_objects/evalerror", + "type": "Errors" + }, + { + "name": "EvalError.evalError", + "path": "global_objects/evalerror/evalerror", + "type": "Errors" + }, + { + "name": "Exponentiation", + "path": "operators/exponentiation", + "type": "Operators" + }, + { + "name": "Exponentiation assignment", + "path": "operators/exponentiation_assignment", + "type": "Operators" + }, + { "name": "export", "path": "statements/export", "type": "Statements" }, + { + "name": "Expression statement", + "path": "statements/expression_statement", + "type": "Statements" + }, + { "name": "extends", "path": "classes/extends", "type": "Classes" }, + { + "name": "FinalizationRegistry", + "path": "global_objects/finalizationregistry", + "type": "Global Objects" + }, + { + "name": "FinalizationRegistry.finalizationRegistry", + "path": "global_objects/finalizationregistry/finalizationregistry", + "type": "FinalizationRegistry" + }, + { + "name": "finalizationRegistry.register", + "path": "global_objects/finalizationregistry/register", + "type": "FinalizationRegistry" + }, + { + "name": "finalizationRegistry.unregister", + "path": "global_objects/finalizationregistry/unregister", + "type": "FinalizationRegistry" + }, + { + "name": "Float32Array", + "path": "global_objects/float32array", + "type": "Global Objects" + }, + { + "name": "Float32Array.float32Array", + "path": "global_objects/float32array/float32array", + "type": "Float32Array" + }, + { + "name": "Float64Array", + "path": "global_objects/float64array", + "type": "Global Objects" + }, + { + "name": "Float64Array.float64Array", + "path": "global_objects/float64array/float64array", + "type": "Float64Array" + }, + { "name": "for", "path": "statements/for", "type": "Statements" }, + { + "name": "for-await...of", + "path": "statements/for-await...of", + "type": "Statements" + }, + { "name": "for...in", "path": "statements/for...in", "type": "Statements" }, + { "name": "for...of", "path": "statements/for...of", "type": "Statements" }, + { + "name": "Function", + "path": "global_objects/function", + "type": "Function" + }, + { "name": "function", "path": "statements/function", "type": "Statements" }, + { "name": "function", "path": "operators/function", "type": "Operators" }, + { "name": "function*", "path": "operators/function*", "type": "Operators" }, + { + "name": "function*", + "path": "statements/function*", + "type": "Statements" + }, + { + "name": "Function.@@hasInstance", + "path": "global_objects/function/@@hasinstance", + "type": "Function" + }, + { + "name": "function.apply", + "path": "global_objects/function/apply", + "type": "Function" + }, + { + "name": "Function.arguments", + "path": "global_objects/function/arguments", + "type": "Function" + }, + { + "name": "function.bind", + "path": "global_objects/function/bind", + "type": "Function" + }, + { + "name": "function.call", + "path": "global_objects/function/call", + "type": "Function" + }, + { + "name": "Function.caller", + "path": "global_objects/function/caller", + "type": "Function" + }, + { + "name": "Function.displayName", + "path": "global_objects/function/displayname", + "type": "Function" + }, + { + "name": "Function.function", + "path": "global_objects/function/function", + "type": "Function" + }, + { + "name": "Function.length", + "path": "global_objects/function/length", + "type": "Function" + }, + { + "name": "Function.name", + "path": "global_objects/function/name", + "type": "Function" + }, + { + "name": "Function.prototype", + "path": "global_objects/function/prototype", + "type": "Function" + }, + { + "name": "Function.toString", + "path": "global_objects/function/tostring", + "type": "Function" + }, + { "name": "Functions", "path": "functions", "type": "Function" }, + { + "name": "Generator", + "path": "global_objects/generator", + "type": "Generator" + }, + { + "name": "generator.next", + "path": "global_objects/generator/next", + "type": "Generator" + }, + { + "name": "generator.return", + "path": "global_objects/generator/return", + "type": "Generator" + }, + { + "name": "generator.throw", + "path": "global_objects/generator/throw", + "type": "Generator" + }, + { + "name": "GeneratorFunction", + "path": "global_objects/generatorfunction", + "type": "Function" + }, + { + "name": "GeneratorFunction.generatorFunction", + "path": "global_objects/generatorfunction/generatorfunction", + "type": "Function" + }, + { "name": "get", "path": "functions/get", "type": "Function" }, + { + "name": "globalThis", + "path": "global_objects/globalthis", + "type": "Global Objects" + }, + { + "name": "Greater than", + "path": "operators/greater_than", + "type": "Operators" + }, + { + "name": "Greater than or equal", + "path": "operators/greater_than_or_equal", + "type": "Operators" + }, + { "name": "Grouping", "path": "operators/grouping", "type": "Operators" }, + { + "name": "if...else", + "path": "statements/if...else", + "type": "Statements" + }, + { "name": "import", "path": "operators/import", "type": "Operators" }, + { "name": "import", "path": "statements/import", "type": "Statements" }, + { + "name": "import.meta", + "path": "operators/import.meta", + "type": "Operators" + }, + { + "name": "import.meta.resolve", + "path": "operators/import.meta/resolve", + "type": "Operators" + }, + { "name": "in", "path": "operators/in", "type": "Operators" }, + { "name": "Increment", "path": "operators/increment", "type": "Operators" }, + { + "name": "Inequality", + "path": "operators/inequality", + "type": "Operators" + }, + { + "name": "Infinity", + "path": "global_objects/infinity", + "type": "Global Objects" + }, + { + "name": "instanceof", + "path": "operators/instanceof", + "type": "Operators" + }, + { + "name": "Int16Array", + "path": "global_objects/int16array", + "type": "Global Objects" + }, + { + "name": "Int16Array.int16Array", + "path": "global_objects/int16array/int16array", + "type": "Int16Array" + }, + { + "name": "Int32Array", + "path": "global_objects/int32array", + "type": "Global Objects" + }, + { + "name": "Int32Array.int32Array", + "path": "global_objects/int32array/int32array", + "type": "Int32Array" + }, + { + "name": "Int8Array", + "path": "global_objects/int8array", + "type": "Global Objects" + }, + { + "name": "Int8Array.int8Array", + "path": "global_objects/int8array/int8array", + "type": "Int8Array" + }, + { + "name": "InternalError", + "path": "global_objects/internalerror", + "type": "Errors" + }, + { + "name": "InternalError.internalError", + "path": "global_objects/internalerror/internalerror", + "type": "Errors" + }, + { "name": "Intl", "path": "global_objects/intl", "type": "Intl" }, + { + "name": "Intl.collator", + "path": "global_objects/intl/collator", + "type": "Intl" + }, + { + "name": "Intl.collator.Collator", + "path": "global_objects/intl/collator/collator", + "type": "Intl" + }, + { + "name": "Intl.collator.compare", + "path": "global_objects/intl/collator/compare", + "type": "Intl" + }, + { + "name": "Intl.collator.resolvedOptions", + "path": "global_objects/intl/collator/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.collator.supportedLocalesOf", + "path": "global_objects/intl/collator/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat", + "path": "global_objects/intl/datetimeformat", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.DateTimeFormat", + "path": "global_objects/intl/datetimeformat/datetimeformat", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.format", + "path": "global_objects/intl/datetimeformat/format", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.formatRange", + "path": "global_objects/intl/datetimeformat/formatrange", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.formatRangeToParts", + "path": "global_objects/intl/datetimeformat/formatrangetoparts", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.formatToParts", + "path": "global_objects/intl/datetimeformat/formattoparts", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.resolvedOptions", + "path": "global_objects/intl/datetimeformat/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.dateTimeFormat.supportedLocalesOf", + "path": "global_objects/intl/datetimeformat/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.displayNames", + "path": "global_objects/intl/displaynames", + "type": "Intl" + }, + { + "name": "Intl.displayNames.DisplayNames", + "path": "global_objects/intl/displaynames/displaynames", + "type": "Intl" + }, + { + "name": "Intl.displayNames.of", + "path": "global_objects/intl/displaynames/of", + "type": "Intl" + }, + { + "name": "Intl.displayNames.resolvedOptions", + "path": "global_objects/intl/displaynames/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.displayNames.supportedLocalesOf", + "path": "global_objects/intl/displaynames/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.durationFormat", + "path": "global_objects/intl/durationformat", + "type": "Intl" + }, + { + "name": "Intl.durationFormat.DurationFormat", + "path": "global_objects/intl/durationformat/durationformat", + "type": "Intl" + }, + { + "name": "Intl.durationFormat.format", + "path": "global_objects/intl/durationformat/format", + "type": "Intl" + }, + { + "name": "Intl.durationFormat.formatToParts", + "path": "global_objects/intl/durationformat/formattoparts", + "type": "Intl" + }, + { + "name": "Intl.durationFormat.resolvedOptions", + "path": "global_objects/intl/durationformat/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.durationFormat.supportedLocalesOf", + "path": "global_objects/intl/durationformat/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.getCanonicalLocales", + "path": "global_objects/intl/getcanonicallocales", + "type": "Intl" + }, + { + "name": "Intl.listFormat", + "path": "global_objects/intl/listformat", + "type": "Intl" + }, + { + "name": "Intl.listFormat.format", + "path": "global_objects/intl/listformat/format", + "type": "Intl" + }, + { + "name": "Intl.listFormat.formatToParts", + "path": "global_objects/intl/listformat/formattoparts", + "type": "Intl" + }, + { + "name": "Intl.listFormat.ListFormat", + "path": "global_objects/intl/listformat/listformat", + "type": "Intl" + }, + { + "name": "Intl.listFormat.resolvedOptions", + "path": "global_objects/intl/listformat/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.listFormat.supportedLocalesOf", + "path": "global_objects/intl/listformat/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.locale", + "path": "global_objects/intl/locale", + "type": "Intl" + }, + { + "name": "Intl.locale.baseName", + "path": "global_objects/intl/locale/basename", + "type": "Intl" + }, + { + "name": "Intl.locale.calendar", + "path": "global_objects/intl/locale/calendar", + "type": "Intl" + }, + { + "name": "Intl.locale.caseFirst", + "path": "global_objects/intl/locale/casefirst", + "type": "Intl" + }, + { + "name": "Intl.locale.collation", + "path": "global_objects/intl/locale/collation", + "type": "Intl" + }, + { + "name": "Intl.locale.getCalendars", + "path": "global_objects/intl/locale/getcalendars", + "type": "Intl" + }, + { + "name": "Intl.locale.getCollations", + "path": "global_objects/intl/locale/getcollations", + "type": "Intl" + }, + { + "name": "Intl.locale.getHourCycles", + "path": "global_objects/intl/locale/gethourcycles", + "type": "Intl" + }, + { + "name": "Intl.locale.getNumberingSystems", + "path": "global_objects/intl/locale/getnumberingsystems", + "type": "Intl" + }, + { + "name": "Intl.locale.getTextInfo", + "path": "global_objects/intl/locale/gettextinfo", + "type": "Intl" + }, + { + "name": "Intl.locale.getTimeZones", + "path": "global_objects/intl/locale/gettimezones", + "type": "Intl" + }, + { + "name": "Intl.locale.getWeekInfo", + "path": "global_objects/intl/locale/getweekinfo", + "type": "Intl" + }, + { + "name": "Intl.locale.hourCycle", + "path": "global_objects/intl/locale/hourcycle", + "type": "Intl" + }, + { + "name": "Intl.locale.language", + "path": "global_objects/intl/locale/language", + "type": "Intl" + }, + { + "name": "Intl.locale.Locale", + "path": "global_objects/intl/locale/locale", + "type": "Intl" + }, + { + "name": "Intl.locale.maximize", + "path": "global_objects/intl/locale/maximize", + "type": "Intl" + }, + { + "name": "Intl.locale.minimize", + "path": "global_objects/intl/locale/minimize", + "type": "Intl" + }, + { + "name": "Intl.locale.numberingSystem", + "path": "global_objects/intl/locale/numberingsystem", + "type": "Intl" + }, + { + "name": "Intl.locale.numeric", + "path": "global_objects/intl/locale/numeric", + "type": "Intl" + }, + { + "name": "Intl.locale.region", + "path": "global_objects/intl/locale/region", + "type": "Intl" + }, + { + "name": "Intl.locale.script", + "path": "global_objects/intl/locale/script", + "type": "Intl" + }, + { + "name": "Intl.locale.toString", + "path": "global_objects/intl/locale/tostring", + "type": "Intl" + }, + { + "name": "Intl.numberFormat", + "path": "global_objects/intl/numberformat", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.format", + "path": "global_objects/intl/numberformat/format", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.formatRange", + "path": "global_objects/intl/numberformat/formatrange", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.formatRangeToParts", + "path": "global_objects/intl/numberformat/formatrangetoparts", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.formatToParts", + "path": "global_objects/intl/numberformat/formattoparts", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.NumberFormat", + "path": "global_objects/intl/numberformat/numberformat", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.resolvedOptions", + "path": "global_objects/intl/numberformat/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.numberFormat.supportedLocalesOf", + "path": "global_objects/intl/numberformat/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.pluralRules", + "path": "global_objects/intl/pluralrules", + "type": "Intl" + }, + { + "name": "Intl.pluralRules.PluralRules", + "path": "global_objects/intl/pluralrules/pluralrules", + "type": "Intl" + }, + { + "name": "Intl.pluralRules.resolvedOptions", + "path": "global_objects/intl/pluralrules/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.pluralRules.select", + "path": "global_objects/intl/pluralrules/select", + "type": "Intl" + }, + { + "name": "Intl.pluralRules.selectRange", + "path": "global_objects/intl/pluralrules/selectrange", + "type": "Intl" + }, + { + "name": "Intl.pluralRules.supportedLocalesOf", + "path": "global_objects/intl/pluralrules/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat", + "path": "global_objects/intl/relativetimeformat", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat.format", + "path": "global_objects/intl/relativetimeformat/format", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat.formatToParts", + "path": "global_objects/intl/relativetimeformat/formattoparts", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat.RelativeTimeFormat", + "path": "global_objects/intl/relativetimeformat/relativetimeformat", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat.resolvedOptions", + "path": "global_objects/intl/relativetimeformat/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.relativeTimeFormat.supportedLocalesOf", + "path": "global_objects/intl/relativetimeformat/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.segmenter", + "path": "global_objects/intl/segmenter", + "type": "Intl" + }, + { + "name": "Intl.segmenter.resolvedOptions", + "path": "global_objects/intl/segmenter/resolvedoptions", + "type": "Intl" + }, + { + "name": "Intl.segmenter.segment", + "path": "global_objects/intl/segmenter/segment", + "type": "Intl" + }, + { + "name": "Intl.segmenter.segment.Segments", + "path": "global_objects/intl/segmenter/segment/segments", + "type": "Intl" + }, + { + "name": "Intl.segmenter.segment.Segments.@@iterator", + "path": "global_objects/intl/segmenter/segment/segments/@@iterator", + "type": "Intl" + }, + { + "name": "Intl.segmenter.segment.Segments.containing", + "path": "global_objects/intl/segmenter/segment/segments/containing", + "type": "Intl" + }, + { + "name": "Intl.segmenter.Segmenter", + "path": "global_objects/intl/segmenter/segmenter", + "type": "Intl" + }, + { + "name": "Intl.segmenter.supportedLocalesOf", + "path": "global_objects/intl/segmenter/supportedlocalesof", + "type": "Intl" + }, + { + "name": "Intl.supportedValuesOf", + "path": "global_objects/intl/supportedvaluesof", + "type": "Intl" + }, + { + "name": "isFinite", + "path": "global_objects/isfinite", + "type": "Global Objects" + }, + { + "name": "isNaN", + "path": "global_objects/isnan", + "type": "Global Objects" + }, + { + "name": "Iteration protocols", + "path": "iteration_protocols", + "type": "Miscellaneous" + }, + { + "name": "Iterator", + "path": "global_objects/iterator", + "type": "Global Objects" + }, + { + "name": "Iterator.@@iterator", + "path": "global_objects/iterator/@@iterator", + "type": "Iterator" + }, + { + "name": "Iterator.drop", + "path": "global_objects/iterator/drop", + "type": "Iterator" + }, + { + "name": "Iterator.every", + "path": "global_objects/iterator/every", + "type": "Iterator" + }, + { + "name": "Iterator.filter", + "path": "global_objects/iterator/filter", + "type": "Iterator" + }, + { + "name": "Iterator.find", + "path": "global_objects/iterator/find", + "type": "Iterator" + }, + { + "name": "Iterator.flatMap", + "path": "global_objects/iterator/flatmap", + "type": "Iterator" + }, + { + "name": "Iterator.forEach", + "path": "global_objects/iterator/foreach", + "type": "Iterator" + }, + { + "name": "Iterator.from", + "path": "global_objects/iterator/from", + "type": "Iterator" + }, + { + "name": "Iterator.iterator", + "path": "global_objects/iterator/iterator", + "type": "Iterator" + }, + { + "name": "Iterator.map", + "path": "global_objects/iterator/map", + "type": "Iterator" + }, + { + "name": "Iterator.reduce", + "path": "global_objects/iterator/reduce", + "type": "Iterator" + }, + { + "name": "Iterator.some", + "path": "global_objects/iterator/some", + "type": "Iterator" + }, + { + "name": "Iterator.take", + "path": "global_objects/iterator/take", + "type": "Iterator" + }, + { + "name": "Iterator.toArray", + "path": "global_objects/iterator/toarray", + "type": "Iterator" + }, + { "name": "JSON", "path": "global_objects/json", "type": "JSON" }, + { + "name": "JSON.parse", + "path": "global_objects/json/parse", + "type": "JSON" + }, + { + "name": "JSON.stringify", + "path": "global_objects/json/stringify", + "type": "JSON" + }, + { "name": "label", "path": "statements/label", "type": "Statements" }, + { + "name": "Left shift", + "path": "operators/left_shift", + "type": "Operators" + }, + { + "name": "Left shift assignment", + "path": "operators/left_shift_assignment", + "type": "Operators" + }, + { "name": "Less than", "path": "operators/less_than", "type": "Operators" }, + { + "name": "Less than or equal", + "path": "operators/less_than_or_equal", + "type": "Operators" + }, + { "name": "let", "path": "statements/let", "type": "Statements" }, + { + "name": "Lexical grammar", + "path": "lexical_grammar", + "type": "Miscellaneous" + }, + { + "name": "Logical AND", + "path": "operators/logical_and", + "type": "Operators" + }, + { + "name": "Logical AND assignment", + "path": "operators/logical_and_assignment", + "type": "Operators" + }, + { + "name": "Logical NOT", + "path": "operators/logical_not", + "type": "Operators" + }, + { + "name": "Logical OR", + "path": "operators/logical_or", + "type": "Operators" + }, + { + "name": "Logical OR assignment", + "path": "operators/logical_or_assignment", + "type": "Operators" + }, + { "name": "Map", "path": "global_objects/map", "type": "Map" }, + { + "name": "Map.@@iterator", + "path": "global_objects/map/@@iterator", + "type": "Map" + }, + { + "name": "Map.@@species", + "path": "global_objects/map/@@species", + "type": "Map" + }, + { "name": "map.clear", "path": "global_objects/map/clear", "type": "Map" }, + { + "name": "map.delete", + "path": "global_objects/map/delete", + "type": "Map" + }, + { + "name": "map.entries", + "path": "global_objects/map/entries", + "type": "Map" + }, + { + "name": "Map.forEach", + "path": "global_objects/map/foreach", + "type": "Map" + }, + { "name": "map.get", "path": "global_objects/map/get", "type": "Map" }, + { + "name": "Map.groupBy", + "path": "global_objects/map/groupby", + "type": "Map" + }, + { "name": "map.has", "path": "global_objects/map/has", "type": "Map" }, + { "name": "map.keys", "path": "global_objects/map/keys", "type": "Map" }, + { "name": "Map.map", "path": "global_objects/map/map", "type": "Map" }, + { "name": "map.set", "path": "global_objects/map/set", "type": "Map" }, + { "name": "map.size", "path": "global_objects/map/size", "type": "Map" }, + { + "name": "map.values", + "path": "global_objects/map/values", + "type": "Map" + }, + { "name": "Math", "path": "global_objects/math", "type": "Math" }, + { "name": "Math.abs", "path": "global_objects/math/abs", "type": "Math" }, + { "name": "Math.acos", "path": "global_objects/math/acos", "type": "Math" }, + { + "name": "Math.acosh", + "path": "global_objects/math/acosh", + "type": "Math" + }, + { "name": "Math.asin", "path": "global_objects/math/asin", "type": "Math" }, + { + "name": "Math.asinh", + "path": "global_objects/math/asinh", + "type": "Math" + }, + { "name": "Math.atan", "path": "global_objects/math/atan", "type": "Math" }, + { + "name": "Math.atan2", + "path": "global_objects/math/atan2", + "type": "Math" + }, + { + "name": "Math.atanh", + "path": "global_objects/math/atanh", + "type": "Math" + }, + { "name": "Math.cbrt", "path": "global_objects/math/cbrt", "type": "Math" }, + { "name": "Math.ceil", "path": "global_objects/math/ceil", "type": "Math" }, + { + "name": "Math.clz32", + "path": "global_objects/math/clz32", + "type": "Math" + }, + { "name": "Math.cos", "path": "global_objects/math/cos", "type": "Math" }, + { "name": "Math.cosh", "path": "global_objects/math/cosh", "type": "Math" }, + { "name": "Math.E", "path": "global_objects/math/e", "type": "Math" }, + { "name": "Math.exp", "path": "global_objects/math/exp", "type": "Math" }, + { + "name": "Math.expm1", + "path": "global_objects/math/expm1", + "type": "Math" + }, + { + "name": "Math.floor", + "path": "global_objects/math/floor", + "type": "Math" + }, + { + "name": "Math.fround", + "path": "global_objects/math/fround", + "type": "Math" + }, + { + "name": "Math.hypot", + "path": "global_objects/math/hypot", + "type": "Math" + }, + { "name": "Math.imul", "path": "global_objects/math/imul", "type": "Math" }, + { "name": "Math.LN10", "path": "global_objects/math/ln10", "type": "Math" }, + { "name": "Math.LN2", "path": "global_objects/math/ln2", "type": "Math" }, + { "name": "Math.log", "path": "global_objects/math/log", "type": "Math" }, + { + "name": "Math.log10", + "path": "global_objects/math/log10", + "type": "Math" + }, + { + "name": "Math.LOG10E", + "path": "global_objects/math/log10e", + "type": "Math" + }, + { + "name": "Math.log1p", + "path": "global_objects/math/log1p", + "type": "Math" + }, + { "name": "Math.log2", "path": "global_objects/math/log2", "type": "Math" }, + { + "name": "Math.LOG2E", + "path": "global_objects/math/log2e", + "type": "Math" + }, + { "name": "Math.max", "path": "global_objects/math/max", "type": "Math" }, + { "name": "Math.min", "path": "global_objects/math/min", "type": "Math" }, + { "name": "Math.PI", "path": "global_objects/math/pi", "type": "Math" }, + { "name": "Math.pow", "path": "global_objects/math/pow", "type": "Math" }, + { + "name": "Math.random", + "path": "global_objects/math/random", + "type": "Math" + }, + { + "name": "Math.round", + "path": "global_objects/math/round", + "type": "Math" + }, + { "name": "Math.sign", "path": "global_objects/math/sign", "type": "Math" }, + { "name": "Math.sin", "path": "global_objects/math/sin", "type": "Math" }, + { "name": "Math.sinh", "path": "global_objects/math/sinh", "type": "Math" }, + { "name": "Math.sqrt", "path": "global_objects/math/sqrt", "type": "Math" }, + { + "name": "Math.SQRT1_2", + "path": "global_objects/math/sqrt1_2", + "type": "Math" + }, + { + "name": "Math.SQRT2", + "path": "global_objects/math/sqrt2", + "type": "Math" + }, + { "name": "Math.tan", "path": "global_objects/math/tan", "type": "Math" }, + { "name": "Math.tanh", "path": "global_objects/math/tanh", "type": "Math" }, + { + "name": "Math.trunc", + "path": "global_objects/math/trunc", + "type": "Math" + }, + { + "name": "Method definitions", + "path": "functions/method_definitions", + "type": "Function" + }, + { + "name": "Multiplication", + "path": "operators/multiplication", + "type": "Operators" + }, + { + "name": "Multiplication assignment", + "path": "operators/multiplication_assignment", + "type": "Operators" + }, + { "name": "NaN", "path": "global_objects/nan", "type": "Global Objects" }, + { "name": "new", "path": "operators/new", "type": "Operators" }, + { + "name": "new.target", + "path": "operators/new.target", + "type": "Operators" + }, + { "name": "null", "path": "operators/null", "type": "Operators" }, + { + "name": "Nullish coalescing", + "path": "operators/nullish_coalescing", + "type": "Operators" + }, + { + "name": "Nullish coalescing assignment", + "path": "operators/nullish_coalescing_assignment", + "type": "Operators" + }, + { "name": "Number", "path": "global_objects/number", "type": "Number" }, + { + "name": "Number.EPSILON", + "path": "global_objects/number/epsilon", + "type": "Number" + }, + { + "name": "Number.isFinite", + "path": "global_objects/number/isfinite", + "type": "Number" + }, + { + "name": "Number.isInteger", + "path": "global_objects/number/isinteger", + "type": "Number" + }, + { + "name": "Number.isNaN", + "path": "global_objects/number/isnan", + "type": "Number" + }, + { + "name": "Number.isSafeInteger", + "path": "global_objects/number/issafeinteger", + "type": "Number" + }, + { + "name": "Number.MAX_SAFE_INTEGER", + "path": "global_objects/number/max_safe_integer", + "type": "Number" + }, + { + "name": "Number.MAX_VALUE", + "path": "global_objects/number/max_value", + "type": "Number" + }, + { + "name": "Number.MIN_SAFE_INTEGER", + "path": "global_objects/number/min_safe_integer", + "type": "Number" + }, + { + "name": "Number.MIN_VALUE", + "path": "global_objects/number/min_value", + "type": "Number" + }, + { + "name": "Number.NaN", + "path": "global_objects/number/nan", + "type": "Number" + }, + { + "name": "Number.NEGATIVE_INFINITY", + "path": "global_objects/number/negative_infinity", + "type": "Number" + }, + { + "name": "Number.number", + "path": "global_objects/number/number", + "type": "Number" + }, + { + "name": "Number.parseFloat", + "path": "global_objects/number/parsefloat", + "type": "Number" + }, + { + "name": "Number.parseInt", + "path": "global_objects/number/parseint", + "type": "Number" + }, + { + "name": "Number.POSITIVE_INFINITY", + "path": "global_objects/number/positive_infinity", + "type": "Number" + }, + { + "name": "Number.toExponential", + "path": "global_objects/number/toexponential", + "type": "Number" + }, + { + "name": "Number.toFixed", + "path": "global_objects/number/tofixed", + "type": "Number" + }, + { + "name": "Number.toLocaleString", + "path": "global_objects/number/tolocalestring", + "type": "Number" + }, + { + "name": "Number.toPrecision", + "path": "global_objects/number/toprecision", + "type": "Number" + }, + { + "name": "Number.toString", + "path": "global_objects/number/tostring", + "type": "Number" + }, + { + "name": "Number.valueOf", + "path": "global_objects/number/valueof", + "type": "Number" + }, + { "name": "Object", "path": "global_objects/object", "type": "Object" }, + { + "name": "Object initializer", + "path": "operators/object_initializer", + "type": "Operators" + }, + { + "name": "object.__defineGetter__", + "path": "global_objects/object/__definegetter__", + "type": "Object" + }, + { + "name": "object.__defineSetter__", + "path": "global_objects/object/__definesetter__", + "type": "Object" + }, + { + "name": "object.__lookupGetter__", + "path": "global_objects/object/__lookupgetter__", + "type": "Object" + }, + { + "name": "object.__lookupSetter__", + "path": "global_objects/object/__lookupsetter__", + "type": "Object" + }, + { + "name": "Object.assign", + "path": "global_objects/object/assign", + "type": "Object" + }, + { + "name": "object.constructor", + "path": "global_objects/object/constructor", + "type": "Object" + }, + { + "name": "Object.create", + "path": "global_objects/object/create", + "type": "Object" + }, + { + "name": "Object.defineProperties", + "path": "global_objects/object/defineproperties", + "type": "Object" + }, + { + "name": "Object.defineProperty", + "path": "global_objects/object/defineproperty", + "type": "Object" + }, + { + "name": "Object.entries", + "path": "global_objects/object/entries", + "type": "Object" + }, + { + "name": "Object.freeze", + "path": "global_objects/object/freeze", + "type": "Object" + }, + { + "name": "Object.fromEntries", + "path": "global_objects/object/fromentries", + "type": "Object" + }, + { + "name": "Object.getOwnPropertyDescriptor", + "path": "global_objects/object/getownpropertydescriptor", + "type": "Object" + }, + { + "name": "Object.getOwnPropertyDescriptors", + "path": "global_objects/object/getownpropertydescriptors", + "type": "Object" + }, + { + "name": "Object.getOwnPropertyNames", + "path": "global_objects/object/getownpropertynames", + "type": "Object" + }, + { + "name": "Object.getOwnPropertySymbols", + "path": "global_objects/object/getownpropertysymbols", + "type": "Object" + }, + { + "name": "Object.getPrototypeOf", + "path": "global_objects/object/getprototypeof", + "type": "Object" + }, + { + "name": "Object.groupBy", + "path": "global_objects/object/groupby", + "type": "Object" + }, + { + "name": "Object.hasOwn", + "path": "global_objects/object/hasown", + "type": "Object" + }, + { + "name": "Object.hasOwnProperty", + "path": "global_objects/object/hasownproperty", + "type": "Object" + }, + { + "name": "Object.is", + "path": "global_objects/object/is", + "type": "Object" + }, + { + "name": "Object.isExtensible", + "path": "global_objects/object/isextensible", + "type": "Object" + }, + { + "name": "Object.isFrozen", + "path": "global_objects/object/isfrozen", + "type": "Object" + }, + { + "name": "Object.isPrototypeOf", + "path": "global_objects/object/isprototypeof", + "type": "Object" + }, + { + "name": "Object.isSealed", + "path": "global_objects/object/issealed", + "type": "Object" + }, + { + "name": "Object.keys", + "path": "global_objects/object/keys", + "type": "Object" + }, + { + "name": "Object.object", + "path": "global_objects/object/object", + "type": "Object" + }, + { + "name": "Object.preventExtensions", + "path": "global_objects/object/preventextensions", + "type": "Object" + }, + { + "name": "Object.propertyIsEnumerable", + "path": "global_objects/object/propertyisenumerable", + "type": "Object" + }, + { + "name": "Object.proto", + "path": "global_objects/object/proto", + "type": "Object" + }, + { + "name": "Object.seal", + "path": "global_objects/object/seal", + "type": "Object" + }, + { + "name": "Object.setPrototypeOf", + "path": "global_objects/object/setprototypeof", + "type": "Object" + }, + { + "name": "Object.toLocaleString", + "path": "global_objects/object/tolocalestring", + "type": "Object" + }, + { + "name": "Object.toString", + "path": "global_objects/object/tostring", + "type": "Object" + }, + { + "name": "Object.valueOf", + "path": "global_objects/object/valueof", + "type": "Object" + }, + { + "name": "Object.values", + "path": "global_objects/object/values", + "type": "Object" + }, + { + "name": "Operator precedence", + "path": "operators/operator_precedence", + "type": "Operators" + }, + { + "name": "Optional chaining", + "path": "operators/optional_chaining", + "type": "Operators" + }, + { + "name": "parseFloat", + "path": "global_objects/parsefloat", + "type": "Global Objects" + }, + { + "name": "parseInt", + "path": "global_objects/parseint", + "type": "Global Objects" + }, + { + "name": "Private class fields", + "path": "classes/private_class_fields", + "type": "Classes" + }, + { "name": "Promise", "path": "global_objects/promise", "type": "Promise" }, + { + "name": "Promise.@@species", + "path": "global_objects/promise/@@species", + "type": "Promise" + }, + { + "name": "Promise.all", + "path": "global_objects/promise/all", + "type": "Promise" + }, + { + "name": "Promise.allSettled", + "path": "global_objects/promise/allsettled", + "type": "Promise" + }, + { + "name": "Promise.any", + "path": "global_objects/promise/any", + "type": "Promise" + }, + { + "name": "promise.catch", + "path": "global_objects/promise/catch", + "type": "Promise" + }, + { + "name": "promise.finally", + "path": "global_objects/promise/finally", + "type": "Promise" + }, + { + "name": "Promise.promise", + "path": "global_objects/promise/promise", + "type": "Promise" + }, + { + "name": "Promise.race", + "path": "global_objects/promise/race", + "type": "Promise" + }, + { + "name": "Promise.reject", + "path": "global_objects/promise/reject", + "type": "Promise" + }, + { + "name": "Promise.resolve", + "path": "global_objects/promise/resolve", + "type": "Promise" + }, + { + "name": "promise.then", + "path": "global_objects/promise/then", + "type": "Promise" + }, + { + "name": "Property accessors", + "path": "operators/property_accessors", + "type": "Operators" + }, + { + "name": "Proxy", + "path": "global_objects/proxy", + "type": "Global Objects" + }, + { + "name": "Proxy.proxy", + "path": "global_objects/proxy/proxy", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.apply", + "path": "global_objects/proxy/proxy/apply", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.construct", + "path": "global_objects/proxy/proxy/construct", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.defineProperty", + "path": "global_objects/proxy/proxy/defineproperty", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.deleteProperty", + "path": "global_objects/proxy/proxy/deleteproperty", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.get", + "path": "global_objects/proxy/proxy/get", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.getOwnPropertyDescriptor", + "path": "global_objects/proxy/proxy/getownpropertydescriptor", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.getPrototypeOf", + "path": "global_objects/proxy/proxy/getprototypeof", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.has", + "path": "global_objects/proxy/proxy/has", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.isExtensible", + "path": "global_objects/proxy/proxy/isextensible", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.ownKeys", + "path": "global_objects/proxy/proxy/ownkeys", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.preventExtensions", + "path": "global_objects/proxy/proxy/preventextensions", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.set", + "path": "global_objects/proxy/proxy/set", + "type": "Proxy" + }, + { + "name": "Proxy.proxy.setPrototypeOf", + "path": "global_objects/proxy/proxy/setprototypeof", + "type": "Proxy" + }, + { + "name": "Proxy.revocable", + "path": "global_objects/proxy/revocable", + "type": "Proxy" + }, + { + "name": "Public class fields", + "path": "classes/public_class_fields", + "type": "Classes" + }, + { + "name": "RangeError", + "path": "global_objects/rangeerror", + "type": "Errors" + }, + { + "name": "RangeError.rangeError", + "path": "global_objects/rangeerror/rangeerror", + "type": "Errors" + }, + { + "name": "ReferenceError", + "path": "global_objects/referenceerror", + "type": "Errors" + }, + { + "name": "ReferenceError.referenceError", + "path": "global_objects/referenceerror/referenceerror", + "type": "Errors" + }, + { "name": "Reflect", "path": "global_objects/reflect", "type": "Reflect" }, + { + "name": "Reflect.apply", + "path": "global_objects/reflect/apply", + "type": "Reflect" + }, + { + "name": "Reflect.construct", + "path": "global_objects/reflect/construct", + "type": "Reflect" + }, + { + "name": "Reflect.defineProperty", + "path": "global_objects/reflect/defineproperty", + "type": "Reflect" + }, + { + "name": "Reflect.deleteProperty", + "path": "global_objects/reflect/deleteproperty", + "type": "Reflect" + }, + { + "name": "Reflect.get", + "path": "global_objects/reflect/get", + "type": "Reflect" + }, + { + "name": "Reflect.getOwnPropertyDescriptor", + "path": "global_objects/reflect/getownpropertydescriptor", + "type": "Reflect" + }, + { + "name": "Reflect.getPrototypeOf", + "path": "global_objects/reflect/getprototypeof", + "type": "Reflect" + }, + { + "name": "Reflect.has", + "path": "global_objects/reflect/has", + "type": "Reflect" + }, + { + "name": "Reflect.isExtensible", + "path": "global_objects/reflect/isextensible", + "type": "Reflect" + }, + { + "name": "Reflect.ownKeys", + "path": "global_objects/reflect/ownkeys", + "type": "Reflect" + }, + { + "name": "Reflect.preventExtensions", + "path": "global_objects/reflect/preventextensions", + "type": "Reflect" + }, + { + "name": "Reflect.set", + "path": "global_objects/reflect/set", + "type": "Reflect" + }, + { + "name": "Reflect.setPrototypeOf", + "path": "global_objects/reflect/setprototypeof", + "type": "Reflect" + }, + { "name": "RegExp", "path": "global_objects/regexp", "type": "RegExp" }, + { + "name": "RegExp.@@match", + "path": "global_objects/regexp/@@match", + "type": "RegExp" + }, + { + "name": "RegExp.@@matchAll", + "path": "global_objects/regexp/@@matchall", + "type": "RegExp" + }, + { + "name": "RegExp.@@replace", + "path": "global_objects/regexp/@@replace", + "type": "RegExp" + }, + { + "name": "RegExp.@@search", + "path": "global_objects/regexp/@@search", + "type": "RegExp" + }, + { + "name": "RegExp.@@species", + "path": "global_objects/regexp/@@species", + "type": "RegExp" + }, + { + "name": "RegExp.@@split", + "path": "global_objects/regexp/@@split", + "type": "RegExp" + }, + { + "name": "regExp.compile", + "path": "global_objects/regexp/compile", + "type": "RegExp" + }, + { + "name": "regExp.dotAll", + "path": "global_objects/regexp/dotall", + "type": "RegExp" + }, + { + "name": "regExp.exec", + "path": "global_objects/regexp/exec", + "type": "RegExp" + }, + { + "name": "regExp.flags", + "path": "global_objects/regexp/flags", + "type": "RegExp" + }, + { + "name": "regExp.global", + "path": "global_objects/regexp/global", + "type": "RegExp" + }, + { + "name": "regExp.hasIndices", + "path": "global_objects/regexp/hasindices", + "type": "RegExp" + }, + { + "name": "RegExp.ignoreCase", + "path": "global_objects/regexp/ignorecase", + "type": "RegExp" + }, + { + "name": "RegExp.input", + "path": "global_objects/regexp/input", + "type": "RegExp" + }, + { + "name": "RegExp.lastIndex", + "path": "global_objects/regexp/lastindex", + "type": "RegExp" + }, + { + "name": "RegExp.lastMatch", + "path": "global_objects/regexp/lastmatch", + "type": "RegExp" + }, + { + "name": "RegExp.lastParen", + "path": "global_objects/regexp/lastparen", + "type": "RegExp" + }, + { + "name": "RegExp.leftContext", + "path": "global_objects/regexp/leftcontext", + "type": "RegExp" + }, + { + "name": "regExp.multiline", + "path": "global_objects/regexp/multiline", + "type": "RegExp" + }, + { "name": "RegExp.n", "path": "global_objects/regexp/n", "type": "RegExp" }, + { + "name": "RegExp.regExp", + "path": "global_objects/regexp/regexp", + "type": "RegExp" + }, + { + "name": "RegExp.rightContext", + "path": "global_objects/regexp/rightcontext", + "type": "RegExp" + }, + { + "name": "regExp.source", + "path": "global_objects/regexp/source", + "type": "RegExp" + }, + { + "name": "regExp.sticky", + "path": "global_objects/regexp/sticky", + "type": "RegExp" + }, + { + "name": "regExp.test", + "path": "global_objects/regexp/test", + "type": "RegExp" + }, + { + "name": "RegExp.toString", + "path": "global_objects/regexp/tostring", + "type": "RegExp" + }, + { + "name": "regExp.unicode", + "path": "global_objects/regexp/unicode", + "type": "RegExp" + }, + { + "name": "RegExp.unicodeSets", + "path": "global_objects/regexp/unicodesets", + "type": "RegExp" + }, + { + "name": "Regular expressions", + "path": "regular_expressions", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Backreference", + "path": "regular_expressions/backreference", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Capturing group", + "path": "regular_expressions/capturing_group", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Character class", + "path": "regular_expressions/character_class", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Character class escape", + "path": "regular_expressions/character_class_escape", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Character escape", + "path": "regular_expressions/character_escape", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Disjunction", + "path": "regular_expressions/disjunction", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Input boundary assertion", + "path": "regular_expressions/input_boundary_assertion", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Literal character", + "path": "regular_expressions/literal_character", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Lookahead assertion", + "path": "regular_expressions/lookahead_assertion", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Lookbehind assertion", + "path": "regular_expressions/lookbehind_assertion", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Named backreference", + "path": "regular_expressions/named_backreference", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Named capturing group", + "path": "regular_expressions/named_capturing_group", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Non-capturing group", + "path": "regular_expressions/non-capturing_group", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Quantifier", + "path": "regular_expressions/quantifier", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Unicode character class escape", + "path": "regular_expressions/unicode_character_class_escape", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Wildcard", + "path": "regular_expressions/wildcard", + "type": "Miscellaneous" + }, + { + "name": "Regular expressions.Word boundary assertion", + "path": "regular_expressions/word_boundary_assertion", + "type": "Miscellaneous" + }, + { "name": "Remainder", "path": "operators/remainder", "type": "Operators" }, + { + "name": "Remainder assignment", + "path": "operators/remainder_assignment", + "type": "Operators" + }, + { + "name": "rest parameters", + "path": "functions/rest_parameters", + "type": "Function" + }, + { "name": "return", "path": "statements/return", "type": "Statements" }, + { + "name": "Right shift", + "path": "operators/right_shift", + "type": "Operators" + }, + { + "name": "Right shift assignment", + "path": "operators/right_shift_assignment", + "type": "Operators" + }, + { "name": "set", "path": "functions/set", "type": "Function" }, + { "name": "Set", "path": "global_objects/set", "type": "Set" }, + { + "name": "Set.@@iterator", + "path": "global_objects/set/@@iterator", + "type": "Set" + }, + { + "name": "Set.@@species", + "path": "global_objects/set/@@species", + "type": "Set" + }, + { "name": "set.add", "path": "global_objects/set/add", "type": "Set" }, + { "name": "set.clear", "path": "global_objects/set/clear", "type": "Set" }, + { + "name": "set.delete", + "path": "global_objects/set/delete", + "type": "Set" + }, + { + "name": "set.entries", + "path": "global_objects/set/entries", + "type": "Set" + }, + { + "name": "Set.forEach", + "path": "global_objects/set/foreach", + "type": "Set" + }, + { "name": "set.has", "path": "global_objects/set/has", "type": "Set" }, + { "name": "set.keys", "path": "global_objects/set/keys", "type": "Set" }, + { "name": "Set.set", "path": "global_objects/set/set", "type": "Set" }, + { "name": "set.size", "path": "global_objects/set/size", "type": "Set" }, + { + "name": "set.values", + "path": "global_objects/set/values", + "type": "Set" + }, + { + "name": "SharedArrayBuffer", + "path": "global_objects/sharedarraybuffer", + "type": "SharedArrayBuffer" + }, + { + "name": "SharedArrayBuffer.@@species", + "path": "global_objects/sharedarraybuffer/@@species", + "type": "SharedArrayBuffer" + }, + { + "name": "SharedArrayBuffer.byteLength", + "path": "global_objects/sharedarraybuffer/bytelength", + "type": "SharedArrayBuffer" + }, + { + "name": "sharedArrayBuffer.grow", + "path": "global_objects/sharedarraybuffer/grow", + "type": "SharedArrayBuffer" + }, + { + "name": "sharedArrayBuffer.growable", + "path": "global_objects/sharedarraybuffer/growable", + "type": "SharedArrayBuffer" + }, + { + "name": "SharedArrayBuffer.maxByteLength", + "path": "global_objects/sharedarraybuffer/maxbytelength", + "type": "SharedArrayBuffer" + }, + { + "name": "SharedArrayBuffer.sharedArrayBuffer", + "path": "global_objects/sharedarraybuffer/sharedarraybuffer", + "type": "SharedArrayBuffer" + }, + { + "name": "sharedArrayBuffer.slice", + "path": "global_objects/sharedarraybuffer/slice", + "type": "SharedArrayBuffer" + }, + { + "name": "Spread syntax", + "path": "operators/spread_syntax", + "type": "Operators" + }, + { "name": "static", "path": "classes/static", "type": "Classes" }, + { + "name": "Static initialization blocks", + "path": "classes/static_initialization_blocks", + "type": "Classes" + }, + { + "name": "Strict equality", + "path": "operators/strict_equality", + "type": "Operators" + }, + { + "name": "Strict inequality", + "path": "operators/strict_inequality", + "type": "Operators" + }, + { "name": "Strict mode", "path": "strict_mode", "type": "Miscellaneous" }, + { "name": "String", "path": "global_objects/string", "type": "String" }, + { + "name": "String.@@iterator", + "path": "global_objects/string/@@iterator", + "type": "String" + }, + { + "name": "string.anchor", + "path": "global_objects/string/anchor", + "type": "String" + }, + { + "name": "string.at", + "path": "global_objects/string/at", + "type": "String" + }, + { + "name": "string.big", + "path": "global_objects/string/big", + "type": "String" + }, + { + "name": "string.blink", + "path": "global_objects/string/blink", + "type": "String" + }, + { + "name": "string.bold", + "path": "global_objects/string/bold", + "type": "String" + }, + { + "name": "String.charAt", + "path": "global_objects/string/charat", + "type": "String" + }, + { + "name": "String.charCodeAt", + "path": "global_objects/string/charcodeat", + "type": "String" + }, + { + "name": "String.codePointAt", + "path": "global_objects/string/codepointat", + "type": "String" + }, + { + "name": "string.concat", + "path": "global_objects/string/concat", + "type": "String" + }, + { + "name": "String.endsWith", + "path": "global_objects/string/endswith", + "type": "String" + }, + { + "name": "string.fixed", + "path": "global_objects/string/fixed", + "type": "String" + }, + { + "name": "string.fontcolor", + "path": "global_objects/string/fontcolor", + "type": "String" + }, + { + "name": "string.fontsize", + "path": "global_objects/string/fontsize", + "type": "String" + }, + { + "name": "String.fromCharCode", + "path": "global_objects/string/fromcharcode", + "type": "String" + }, + { + "name": "String.fromCodePoint", + "path": "global_objects/string/fromcodepoint", + "type": "String" + }, + { + "name": "string.includes", + "path": "global_objects/string/includes", + "type": "String" + }, + { + "name": "String.indexOf", + "path": "global_objects/string/indexof", + "type": "String" + }, + { + "name": "String.isWellFormed", + "path": "global_objects/string/iswellformed", + "type": "String" + }, + { + "name": "string.italics", + "path": "global_objects/string/italics", + "type": "String" + }, + { + "name": "String.lastIndexOf", + "path": "global_objects/string/lastindexof", + "type": "String" + }, + { + "name": "String.length", + "path": "global_objects/string/length", + "type": "String" + }, + { + "name": "string.link", + "path": "global_objects/string/link", + "type": "String" + }, + { + "name": "string.localeCompare", + "path": "global_objects/string/localecompare", + "type": "String" + }, + { + "name": "string.match", + "path": "global_objects/string/match", + "type": "String" + }, + { + "name": "String.matchAll", + "path": "global_objects/string/matchall", + "type": "String" + }, + { + "name": "string.normalize", + "path": "global_objects/string/normalize", + "type": "String" + }, + { + "name": "String.padEnd", + "path": "global_objects/string/padend", + "type": "String" + }, + { + "name": "String.padStart", + "path": "global_objects/string/padstart", + "type": "String" + }, + { + "name": "String.raw", + "path": "global_objects/string/raw", + "type": "String" + }, + { + "name": "string.repeat", + "path": "global_objects/string/repeat", + "type": "String" + }, + { + "name": "string.replace", + "path": "global_objects/string/replace", + "type": "String" + }, + { + "name": "String.replaceAll", + "path": "global_objects/string/replaceall", + "type": "String" + }, + { + "name": "string.search", + "path": "global_objects/string/search", + "type": "String" + }, + { + "name": "string.slice", + "path": "global_objects/string/slice", + "type": "String" + }, + { + "name": "string.small", + "path": "global_objects/string/small", + "type": "String" + }, + { + "name": "string.split", + "path": "global_objects/string/split", + "type": "String" + }, + { + "name": "String.startsWith", + "path": "global_objects/string/startswith", + "type": "String" + }, + { + "name": "string.strike", + "path": "global_objects/string/strike", + "type": "String" + }, + { + "name": "String.string", + "path": "global_objects/string/string", + "type": "String" + }, + { + "name": "string.sub", + "path": "global_objects/string/sub", + "type": "String" + }, + { + "name": "string.substr", + "path": "global_objects/string/substr", + "type": "String" + }, + { + "name": "string.substring", + "path": "global_objects/string/substring", + "type": "String" + }, + { + "name": "string.sup", + "path": "global_objects/string/sup", + "type": "String" + }, + { + "name": "String.toLocaleLowerCase", + "path": "global_objects/string/tolocalelowercase", + "type": "String" + }, + { + "name": "String.toLocaleUpperCase", + "path": "global_objects/string/tolocaleuppercase", + "type": "String" + }, + { + "name": "String.toLowerCase", + "path": "global_objects/string/tolowercase", + "type": "String" + }, + { + "name": "String.toString", + "path": "global_objects/string/tostring", + "type": "String" + }, + { + "name": "String.toUpperCase", + "path": "global_objects/string/touppercase", + "type": "String" + }, + { + "name": "String.toWellFormed", + "path": "global_objects/string/towellformed", + "type": "String" + }, + { + "name": "string.trim", + "path": "global_objects/string/trim", + "type": "String" + }, + { + "name": "String.trimEnd", + "path": "global_objects/string/trimend", + "type": "String" + }, + { + "name": "String.trimStart", + "path": "global_objects/string/trimstart", + "type": "String" + }, + { + "name": "String.valueOf", + "path": "global_objects/string/valueof", + "type": "String" + }, + { + "name": "Subtraction", + "path": "operators/subtraction", + "type": "Operators" + }, + { + "name": "Subtraction assignment", + "path": "operators/subtraction_assignment", + "type": "Operators" + }, + { "name": "super", "path": "operators/super", "type": "Operators" }, + { "name": "switch", "path": "statements/switch", "type": "Statements" }, + { "name": "Symbol", "path": "global_objects/symbol", "type": "Symbol" }, + { + "name": "Symbol.@@toPrimitive", + "path": "global_objects/symbol/@@toprimitive", + "type": "Symbol" + }, + { + "name": "Symbol.asyncIterator", + "path": "global_objects/symbol/asynciterator", + "type": "Symbol" + }, + { + "name": "symbol.description", + "path": "global_objects/symbol/description", + "type": "Symbol" + }, + { + "name": "Symbol.for", + "path": "global_objects/symbol/for", + "type": "Symbol" + }, + { + "name": "Symbol.hasInstance", + "path": "global_objects/symbol/hasinstance", + "type": "Symbol" + }, + { + "name": "Symbol.isConcatSpreadable", + "path": "global_objects/symbol/isconcatspreadable", + "type": "Symbol" + }, + { + "name": "Symbol.iterator", + "path": "global_objects/symbol/iterator", + "type": "Symbol" + }, + { + "name": "Symbol.keyFor", + "path": "global_objects/symbol/keyfor", + "type": "Symbol" + }, + { + "name": "Symbol.match", + "path": "global_objects/symbol/match", + "type": "Symbol" + }, + { + "name": "Symbol.matchAll", + "path": "global_objects/symbol/matchall", + "type": "Symbol" + }, + { + "name": "Symbol.replace", + "path": "global_objects/symbol/replace", + "type": "Symbol" + }, + { + "name": "Symbol.search", + "path": "global_objects/symbol/search", + "type": "Symbol" + }, + { + "name": "Symbol.species", + "path": "global_objects/symbol/species", + "type": "Symbol" + }, + { + "name": "Symbol.split", + "path": "global_objects/symbol/split", + "type": "Symbol" + }, + { + "name": "Symbol.symbol", + "path": "global_objects/symbol/symbol", + "type": "Symbol" + }, + { + "name": "Symbol.toPrimitive", + "path": "global_objects/symbol/toprimitive", + "type": "Symbol" + }, + { + "name": "Symbol.toString", + "path": "global_objects/symbol/tostring", + "type": "Symbol" + }, + { + "name": "Symbol.toStringTag", + "path": "global_objects/symbol/tostringtag", + "type": "Symbol" + }, + { + "name": "Symbol.unscopables", + "path": "global_objects/symbol/unscopables", + "type": "Symbol" + }, + { + "name": "Symbol.valueOf", + "path": "global_objects/symbol/valueof", + "type": "Symbol" + }, + { + "name": "SyntaxError", + "path": "global_objects/syntaxerror", + "type": "Errors" + }, + { + "name": "SyntaxError.syntaxError", + "path": "global_objects/syntaxerror/syntaxerror", + "type": "Errors" + }, + { + "name": "Template literals", + "path": "template_literals", + "type": "Miscellaneous" + }, + { "name": "this", "path": "operators/this", "type": "Operators" }, + { "name": "throw", "path": "statements/throw", "type": "Statements" }, + { + "name": "Trailing commas", + "path": "trailing_commas", + "type": "Miscellaneous" + }, + { + "name": "try...catch", + "path": "statements/try...catch", + "type": "Statements" + }, + { + "name": "TypedArray", + "path": "global_objects/typedarray", + "type": "TypedArray" + }, + { + "name": "TypedArray.@@iterator", + "path": "global_objects/typedarray/@@iterator", + "type": "TypedArray" + }, + { + "name": "TypedArray.@@species", + "path": "global_objects/typedarray/@@species", + "type": "TypedArray" + }, + { + "name": "typedArray.at", + "path": "global_objects/typedarray/at", + "type": "TypedArray" + }, + { + "name": "typedArray.buffer", + "path": "global_objects/typedarray/buffer", + "type": "TypedArray" + }, + { + "name": "TypedArray.byteLength", + "path": "global_objects/typedarray/bytelength", + "type": "TypedArray" + }, + { + "name": "TypedArray.byteOffset", + "path": "global_objects/typedarray/byteoffset", + "type": "TypedArray" + }, + { + "name": "TypedArray.BYTES_PER_ELEMENT", + "path": "global_objects/typedarray/bytes_per_element", + "type": "TypedArray" + }, + { + "name": "TypedArray.copyWithin", + "path": "global_objects/typedarray/copywithin", + "type": "TypedArray" + }, + { + "name": "typedArray.entries", + "path": "global_objects/typedarray/entries", + "type": "TypedArray" + }, + { + "name": "typedArray.every", + "path": "global_objects/typedarray/every", + "type": "TypedArray" + }, + { + "name": "typedArray.fill", + "path": "global_objects/typedarray/fill", + "type": "TypedArray" + }, + { + "name": "typedArray.filter", + "path": "global_objects/typedarray/filter", + "type": "TypedArray" + }, + { + "name": "typedArray.find", + "path": "global_objects/typedarray/find", + "type": "TypedArray" + }, + { + "name": "TypedArray.findIndex", + "path": "global_objects/typedarray/findindex", + "type": "TypedArray" + }, + { + "name": "TypedArray.findLast", + "path": "global_objects/typedarray/findlast", + "type": "TypedArray" + }, + { + "name": "TypedArray.findLastIndex", + "path": "global_objects/typedarray/findlastindex", + "type": "TypedArray" + }, + { + "name": "TypedArray.forEach", + "path": "global_objects/typedarray/foreach", + "type": "TypedArray" + }, + { + "name": "TypedArray.from", + "path": "global_objects/typedarray/from", + "type": "TypedArray" + }, + { + "name": "typedArray.includes", + "path": "global_objects/typedarray/includes", + "type": "TypedArray" + }, + { + "name": "TypedArray.indexOf", + "path": "global_objects/typedarray/indexof", + "type": "TypedArray" + }, + { + "name": "typedArray.join", + "path": "global_objects/typedarray/join", + "type": "TypedArray" + }, + { + "name": "typedArray.keys", + "path": "global_objects/typedarray/keys", + "type": "TypedArray" + }, + { + "name": "TypedArray.lastIndexOf", + "path": "global_objects/typedarray/lastindexof", + "type": "TypedArray" + }, + { + "name": "typedArray.length", + "path": "global_objects/typedarray/length", + "type": "TypedArray" + }, + { + "name": "typedArray.map", + "path": "global_objects/typedarray/map", + "type": "TypedArray" + }, + { + "name": "TypedArray.of", + "path": "global_objects/typedarray/of", + "type": "TypedArray" + }, + { + "name": "typedArray.reduce", + "path": "global_objects/typedarray/reduce", + "type": "TypedArray" + }, + { + "name": "TypedArray.reduceRight", + "path": "global_objects/typedarray/reduceright", + "type": "TypedArray" + }, + { + "name": "typedArray.reverse", + "path": "global_objects/typedarray/reverse", + "type": "TypedArray" + }, + { + "name": "typedArray.set", + "path": "global_objects/typedarray/set", + "type": "TypedArray" + }, + { + "name": "typedArray.slice", + "path": "global_objects/typedarray/slice", + "type": "TypedArray" + }, + { + "name": "typedArray.some", + "path": "global_objects/typedarray/some", + "type": "TypedArray" + }, + { + "name": "typedArray.sort", + "path": "global_objects/typedarray/sort", + "type": "TypedArray" + }, + { + "name": "typedArray.subarray", + "path": "global_objects/typedarray/subarray", + "type": "TypedArray" + }, + { + "name": "TypedArray.toLocaleString", + "path": "global_objects/typedarray/tolocalestring", + "type": "TypedArray" + }, + { + "name": "TypedArray.toReversed", + "path": "global_objects/typedarray/toreversed", + "type": "TypedArray" + }, + { + "name": "TypedArray.toSorted", + "path": "global_objects/typedarray/tosorted", + "type": "TypedArray" + }, + { + "name": "TypedArray.toString", + "path": "global_objects/typedarray/tostring", + "type": "TypedArray" + }, + { + "name": "typedArray.values", + "path": "global_objects/typedarray/values", + "type": "TypedArray" + }, + { + "name": "typedArray.with", + "path": "global_objects/typedarray/with", + "type": "TypedArray" + }, + { + "name": "TypeError", + "path": "global_objects/typeerror", + "type": "Errors" + }, + { + "name": "TypeError.typeError", + "path": "global_objects/typeerror/typeerror", + "type": "Errors" + }, + { "name": "typeof", "path": "operators/typeof", "type": "Operators" }, + { + "name": "Uint16Array", + "path": "global_objects/uint16array", + "type": "Global Objects" + }, + { + "name": "Uint16Array.uint16Array", + "path": "global_objects/uint16array/uint16array", + "type": "Uint16Array" + }, + { + "name": "Uint32Array", + "path": "global_objects/uint32array", + "type": "Global Objects" + }, + { + "name": "Uint32Array.uint32Array", + "path": "global_objects/uint32array/uint32array", + "type": "Uint32Array" + }, + { + "name": "Uint8Array", + "path": "global_objects/uint8array", + "type": "Global Objects" + }, + { + "name": "Uint8Array.uint8Array", + "path": "global_objects/uint8array/uint8array", + "type": "Uint8Array" + }, + { + "name": "Uint8ClampedArray", + "path": "global_objects/uint8clampedarray", + "type": "Global Objects" + }, + { + "name": "Uint8ClampedArray.uint8ClampedArray", + "path": "global_objects/uint8clampedarray/uint8clampedarray", + "type": "Uint8ClampedArray" + }, + { + "name": "Unary negation", + "path": "operators/unary_negation", + "type": "Operators" + }, + { + "name": "Unary plus", + "path": "operators/unary_plus", + "type": "Operators" + }, + { + "name": "undefined", + "path": "global_objects/undefined", + "type": "Global Objects" + }, + { + "name": "unescape", + "path": "global_objects/unescape", + "type": "Global Objects" + }, + { + "name": "Unsigned right shift", + "path": "operators/unsigned_right_shift", + "type": "Operators" + }, + { + "name": "Unsigned right shift assignment", + "path": "operators/unsigned_right_shift_assignment", + "type": "Operators" + }, + { "name": "URIError", "path": "global_objects/urierror", "type": "Errors" }, + { + "name": "URIError.uRIError", + "path": "global_objects/urierror/urierror", + "type": "Errors" + }, + { "name": "var", "path": "statements/var", "type": "Statements" }, + { "name": "void", "path": "operators/void", "type": "Operators" }, + { "name": "WeakMap", "path": "global_objects/weakmap", "type": "WeakMap" }, + { + "name": "weakMap.delete", + "path": "global_objects/weakmap/delete", + "type": "WeakMap" + }, + { + "name": "weakMap.get", + "path": "global_objects/weakmap/get", + "type": "WeakMap" + }, + { + "name": "weakMap.has", + "path": "global_objects/weakmap/has", + "type": "WeakMap" + }, + { + "name": "weakMap.set", + "path": "global_objects/weakmap/set", + "type": "WeakMap" + }, + { + "name": "WeakMap.weakMap", + "path": "global_objects/weakmap/weakmap", + "type": "WeakMap" + }, + { + "name": "WeakRef", + "path": "global_objects/weakref", + "type": "Global Objects" + }, + { + "name": "weakRef.deref", + "path": "global_objects/weakref/deref", + "type": "WeakRef" + }, + { + "name": "WeakRef.weakRef", + "path": "global_objects/weakref/weakref", + "type": "WeakRef" + }, + { "name": "WeakSet", "path": "global_objects/weakset", "type": "WeakSet" }, + { + "name": "weakSet.add", + "path": "global_objects/weakset/add", + "type": "WeakSet" + }, + { + "name": "weakSet.delete", + "path": "global_objects/weakset/delete", + "type": "WeakSet" + }, + { + "name": "weakSet.has", + "path": "global_objects/weakset/has", + "type": "WeakSet" + }, + { + "name": "WeakSet.weakSet", + "path": "global_objects/weakset/weakset", + "type": "WeakSet" + }, + { "name": "while", "path": "statements/while", "type": "Statements" }, + { "name": "with", "path": "statements/with", "type": "Statements" }, + { "name": "yield", "path": "operators/yield", "type": "Operators" }, + { "name": "yield*", "path": "operators/yield*", "type": "Operators" } + ], + "types": [ + { "name": "Array", "count": 48, "slug": "array" }, + { "name": "ArrayBuffer", "count": 12, "slug": "arraybuffer" }, + { "name": "AsyncGenerator", "count": 3, "slug": "asyncgenerator" }, + { "name": "AsyncIterator", "count": 1, "slug": "asynciterator" }, + { "name": "Atomics", "count": 14, "slug": "atomics" }, + { "name": "BigInt", "count": 6, "slug": "bigint" }, + { "name": "BigInt64Array", "count": 1, "slug": "bigint64array" }, + { "name": "BigUint64Array", "count": 1, "slug": "biguint64array" }, + { "name": "Boolean", "count": 4, "slug": "boolean" }, + { "name": "Classes", "count": 7, "slug": "classes" }, + { "name": "DataView", "count": 25, "slug": "dataview" }, + { "name": "Date", "count": 51, "slug": "date" }, + { "name": "Errors", "count": 109, "slug": "errors" }, + { + "name": "FinalizationRegistry", + "count": 3, + "slug": "finalizationregistry" + }, + { "name": "Float32Array", "count": 1, "slug": "float32array" }, + { "name": "Float64Array", "count": 1, "slug": "float64array" }, + { "name": "Function", "count": 30, "slug": "function" }, + { "name": "Generator", "count": 4, "slug": "generator" }, + { "name": "Global Objects", "count": 33, "slug": "global-objects" }, + { "name": "Int16Array", "count": 1, "slug": "int16array" }, + { "name": "Int32Array", "count": 1, "slug": "int32array" }, + { "name": "Int8Array", "count": 1, "slug": "int8array" }, + { "name": "Intl", "count": 83, "slug": "intl" }, + { "name": "Iterator", "count": 14, "slug": "iterator" }, + { "name": "JSON", "count": 3, "slug": "json" }, + { "name": "Map", "count": 15, "slug": "map" }, + { "name": "Math", "count": 44, "slug": "math" }, + { "name": "Miscellaneous", "count": 23, "slug": "miscellaneous" }, + { "name": "Number", "count": 22, "slug": "number" }, + { "name": "Object", "count": 37, "slug": "object" }, + { "name": "Operators", "count": 75, "slug": "operators" }, + { "name": "Promise", "count": 12, "slug": "promise" }, + { "name": "Proxy", "count": 15, "slug": "proxy" }, + { "name": "Reflect", "count": 14, "slug": "reflect" }, + { "name": "RegExp", "count": 29, "slug": "regexp" }, + { "name": "Set", "count": 13, "slug": "set" }, + { "name": "SharedArrayBuffer", "count": 8, "slug": "sharedarraybuffer" }, + { "name": "Statements", "count": 29, "slug": "statements" }, + { "name": "String", "count": 55, "slug": "string" }, + { "name": "Symbol", "count": 21, "slug": "symbol" }, + { "name": "TypedArray", "count": 41, "slug": "typedarray" }, + { "name": "Uint16Array", "count": 1, "slug": "uint16array" }, + { "name": "Uint32Array", "count": 1, "slug": "uint32array" }, + { "name": "Uint8Array", "count": 1, "slug": "uint8array" }, + { "name": "Uint8ClampedArray", "count": 1, "slug": "uint8clampedarray" }, + { "name": "WeakMap", "count": 6, "slug": "weakmap" }, + { "name": "WeakRef", "count": 2, "slug": "weakref" }, + { "name": "WeakSet", "count": 5, "slug": "weakset" } + ] +}