repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/html | data/mdn-content/files/en-us/web/html/microdata/index.md | ---
title: Microdata
slug: Web/HTML/Microdata
page-type: guide
---
{{HTMLSidebar}}
Microdata is part of the {{glossary("WHATWG")}} HTML Standard and is used to nest metadata within existing content on web pages. Search engines and web crawlers can extract and process microdata from a web page and use it to provide a richer browsing experience for users. Search engines benefit greatly from direct access to this structured data because it allows search engines to understand the information on web pages and provide more relevant results to users. Microdata uses a supporting vocabulary to describe an item and name-value pairs to assign values to its properties. Microdata is an attempt to provide a simpler way of annotating HTML elements with machine-readable tags than the similar approaches of using RDFa and classic microformats.
At a high level, microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
- To create an item, the `itemscope` attribute is used.
- To add a property to an item, the `itemprop` attribute is used on one of the item's descendants.
## Vocabularies
Google and other major search engines support the [Schema.org](https://schema.org) vocabulary for structured data. This vocabulary defines a standard set of type names and property names, for example, [Schema.org Music Event](https://schema.org/MusicEvent) indicates a concert performance, with [`startDate`](https://schema.org/startDate) and [`location`](https://schema.org/location) properties to specify the concert's key details. In this case, [Schema.org Music Event](https://schema.org/MusicEvent) would be the URL used by `itemtype` and `startDate` and location would be `itemprop`'s that [Schema.org Music Event](https://schema.org/MusicEvent) defines.
> **Note:** More about itemtype attributes can be found at <https://schema.org/Thing>.
Microdata vocabularies provide the semantics or meaning of an _`Item`_. Web developers can design a custom vocabulary or use vocabularies available on the web, such as the widely used [schema.org](https://schema.org) vocabulary. A collection of commonly used markup vocabularies are provided by Schema.org.
Commonly used vocabularies:
- Creative works: [CreativeWork](https://schema.org/CreativeWork), [Book](https://schema.org/Book), [Movie](https://schema.org/Movie), [MusicRecording](https://schema.org/MusicRecording), [Recipe](https://schema.org/Recipe), [TVSeries](https://schema.org/TVSeries)
- Embedded non-text objects: [AudioObject](https://schema.org/AudioObject), [ImageObject](https://schema.org/ImageObject), [VideoObject](https://schema.org/VideoObject)
- [`Event`](https://schema.org/Event)
- [Health and medical types](https://schema.org/docs/meddocs.html): Notes on the health and medical types under [MedicalEntity](https://schema.org/MedicalEntity)
- [`Organization`](https://schema.org/Organization)
- [`Person`](https://schema.org/Person)
- [`Place`](https://schema.org/Place), [LocalBusiness](https://schema.org/LocalBusiness), [Restaurant](https://schema.org/Restaurant)
- [`Product`](https://schema.org/Product), [Offer](https://schema.org/Offer), [AggregateOffer](https://schema.org/AggregateOffer)
- [`Review`](https://schema.org/Review), [AggregateRating](https://schema.org/AggregateRating)
- [`Action`](https://schema.org/Action)
- [`Thing`](https://schema.org/Thing)
- [`Intangible`](https://schema.org/Intangible)
Major search engine operators like Google, Microsoft, and Yahoo! rely on the [schema.org](https://schema.org/) vocabulary to improve search results. For some purposes, an ad hoc vocabulary is adequate. For others, a vocabulary will need to be designed. Where possible, authors are encouraged to re-use existing vocabularies, as this makes content re-use easier.
## Localization
In some cases, search engines covering specific regions may provide locally-specific extensions of microdata. For example, [Yandex](https://yandex.com/), a major search engine in Russia, supports microformats such as `hCard` (company contact information), `hRecipe` (food recipe), `hReview` (market reviews) and `hProduct` (product data) and provides its own format for the definition of the terms and encyclopedic articles. This extension was made to solve transliteration problems between the Cyrillic and Latin alphabets. Due to the implementation of additional marking parameters of Schema's vocabulary, the indexation of information in Russian-language web-pages became considerably more successful.
## Global attributes
[`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) β The unique, global identifier of an item.
[`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) β Used to add properties to an item. Every HTML element may have an `itemprop` attribute specified, where an `itemprop` consists of a name and value pair.
[`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) β Properties that are not descendants of an element with the `itemscope` attribute can be associated with the item using an **itemref**. `itemref` provides a list of element ids (not `itemid`s) with additional properties elsewhere in the document.
[`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) β The `itemscope` attribute (usually) works along with [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype) to specify that the HTML contained in a block is about a particular item. The `itemscope` attribute creates the _`Item`_ and defines the scope of the itemtype associated with it. The `itemtype` attribute is a valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context.
[`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype) β Specifies the URL of the vocabulary that will be used to define `itemprop`'s (item properties) in the data structure. The [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) attribute is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active.
## Example
### HTML
```html
<div itemscope itemtype="https://schema.org/SoftwareApplication">
<span itemprop="name">Angry Birds</span> - REQUIRES
<span itemprop="operatingSystem">ANDROID</span><br />
<link
itemprop="applicationCategory"
href="https://schema.org/SoftwareApplication" />
<div
itemprop="aggregateRating"
itemscope
itemtype="https://schema.org/AggregateRating">
RATING:
<span itemprop="ratingValue">4.6</span> (
<span itemprop="ratingCount">8864</span> ratings )
</div>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
Price: $<span itemprop="price">1.00</span>
<meta itemprop="priceCurrency" content="USD" />
</div>
</div>
```
### Structured data
<table class="standard-table">
<tbody>
<tr>
<td rowspan="4">itemscope</td>
<td>itemtype</td>
<td colspan="2">
SoftwareApplication (https://schema.org/SoftwareApplication)
</td>
</tr>
<tr>
<td>itemprop</td>
<td>name</td>
<td>Angry Birds</td>
</tr>
<tr>
<td>itemprop</td>
<td>operatingSystem</td>
<td>ANDROID</td>
</tr>
<tr>
<td>itemprop</td>
<td>applicationCategory</td>
<td>SoftwareApplication (https://schema.org/SoftwareApplication)</td>
</tr>
<tr>
<td rowspan="3">itemscope</td>
<td>itemprop[itemtype]</td>
<td colspan="2">aggregateRating [AggregateRating]</td>
</tr>
<tr>
<td>itemprop</td>
<td>ratingValue</td>
<td>4.6</td>
</tr>
<tr>
<td>itemprop</td>
<td>ratingCount</td>
<td>8864</td>
</tr>
<tr>
<td rowspan="3">itemscope</td>
<td>itemprop[itemtype]</td>
<td colspan="2">offers [Offer]</td>
</tr>
<tr>
<td>itemprop</td>
<td>price</td>
<td>1.00</td>
</tr>
<tr>
<td>itemprop</td>
<td>priceCurrency</td>
<td>USD</td>
</tr>
</tbody>
</table>
### Result
{{ EmbedLiveSample('HTML', '', '100') }}
> **Note:** A handy tool for extracting microdata structures from HTML is Google's [Structured Data Testing Tool](https://developers.google.com/search/docs/advanced/structured-data/intro-structured-data). Try it on the HTML shown above.
## Browser compatibility
Supported in Firefox 16. Removed in Firefox 49.
## See also
- [Global Attributes](/en-US/docs/Web/HTML/Global_attributes)
| 0 |
data/mdn-content/files/en-us/web/html | data/mdn-content/files/en-us/web/html/cors_enabled_image/index.md | ---
title: Allowing cross-origin use of images and canvas
slug: Web/HTML/CORS_enabled_image
page-type: guide
---
{{HTMLSidebar}}
HTML provides a [`crossorigin`](/en-US/docs/Web/HTML/Element/img#crossorigin) attribute for images that, in combination with an appropriate {{Glossary("CORS")}} header, allows images defined by the {{ HTMLElement("img") }} element that are loaded from foreign origins to be used in a {{HTMLElement("canvas")}} as if they had been loaded from the current origin.
See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for details on how the `crossorigin` attribute is used.
## Security and tainted canvases
Because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise.
As soon as you draw into a canvas any data that was loaded from another origin without CORS approval, the canvas becomes **tainted**. A tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown.
If the source of the foreign content is an HTML {{HTMLElement("img")}} or SVG {{SVGElement("svg")}} element, attempting to retrieve the contents of the canvas isn't allowed.
If the foreign content comes from an image obtained from either as {{domxref("HTMLCanvasElement")}} or {{domxref("ImageBitMap")}}, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked.
Calling any of the following on a tainted canvas will result in an error:
- Calling {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} on the canvas's context
- Calling {{domxref("HTMLCanvasElement.toBlob", "toBlob()")}}, {{domxref("HTMLCanvasElement.toDataURL", "toDataURL()")}} or {{domxref("HTMLCanvasElement.captureStream", "captureStream()")}} on the {{HTMLElement("canvas")}} element itself
Attempting any of these when the canvas is tainted will cause a `SecurityError` to be thrown. This protects users from having private data exposed by using images to pull information from remote websites without permission.
## Storing an image from a foreign origin
In this example, we wish to permit images from a foreign origin to be retrieved and saved to local storage. Implementing this requires configuring the server as well as writing code for the website itself.
### Web server configuration
The first thing we need is a server that's configured to host images with the {{HTTPHeader("Access-Control-Allow-Origin")}} header configured to permit cross-origin access to image files.
Let's assume we're serving our site using [Apache](https://httpd.apache.org/). Consider the HTML5 Boilerplate [Apache server configuration file for CORS images](https://github.com/h5bp/server-configs-apache/blob/main/h5bp/cross-origin/images.conf), shown below:
```xml
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(avifs?|bmp|cur|gif|ico|jpe?g|jxl|a?png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
```
In short, this configures the server to allow graphic files (those with the extensions ".bmp", ".cur", ".gif", ".ico", ".jpg", ".jpeg", ".png", ".svg", ".svgz", and ".webp") to be accessed cross-origin from anywhere on the internet.
### Implementing the save feature
Now that the server has been configured to allow retrieval of the images cross-origin, we can write the code that allows the user to save them to [local storage](/en-US/docs/Web/API/Web_Storage_API), just as if they were being served from the same domain the code is running on.
The key is to use the [`crossorigin`](/en-US/docs/Web/HTML/Element/image#crossorigin) attribute by setting {{domxref("HTMLImageElement.crossOrigin", "crossOrigin")}} on the {{domxref("HTMLImageElement")}} into which the image will be loaded. This tells the browser to request cross-origin access when downloading the image data.
#### Starting the download
The code that starts the download (say, when the user clicks a "Download" button), looks like this:
```js
function startDownload() {
let imageURL =
"https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189";
let imageDescription = "The Mozilla logo";
downloadedImg = new Image();
downloadedImg.crossOrigin = "anonymous";
downloadedImg.addEventListener("load", imageReceived, false);
downloadedImg.alt = imageDescription;
downloadedImg.src = imageURL;
}
```
We're using a hard-coded URL (`imageURL`) and associated descriptive text (`imageDescription`) here, but that could easily come from anywhere. To begin downloading the image, we create a new {{domxref("HTMLImageElement")}} object by using the {{domxref("HTMLImageElement.Image", "Image()")}} constructor. The image is then configured to allow cross-origin downloading by setting its `crossOrigin` attribute to `"anonymous"` (that is, allow non-authenticated downloading of the image cross-origin). An event listener is added for the {{domxref("Window/load_event", "load")}} event being fired on the image element, which means the image data has been received. Alternative text is added to the image; while `<canvas>` does not support the `alt` attribute, the value can be used to set an `aria-label` or the canvas's inner content.
Finally, the image's {{domxref("HTMLImageElement.src", "src")}} attribute is set to the URL of the image to download; this triggers the download to begin.
#### Receiving and saving the image
The code that handles the newly-downloaded image is found in the `imageReceived()` method:
```js
function imageReceived() {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = downloadedImg.width;
canvas.height = downloadedImg.height;
canvas.innerText = downloadedImg.alt;
context.drawImage(downloadedImg, 0, 0);
imageBox.appendChild(canvas);
try {
localStorage.setItem("saved-image-example", canvas.toDataURL("image/png"));
} catch (err) {
console.error(`Error: ${err}`);
}
}
```
`imageReceived()` is called to handle the `"load"` event on the `HTMLImageElement` that receives the downloaded image. This event is triggered once the downloaded data is all available. It begins by creating a new {{HTMLElement("canvas")}} element that we'll use to convert the image into a data URL, and by getting access to the canvas's 2D drawing context ({{domxref("CanvasRenderingContext2D")}}) in the variable `context`.
The canvas's size is adjusted to match the received image, the inner text is set to the image description, then the image is drawn into the canvas using {{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}}. The canvas is then inserted into the document so the image is visible.
Now it's time to actually save the image locally. To do this, we use the Web Storage API's local storage mechanism, which is accessed through the {{domxref("Window.localStorage", "localStorage")}} global. The canvas method {{domxref("HTMLCanvasElement.toDataURL", "toDataURL()")}} is used to convert the image into a data:// URL representing a PNG image, which is then saved into local storage using {{domxref("Storage.setItem", "setItem()")}}.
## See also
- [Using Cross-domain images in WebGL and Chrome 13](https://blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html)
- [HTML Specification - the `crossorigin` attribute](https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-crossorigin)
- [Web Storage API](/en-US/docs/Web/API/Web_Storage_API)
| 0 |
data/mdn-content/files/en-us/web | data/mdn-content/files/en-us/web/opensearch/index.md | ---
title: OpenSearch description format
slug: Web/OpenSearch
page-type: guide
---
{{AddonSidebar}}
The **[OpenSearch description format](https://github.com/dewitt/opensearch)** can be used to describe the web interface of a search engine. This allows a website to describe a search engine for itself, so that a browser or other client application can use that search engine. OpenSearch is supported by (at least) Firefox, Edge, Safari, and Chrome. (See [Reference Material](#reference_material) for links to other browsers' documentation.)
Firefox also supports additional features not in the OpenSearch standard, such as search suggestions and the `<SearchForm>` element. This article focuses on creating OpenSearch-compatible search plugins that support these additional Firefox features.
OpenSearch description files can be advertised as described in [Autodiscovery of search plugins](#autodiscovery_of_search_plugins).
> **Warning:** OpenSearch plugins can't be uploaded anymore on [addons.mozilla.org](https://addons.mozilla.org) (AMO). Search engine feature must use WebExtension API with [chrome settings](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides) in `manifest.json` file.
## OpenSearch description file
The XML file that describes a search engine follows the basic template below. Sections in _\[square brackets]_ should be customized for the specific plugin you're writing.
```xml
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>[SNK]</ShortName>
<Description>[Search engine full name and summary]</Description>
<InputEncoding>[UTF-8]</InputEncoding>
<Image width="16" height="16" type="image/x-icon">[https://example.com/favicon.ico]</Image>
<Url type="text/html" template="[searchURL]"/>
<Url type="application/x-suggestions+json" template="[suggestionURL]"/>
<moz:SearchForm>[https://example.com/search]</moz:SearchForm>
</OpenSearchDescription>
```
- ShortName
- : A short name for the search engine. It must be **16 or fewer character**s of plain text, with no HTML or other markup.
- Description
- : A brief description of the search engine. It must be **1024 or fewer characters** of plain text, with no HTML or other markup.
- InputEncoding
- : The [character encoding](/en-US/docs/Glossary/Character_encoding) to use when submitting input to the search engine.
- Image
- : URL of an icon for the search engine. When possible, include a 16Γ16 image of type `image/x-icon` (such as `/favicon.ico`) and a 64Γ64 image of type `image/jpeg` or `image/png`.
The URL may also use the [`data:` URL scheme](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). (You can generate a `data:` URL from an icon file at [The `data:` URL kitchen](https://software.hixie.ch/utilities/cgi/data/data).)
```xml
<Image height="16" width="16" type="image/x-icon">https://example.com/favicon.ico</Image>
<!-- or -->
<Image height="16" width="16">data:image/x-icon;base64,AAABAAEAEBAAA β¦ DAAA=</Image>
```
Firefox caches the icon as a [base64](https://en.wikipedia.org/wiki/Base64) `data:` URL (search plug-ins are stored in the [profile](https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data)'s `searchplugins/` folder). `http:` and `https:` URLs are converted to `data:` URLs when this is done.
> **Note:** For icons loaded remotely (that is, from `https://` URLs as opposed to `data:` URLs), Firefox will reject icons larger than **10 kilobytes**.

- Url
- : Describes the URL or URLs to use for the search. The `template` attribute indicates the base URL for the search query.
Firefox supports three URL types:
- `type="text/html"` specifies the URL for the actual search query.
- `type="application/x-suggestions+json"` specifies the URL for fetching search suggestions. In Firefox 63 onwards, `type="application/json"` is accepted as an alias of this.
- `type="application/x-moz-keywordsearch"` specifies the URL used when a keyword search is entered in the location bar. This is supported only in Firefox.
For these URL types, you can use `{searchTerms}` to substitute the search terms entered by the user in the search bar or location bar. Other supported dynamic search parameters are described in [OpenSearch 1.1 parameters](https://github.com/dewitt/opensearch/blob/master/opensearch-1-1-draft-6.md#opensearch-11-parameters).
For search suggestions, the `application/x-suggestions+json` URL template is used to fetch a suggestion list in [JSON](/en-US/docs/Glossary/JSON) format.
## Autodiscovery of search plugins
Websites with search plugins can advertise them so Firefox users can easily install the plugins.
To support autodiscovery, add a `<link>` element for each plugin to the `<head>` of your web page:
```html
<link
rel="search"
type="application/opensearchdescription+xml"
title="searchTitle"
href="pluginURL" />
```
Replace the bolded items as explained below:
- searchTitle
- : The name of the search to perform, such as "Search MDC" or "Yahoo! Search". This must match your plugin file's `<ShortName>`.
- pluginURL
- : The URL to the XML search plugin, so the browser can download it.
If your site offers multiple search plugins, you can support autodiscovery for them all. For example:
```html
<link
rel="search"
type="application/opensearchdescription+xml"
title="MySite: By Author"
href="http://example.com/mysiteauthor.xml" />
<link
rel="search"
type="application/opensearchdescription+xml"
title="MySite: By Title"
href="http://example.com/mysitetitle.xml" />
```
This way, your site can offer plugins to search by author, or by title.
> **Note:** In Firefox, an icon change in the search box indicates there's a provided search plugin. (See image, the green plus sign.) Thus if a search box is not shown in the user's UI, they will receive _no_ indication. _In general, behavior varies among browsers_.
## Supporting automatic updates for OpenSearch plugins
OpenSearch plugins can automatically update. To support this, include an extra `Url` element with `type="application/opensearchdescription+xml"` and `rel="self"`. The `template` attribute should be the URL of the OpenSearch document to automatically update to.
For example:
```xml
<Url type="application/opensearchdescription+xml"
rel="self"
template="https://example.com/mysearchdescription.xml" />
```
> **Note:** At this time, [addons.mozilla.org](https://addons.mozilla.org) (AMO) doesn't support automatic updating of OpenSearch plugins. If you want to put your search plugin on AMO, remove the auto-updating feature before submitting it.
## Troubleshooting Tips
If there is a mistake in your Search Plugin XML, you could run into errors when adding a discovered plugin. If the error message isn't be helpful, the following tips could help you find the problem.
- Your server should serve OpenSearch plugins using `Content-Type: application/opensearchdescription+xml`.
- Be sure that your Search Plugin XML is well formed. You can check by loading the file directly into Firefox. Ampersands (&) in the `template` URL must be escaped as `&`, and tags must be closed with a trailing slash or matching end tag.
- The `xmlns` attribute is important β without it you could get the error message "Firefox could not download the search plugin".
- You **must** include a `text/html` URL β search plugins including only Atom or [RSS](/en-US/docs/Glossary/RSS) URL types (which is valid, but Firefox doesn't support) will also generate the "could not download the search plugin" error.
- Remotely fetched favicons must not be larger than 10KB (see [Firefox bug 361923](https://bugzil.la/361923)).
In addition, the search plugin service provides a logging mechanism that may be useful to plugin developers. Use `about:config` to set the pref '`browser.search.log`' to `true`. Then, logging information will appear in Firefox's [Browser Console](https://firefox-source-docs.mozilla.org/devtools-user/browser_console/index.html)(Tools β€ Browser Tools β€ Browser Console) when search plugins are added.
## Reference Material
- [OpenSearch Documentation](https://github.com/dewitt/opensearch)
- [Safari 8.0 Release Notes: Quick Website Search](https://developer.apple.com/library/archive/releasenotes/General/WhatsNewInSafari/Articles/Safari_8_0.html)
- [Microsoft Edge Dev Guide: Search provider discovery](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/)
- [The Chromium Projects: Tab to Search](https://www.chromium.org/tab-to-search/)
- imdb.com has a [working `osd.xml`](https://m.media-amazon.com/images/G/01/imdb/images/imdbsearch-3349468880._CB470047351_.xml)
- [Ready2Search](https://ready.to/search/en/) - create OpenSearch plugins. [Customized Search through Ready2Search](https://ready.to/search/make/en_make_plugin.htm)
| 0 |
data/mdn-content/files/en-us/web | data/mdn-content/files/en-us/web/javascript/index.md | ---
title: JavaScript
slug: Web/JavaScript
page-type: landing-page
---
{{jsSidebar}}
**JavaScript** (**JS**) is a lightweight interpreted (or [just-in-time](https://en.wikipedia.org/wiki/Just-in-time_compilation) compiled) programming language with {{Glossary("First-class Function", "first-class functions")}}. While it is most well-known as the scripting language for Web pages, [many non-browser environments](https://en.wikipedia.org/wiki/JavaScript#Other_usage) also use it, such as {{Glossary("Node.js")}}, [Apache CouchDB](https://couchdb.apache.org/) and [Adobe Acrobat](https://opensource.adobe.com/dc-acrobat-sdk-docs/acrobatsdk/). JavaScript is a [prototype-based](/en-US/docs/Glossary/Prototype-based_programming), multi-paradigm, [single-threaded](/en-US/docs/Glossary/Thread), [dynamic](/en-US/docs/Glossary/Dynamic_typing) language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.
JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via [`eval`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)), object introspection (via [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) and [`Object` utilities](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#static_methods)), and source-code recovery (JavaScript functions store their source text and can be retrieved through [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString)).
This section is dedicated to the JavaScript language itself, and not the parts that are specific to Web pages or other host environments. For information about {{Glossary("API", "APIs")}} that are specific to Web pages, please see [Web APIs](/en-US/docs/Web/API) and {{Glossary("DOM")}}.
The standards for JavaScript are the [ECMAScript Language Specification](https://tc39.es/ecma262/) (ECMA-262) and the [ECMAScript Internationalization API specification](https://tc39.es/ecma402/) (ECMA-402). As soon as one browser implements a feature, we try to document it. This means that cases where some [proposals for new ECMAScript features](https://github.com/tc39/proposals) have already been implemented in browsers, documentation and examples in MDN articles may use some of those new features. Most of the time, this happens between the [stages](https://tc39.es/process-document/) 3 and 4, and is usually before the spec is officially published.
Do not confuse JavaScript with the [Java programming language](<https://en.wikipedia.org/wiki/Java_(programming_language)>) β **JavaScript is _not_ "Interpreted Java"**. Both "Java" and "JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have very different syntax, semantics, and use.
JavaScript documentation of core language features (pure [ECMAScript](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview), for the most part) includes the following:
- The [JavaScript guide](/en-US/docs/Web/JavaScript/Guide)
- The [JavaScript reference](/en-US/docs/Web/JavaScript/Reference)
For more information about JavaScript specifications and related technologies, see [JavaScript technologies overview](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview).
> **Callout:** **Looking to become a front-end web developer?**
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Tutorials
Learn how to program in JavaScript with guides and tutorials.
### For complete beginners
Head over to our [Learning Area JavaScript topic](/en-US/docs/Learn/JavaScript) if you want to learn JavaScript but have no previous experience with JavaScript or programming. The complete modules available there are as follows:
- [JavaScript first steps](/en-US/docs/Learn/JavaScript/First_steps)
- : Answers some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", along with discussing key JavaScript features such as variables, strings, numbers, and arrays.
- [JavaScript building blocks](/en-US/docs/Learn/JavaScript/Building_blocks)
- : Continues our coverage of JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.
- [Introducing JavaScript objects](/en-US/docs/Learn/JavaScript/Objects)
- : The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.
- [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous)
- : Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
- [Client-side web APIs](/en-US/docs/Learn/JavaScript/Client-side_web_APIs)
- : Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.
### JavaScript guide
- [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide)
- : A much more detailed guide to the JavaScript language, aimed at those with previous programming experience either in JavaScript or another language.
### Intermediate
- [Understanding client-side JavaScript frameworks](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks)
- : JavaScript frameworks are an essential part of modern front-end web development, providing developers with proven tools for building scalable, interactive web applications. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to a series of tutorials covering some of today's most popular ones.
- [JavaScript language overview](/en-US/docs/Web/JavaScript/Language_overview)
- : An overview of the basic syntax and semantics of JavaScript for those coming from other programming languages to get up to speed.
- [JavaScript data structures](/en-US/docs/Web/JavaScript/Data_structures)
- : Overview of available data structures in JavaScript.
- [Equality comparisons and sameness](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)
- : JavaScript provides three different value comparison operations: strict equality using `===`, loose equality using `==`, and the {{jsxref("Object.is()")}} method.
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- : How different methods that visit a group of object properties one-by-one handle the enumerability and ownership of properties.
- [Closures](/en-US/docs/Web/JavaScript/Closures)
- : A closure is the combination of a function and the lexical environment within which that function was declared.
### Advanced
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
- : Explanation of the widely misunderstood and underestimated prototype-based inheritance.
- [Memory Management](/en-US/docs/Web/JavaScript/Memory_management)
- : Memory life cycle and garbage collection in JavaScript.
- [The event loop](/en-US/docs/Web/JavaScript/Event_loop)
- : JavaScript has a runtime model based on an "event loop".
## Reference
Browse the complete [JavaScript reference](/en-US/docs/Web/JavaScript/Reference) documentation.
- [Standard objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects)
- : Get to know standard built-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.
- [Expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators)
- : Learn more about the behavior of JavaScript's operators {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}, the [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence), and more.
- [Statements and declarations](/en-US/docs/Web/JavaScript/Reference/Statements)
- : Learn how {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, and more JavaScript statements and keywords work.
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- : Learn how to work with JavaScript's functions to develop your applications.
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- : JavaScript classes are the most appropriate way to do object-oriented programming.
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/equality_comparisons_and_sameness/index.md | ---
title: Equality comparisons and sameness
slug: Web/JavaScript/Equality_comparisons_and_sameness
page-type: guide
---
{{jsSidebar("Intermediate")}}
JavaScript provides three different value-comparison operations:
- [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) β strict equality (triple equals)
- [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) β loose equality (double equals)
- [`Object.is()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
Which operation you choose depends on what sort of comparison you are looking to perform. Briefly:
- Double equals (`==`) will perform a type conversion when comparing two things, and will handle `NaN`, `-0`, and `+0` specially to conform to IEEE 754 (so `NaN != NaN`, and `-0 == +0`);
- Triple equals (`===`) will do the same comparison as double equals (including the special handling for `NaN`, `-0`, and `+0`) but without type conversion; if the types differ, `false` is returned.
- `Object.is()` does no type conversion and no special handling for `NaN`, `-0`, and `+0` (giving it the same behavior as `===` except on those special numeric values).
They correspond to three of four equality algorithms in JavaScript:
- [IsLooselyEqual](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-islooselyequal): `==`
- [IsStrictlyEqual](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-isstrictlyequal): `===`
- [SameValue](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevalue): `Object.is()`
- [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero): used by many built-in operations
Note that the distinction between these all have to do with their handling of primitives; none of them compares whether the parameters are conceptually similar in structure. For any non-primitive objects `x` and `y` which have the same structure but are distinct objects themselves, all of the above forms will evaluate to `false`.
## Strict equality using ===
Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. If the values have the same type, are not numbers, and have the same value, they're considered equal. Finally, if both values are numbers, they're considered equal if they're both not `NaN` and are the same value, or if one is `+0` and one is `-0`.
```js
const num = 0;
const obj = new String("0");
const str = "0";
console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true
console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false
console.log(null === undefined); // false
console.log(obj === null); // false
console.log(obj === undefined); // false
```
Strict equality is almost always the correct comparison operation to use. For all values except numbers, it uses the obvious semantics: a value is only equal to itself. For numbers it uses slightly different semantics to gloss over two different edge cases. The first is that floating point zero is either positively or negatively signed. This is useful in representing certain mathematical solutions, but as most situations don't care about the difference between `+0` and `-0`, strict equality treats them as the same value. The second is that floating point includes the concept of a not-a-number value, `NaN`, to represent the solution to certain ill-defined mathematical problems: negative infinity added to positive infinity, for example. Strict equality treats `NaN` as unequal to every other value β including itself. (The only case in which `(x !== x)` is `true` is when `x` is `NaN`.)
Besides `===`, strict equality is also used by array index-finding methods including [`Array.prototype.indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), [`Array.prototype.lastIndexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf), [`TypedArray.prototype.indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf), [`TypedArray.prototype.lastIndexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/lastIndexOf), and [`case`](/en-US/docs/Web/JavaScript/Reference/Statements/switch)-matching. This means you cannot use `indexOf(NaN)` to find the index of a `NaN` value in an array, or use `NaN` as a `case` value in a `switch` statement and make it match anything.
```js
console.log([NaN].indexOf(NaN)); // -1
switch (NaN) {
case NaN:
console.log("Surprise"); // Nothing is logged
}
```
## Loose equality using ==
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 behavior for performing loose equality using `==` is 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](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion).
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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion): `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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). 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()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) constructor. If conversion fails, return `false`.
Traditionally, and according to ECMAScript, all primitives and objects are loosely unequal to `undefined` and `null`. But most browsers permit a very narrow class of objects (specifically, the `document.all` object for any page), in some contexts, to act as if they _emulate_ the value `undefined`. Loose equality is one such context: `null == A` and `undefined == A` evaluate to true if, and only if, A is an object that _emulates_ `undefined`. In all other cases an object is never loosely equal to `undefined` or `null`.
In most cases, using loose equality is discouraged. The result of a comparison using strict equality is easier to predict, and may evaluate more quickly due to the lack of type coercion.
The following example demonstrates loose equality comparisons involving the number primitive `0`, the bigint primitive `0n`, the string primitive `'0'`, and an object whose `toString()` value is `'0'`.
```js
const num = 0;
const big = 0n;
const str = "0";
const obj = new String("0");
console.log(num == str); // true
console.log(big == num); // true
console.log(str == big); // true
console.log(num == obj); // true
console.log(big == obj); // true
console.log(str == obj); // true
```
Loose equality is only used by the `==` operator.
## Same-value equality using Object.is()
Same-value equality determines whether two values are _functionally identical_ in all contexts. (This use case demonstrates an instance of the [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle).) One instance occurs when an attempt is made to mutate an immutable property:
```js
// Add an immutable NEGATIVE_ZERO property to the Number constructor.
Object.defineProperty(Number, "NEGATIVE_ZERO", {
value: -0,
writable: false,
configurable: false,
enumerable: false,
});
function attemptMutation(v) {
Object.defineProperty(Number, "NEGATIVE_ZERO", { value: v });
}
```
`Object.defineProperty` will throw an exception when attempting to change an immutable property, but it does nothing if no actual change is requested. If `v` is `-0`, no change has been requested, and no error will be thrown. Internally, when an immutable property is redefined, the newly-specified value is compared against the current value using same-value equality.
Same-value equality is provided by the {{jsxref("Object.is")}} method. It's used almost everywhere in the language where a value of equivalent identity is expected.
## Same-value-zero equality
Similar to same-value equality, but +0 and -0 are considered equal.
Same-value-zero equality is not exposed as a JavaScript API, but can be implemented with custom code:
```js
function sameValueZero(x, y) {
if (typeof x === "number" && typeof y === "number") {
// x and y are equal (may be -0 and 0) or they are both NaN
return x === y || (x !== x && y !== y);
}
return x === y;
}
```
Same-value-zero only differs from strict equality by treating `NaN` as equivalent, and only differs from same-value equality by treating `-0` as equivalent to `0`. This makes it usually have the most sensible behavior during searching, especially when working with `NaN`. It's used by [`Array.prototype.includes()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes), [`TypedArray.prototype.includes()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/includes), as well as [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Set`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) methods for comparing key equality.
## Comparing equality methods
People often compare double equals and triple equals by saying one is an "enhanced" version of the other. For example, double equals could be said as an extended version of triple equals, because the former does everything that the latter does, but with type conversion on its operands β for example, `6 == "6"`. Alternatively, it can be claimed that double equals is the baseline, and triple equals is an enhanced version, because it requires the two operands to be the same type, so it adds an extra constraint.
However, this way of thinking implies that the equality comparisons form a one-dimensional "spectrum" where "totally strict" lies on one end and "totally loose" lies on the other. This model falls short with {{jsxref("Object.is")}}, because it isn't "looser" than double equals or "stricter" than triple equals, nor does it fit somewhere in between (i.e., being both stricter than double equals, but looser than triple equals). We can see from the sameness comparisons table below that this is due to the way that {{jsxref("Object.is")}} handles {{jsxref("NaN")}}. Notice that if `Object.is(NaN, NaN)` evaluated to `false`, we _could_ say that it fits on the loose/strict spectrum as an even stricter form of triple equals, one that distinguishes between `-0` and `+0`. The {{jsxref("NaN")}} handling means this is untrue, however. Unfortunately, {{jsxref("Object.is")}} has to be thought of in terms of its specific characteristics, rather than its looseness or strictness with regard to the equality operators.
| x | y | `==` | `===` | `Object.is` | `SameValueZero` |
| ------------------- | ------------------- | ---------- | ---------- | ----------- | --------------- |
| `undefined` | `undefined` | `β
true` | `β
true` | `β
true` | `β
true` |
| `null` | `null` | `β
true` | `β
true` | `β
true` | `β
true` |
| `true` | `true` | `β
true` | `β
true` | `β
true` | `β
true` |
| `false` | `false` | `β
true` | `β
true` | `β
true` | `β
true` |
| `'foo'` | `'foo'` | `β
true` | `β
true` | `β
true` | `β
true` |
| `0` | `0` | `β
true` | `β
true` | `β
true` | `β
true` |
| `+0` | `-0` | `β
true` | `β
true` | `β false` | `β
true` |
| `+0` | `0` | `β
true` | `β
true` | `β
true` | `β
true` |
| `-0` | `0` | `β
true` | `β
true` | `β false` | `β
true` |
| `0n` | `-0n` | `β
true` | `β
true` | `β
true` | `β
true` |
| `0` | `false` | `β
true` | `β false` | `β false` | `β false` |
| `""` | `false` | `β
true` | `β false` | `β false` | `β false` |
| `""` | `0` | `β
true` | `β false` | `β false` | `β false` |
| `'0'` | `0` | `β
true` | `β false` | `β false` | `β false` |
| `'17'` | `17` | `β
true` | `β false` | `β false` | `β false` |
| `[1, 2]` | `'1,2'` | `β
true` | `β false` | `β false` | `β false` |
| `new String('foo')` | `'foo'` | `β
true` | `β false` | `β false` | `β false` |
| `null` | `undefined` | `β
true` | `β false` | `β false` | `β false` |
| `null` | `false` | `β false` | `β false` | `β false` | `β false` |
| `undefined` | `false` | `β false` | `β false` | `β false` | `β false` |
| `{ foo: 'bar' }` | `{ foo: 'bar' }` | `β false` | `β false` | `β false` | `β false` |
| `new String('foo')` | `new String('foo')` | `β false` | `β false` | `β false` | `β false` |
| `0` | `null` | `β false` | `β false` | `β false` | `β false` |
| `0` | `NaN` | `β false` | `β false` | `β false` | `β false` |
| `'foo'` | `NaN` | `β false` | `β false` | `β false` | `β false` |
| `NaN` | `NaN` | `β false` | `β false` | `β
true` | `β
true` |
### When to use Object.is() versus triple equals
In general, the only time {{jsxref("Object.is")}}'s special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors, when it is desirable for your work to mirror some of the characteristics of {{jsxref("Object.defineProperty")}}. If your use case does not require this, it is suggested to avoid {{jsxref("Object.is")}} and use [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) instead. Even if your requirements involve having comparisons between two {{jsxref("NaN")}} values evaluate to `true`, generally it is easier to special-case the {{jsxref("NaN")}} checks (using the {{jsxref("isNaN")}} method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.
Here's a non-exhaustive list of built-in methods and operators that might cause a distinction between `-0` and `+0` to manifest itself in your code:
- [`-` (unary negation)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
- : Consider the following example:
```js
const stoppingForce = obj.mass * -obj.velocity;
```
If `obj.velocity` is `0` (or computes to `0`), a `-0` is introduced at that place and propagates out into `stoppingForce`.
- {{jsxref("Math.atan2")}}, {{jsxref("Math.ceil")}}, {{jsxref("Math.pow")}}, {{jsxref("Math.round")}}
- : In some cases, it's possible for a `-0` to be introduced into an expression as a return value of these methods even when no `-0` exists as one of the parameters. For example, using {{jsxref("Math.pow")}} to raise {{jsxref("Infinity", "-Infinity")}} to the power of any negative, odd exponent evaluates to `-0`. Refer to the documentation for the individual methods.
- {{jsxref("Math.floor")}}, {{jsxref("Math.max")}}, {{jsxref("Math.min")}}, {{jsxref("Math.sin")}}, {{jsxref("Math.sqrt")}}, {{jsxref("Math.tan")}}
- : It's possible to get a `-0` return value out of these methods in some cases where a `-0` exists as one of the parameters. E.g., `Math.min(-0, +0)` evaluates to `-0`. Refer to the documentation for the individual methods.
- [`~`](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT), [`<<`](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift), [`>>`](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)
- : Each of these operators uses the ToInt32 algorithm internally. Since there is only one representation for 0 in the internal 32-bit integer type, `-0` will not survive a round trip after an inverse operation. E.g., both `Object.is(~~(-0), -0)` and `Object.is(-0 << 2 >> 2, -0)` evaluate to `false`.
Relying on {{jsxref("Object.is")}} when the signedness of zeros is not taken into account can be hazardous. Of course, when the intent is to distinguish between `-0` and `+0`, it does exactly what's desired.
### Caveat: Object.is() and NaN
The {{jsxref("Object.is")}} specification treats all instances of {{jsxref("NaN")}} as the same object. However, since [typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) are available, we can have distinct floating point representations of `NaN` which don't behave identically in all contexts. For example:
```js
const f2b = (x) => new Uint8Array(new Float64Array([x]).buffer);
const b2f = (x) => new Float64Array(x.buffer)[0];
// Get a byte representation of NaN
const n = f2b(NaN);
// Change the first bit, which is the sign bit and doesn't matter for NaN
n[0] = 1;
const nan2 = b2f(n);
console.log(nan2); // NaN
console.log(Object.is(nan2, NaN)); // true
console.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127]
console.log(f2b(nan2)); // Uint8Array(8) [1, 0, 0, 0, 0, 0, 248, 127]
```
## See also
- [JS Comparison Table](https://dorey.github.io/JavaScript-Equality-Table/) by [dorey](https://github.com/dorey)
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/event_loop/the_javascript_runtime_environment_example.svg | <svg xmlns="http://www.w3.org/2000/svg" width="294.708" height="271.079" viewBox="0 0 77.975 71.723"><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#cfe7f5;stroke:none" d="M5550 11500H1200V3500h8700v8000z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5550 11500H1200V3500h8700v8000H5550" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1200 3500h8701v8001H1200z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#0ff;stroke:none" d="M5550 11500H1200V9700h8700v1800z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5550 11500H1200V9700h8700v1800H5550" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1200 9700h8701v1801H1200z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#09f;stroke:none" d="M2250 9700H1200V3500h2100v6200z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M2250 9700H1200V3500h2100v6200H2250" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1200 3500h2101v6201H1200z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#cfe7f5;stroke:none" d="M5549 11499H1199V3499h8700v8000z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5549 11499H1199V3499h8700v8000H5549" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1199 3499h8701v8001H1199z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"><g style="stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"><path style="fill:#0ff;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M5549 11499H1199v-1100h8700v1100z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M5549 11499H1199v-1100h8700v1100H5549" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M1199 10399h8701v1101H1199z" transform="translate(-10.576 -31.118) scale(.00893)"/></g></g><g style="visibility:visible;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"><g style="stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"><path style="fill:#09f;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M1999 10399h-800V3499h1600v6900z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M1999 10399h-800V3499h1600v6900h-800" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:#000;stroke-width:29.62461853;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M1199 3499h1601v6901H1199z" transform="translate(-10.576 -31.118) scale(.00893)"/></g></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M7500 7000h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M7500 7000h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M7200 6400h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M6499 6299h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M6499 6299h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M6199 5699h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M7099 4799h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M7099 4799h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M6799 4199h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M5099 5199h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5099 5199h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M4799 4599h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M8699 6499h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M8699 6499h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M8399 5899h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M7899 8299h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M7899 8299h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M7599 7699h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#7e0021;stroke:none" d="M5399 8099h-300v-600h600v600z" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5399 8099h-300v-600h600v600h-300" transform="translate(-10.576 -30.853) scale(.00893)"/><path style="fill:none;stroke:none" d="M5099 7499h601v601h-601z" transform="translate(-10.576 -30.853) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#ff950e;stroke:none" d="M1999 10299h-700v-800h1400v800z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M1999 10299h-700v-800h1400v800h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1299 9499h1401v801H1299z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#ff950e;stroke:none" d="M1999 9399h-700v-800h1400v800z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M1999 9399h-700v-800h1400v800h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1299 8599h1401v801H1299z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#ff950e;stroke:none" d="M1999 8499h-700v-800h1400v800z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M1999 8499h-700v-800h1400v800h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1299 7699h1401v801H1299z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#cc0;stroke:none" d="M1999 11399h-700v-900h1400v900z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M1999 11399h-700v-900h1400v900h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M1299 10499h1401v901H1299z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#cc0;stroke:none" d="M3599 11399h-700v-900h1400v900z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M3599 11399h-700v-900h1400v900h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M2899 10499h1401v901H2899z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#cc0;stroke:none" d="M5199 11399h-700v-900h1400v900z" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:gray" d="M5199 11399h-700v-900h1400v900h-700" transform="translate(-10.576 -31.118) scale(.00893)"/><path style="fill:none;stroke:none" d="M4499 10499h1401v901H4499z" transform="translate(-10.576 -31.118) scale(.00893)"/></g><g style="visibility:visible" class="com.sun.star.drawing.CustomShape"><path style="fill:#ff950e;stroke:none" d="M1999 8499h-700v-800h1400v800z" transform="translate(-10.594 -38.959) scale(.00893)"/><path style="fill:none;stroke:gray" d="M1999 8499h-700v-800h1400v800h-700" transform="translate(-10.594 -38.959) scale(.00893)"/><path style="fill:none;stroke:none" d="M1299 7699h1401v801H1299z" transform="translate(-10.594 -38.959) scale(.00893)"/></g><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="57.178" y="182.058" transform="translate(-56.533 -176.993)"><tspan x="57.178" y="182.058" style="font-size:5.29166651px;line-height:1.38999999;stroke-width:.26458332">Stack</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="120.167" y="182.1" transform="translate(-56.533 -176.993)"><tspan x="120.167" y="182.1" style="font-size:5.29166651px;line-height:1.38999999;stroke-width:.26458332">Heap</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="117.418" y="244.809" transform="translate(-56.533 -176.993)"><tspan x="117.418" y="244.809" style="font-size:5.29166651px;line-height:1.38999999;stroke-width:.26458332">Queue</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="58.622" y="211.613" transform="translate(-56.533 -176.993)"><tspan x="58.622" y="211.613" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Frame</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="58.639" y="219.453" transform="translate(-56.533 -176.993)"><tspan x="58.639" y="219.453" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Frame</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="58.639" y="227.491" transform="translate(-56.533 -176.993)"><tspan x="58.639" y="227.491" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Frame</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="58.639" y="235.529" transform="translate(-56.533 -176.993)"><tspan x="58.639" y="235.529" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Frame</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="58.037" y="244.378" transform="translate(-56.533 -176.993)"><tspan x="58.037" y="244.378" style="font-size:2.82222223px;line-height:1.38999999;stroke-width:.26458332">Message</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="72.327" y="244.378" transform="translate(-56.533 -176.993)"><tspan x="72.327" y="244.378" style="font-size:2.82222223px;line-height:1.38999999;stroke-width:.26458332">Message</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="86.617" y="244.378" transform="translate(-56.533 -176.993)"><tspan x="86.617" y="244.378" style="font-size:2.82222223px;line-height:1.38999999;stroke-width:.26458332">Message</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="86.327" y="185.938" transform="translate(-56.533 -176.993)"><tspan x="86.327" y="185.938" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="104.189" y="182.366" transform="translate(-56.533 -176.993)"><tspan x="104.189" y="182.366" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="98.831" y="195.763" transform="translate(-56.533 -176.993)"><tspan x="98.831" y="195.763" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="118.479" y="197.549" transform="translate(-56.533 -176.993)"><tspan x="118.479" y="197.549" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="107.771" y="202.023" transform="translate(-56.533 -176.993)"><tspan x="107.771" y="202.023" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="111.334" y="213.625" transform="translate(-56.533 -176.993)"><tspan x="111.334" y="213.625" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.17499995px;line-height:0%;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="89.006" y="211.839" transform="translate(-56.533 -176.993)"><tspan x="89.006" y="211.839" style="font-size:3.52777767px;line-height:1.38999999;stroke-width:.26458332">Object</tspan></text></svg> | 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/event_loop/index.md | ---
title: The event loop
slug: Web/JavaScript/Event_loop
page-type: guide
---
{{jsSidebar("Advanced")}}
JavaScript has a runtime model based on an **event loop**, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.
## Runtime concepts
The following sections explain a theoretical model. Modern JavaScript engines implement and heavily optimize the described semantics.
### Visual representation

### Stack
Function calls form a stack of _frames_.
```js
function foo(b) {
const a = 10;
return a + b + 11;
}
function bar(x) {
const y = 3;
return foo(x * y);
}
const baz = bar(7); // assigns 42 to baz
```
Order of operations:
1. When calling `bar`, a first frame is created containing references to `bar`'s arguments and local variables.
2. When `bar` calls `foo`, a second frame is created and pushed on top of the first one, containing references to `foo`'s arguments and local variables.
3. When `foo` returns, the top frame element is popped out of the stack (leaving only `bar`'s call frame).
4. When `bar` returns, the stack is empty.
Note that the arguments and local variables may continue to exist, as they are stored outside the stack β so they can be accessed by any [nested functions](/en-US/docs/Web/JavaScript/Guide/Functions#nested_functions_and_closures) long after their outer function has returned.
### Heap
Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory.
### Queue
A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function that gets called to handle the message.
At some point during the [event loop](#event_loop), the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As always, calling a function creates a new stack frame for that function's use.
The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one).
## Event loop
The **event loop** got its name because of how it's usually implemented, which usually resembles:
```js
while (queue.waitForMessage()) {
queue.processNextMessage();
}
```
`queue.waitForMessage()` waits synchronously for a message to arrive (if one is not already available and waiting to be handled).
### "Run-to-completion"
Each message is processed completely before any other message is processed.
This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.
### Adding messages
In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message β likewise with any other event.
The first two arguments to the function [`setTimeout`](/en-US/docs/Web/API/setTimeout) are a message to add to the queue and a time value (optional; defaults to `0`). The _time value_ represents the (minimum) delay after which the message will be pushed into the queue. If there is no other message in the queue, and the stack is empty, the message is processed right after the delay. However, if there are messages, the `setTimeout` message will have to wait for other messages to be processed. For this reason, the second argument indicates a _minimum_ time β not a _guaranteed_ time.
Here is an example that demonstrates this concept (`setTimeout` does not run immediately after its timer expires):
```js
const seconds = new Date().getTime() / 1000;
setTimeout(() => {
// prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
console.log(`Ran after ${new Date().getTime() / 1000 - seconds} seconds`);
}, 500);
while (true) {
if (new Date().getTime() / 1000 - seconds >= 2) {
console.log("Good, looped for 2 seconds");
break;
}
}
```
### Zero delays
Zero delay doesn't mean the call back will fire-off after zero milliseconds. Calling [`setTimeout`](/en-US/docs/Web/API/setTimeout) with a delay of `0` (zero) milliseconds doesn't execute the callback function after the given interval.
The execution depends on the number of waiting tasks in the queue. In the example below, the message `"this is just a message"` will be written to the console before the message in the callback gets processed, because the delay is the _minimum_ time required for the runtime to process the request (not a _guaranteed_ time).
The `setTimeout` needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your `setTimeout`.
```js
(() => {
console.log("this is the start");
setTimeout(() => {
console.log("Callback 1: this is a msg from call back");
}); // has a default time value of 0
console.log("this is just a message");
setTimeout(() => {
console.log("Callback 2: this is a msg from call back");
}, 0);
console.log("this is the end");
})();
// "this is the start"
// "this is just a message"
// "this is the end"
// "Callback 1: this is a msg from call back"
// "Callback 2: this is a msg from call back"
```
### Several runtimes communicating together
A web worker or a cross-origin `iframe` has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the [`postMessage`](/en-US/docs/Web/API/Window/postMessage) method. This method adds a message to the other runtime if the latter listens to `message` events.
## Never blocking
A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an [IndexedDB](/en-US/docs/Web/API/IndexedDB_API) query to return or a [`fetch()`](/en-US/docs/Web/API/fetch) request to return, it can still process other things like user input.
Legacy exceptions exist like `alert` or synchronous XHR, but it is considered good practice to avoid them. Beware: [exceptions to the exception do exist](https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311) (but are usually implementation bugs, rather than anything else).
## See also
- [Event loops](https://html.spec.whatwg.org/multipage/webappapis.html#event-loops) in the HTML standard
- [The Node.js Event Loop, Timers, and `process.nextTick()`](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#what-is-the-event-loop) in the Node.js docs
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/data_structures/index.md | ---
title: JavaScript data types and data structures
slug: Web/JavaScript/Data_structures
page-type: guide
---
{{jsSidebar("More")}}
Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have. These can be used to build other data structures.
The [language overview](/en-US/docs/Web/JavaScript/Language_overview) offers a similar summary of the common data types, but with more comparisons to other languages.
## Dynamic and weak typing
JavaScript is a [dynamic](https://en.wikipedia.org/wiki/Dynamic_programming_language) language with [dynamic types](https://en.wikipedia.org/wiki/Type_system#DYNAMIC). Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types:
```js
let foo = 42; // foo is now a number
foo = "bar"; // foo is now a string
foo = true; // foo is now a boolean
```
JavaScript is also a [weakly typed](https://en.wikipedia.org/wiki/Strong_and_weak_typing) language, which means it allows implicit type conversion when an operation involves mismatched types, instead of throwing type errors.
```js
const foo = 42; // foo is a number
const result = foo + "1"; // JavaScript coerces foo to a string, so it can be concatenated with the other operand
console.log(result); // 421
```
Implicit coercions are very convenient, but can create subtle bugs when conversions happen where they are not expected, or where they are expected to happen in the other direction (for example, string to number instead of number to string). For [symbols](#symbol_type) and [BigInts](#bigint_type), JavaScript has intentionally disallowed certain implicit type conversions.
## Primitive values
All types except [Object](#objects) define [immutable](/en-US/docs/Glossary/Immutable) values represented directly at the lowest level of the language. We refer to values of these types as _primitive values_.
All primitive types, except [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), can be tested by the [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operator. `typeof null` returns `"object"`, so one has to use `=== null` to test for `null`.
All primitive types, except [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), have their corresponding object wrapper types, which provide useful methods for working with the primitive values. For example, the [`Number`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) object provides methods like [`toExponential()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential). When a property is accessed on a primitive value, JavaScript automatically wraps the value into the corresponding wrapper object and accesses the property on the object instead. However, accessing a property on `null` or `undefined` throws a `TypeError` exception, which necessitates the introduction of the [optional chaining](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) operator.
| Type | `typeof` return value | Object wrapper |
| ---------------------------- | --------------------- | --------------------- |
| [Null](#null_type) | `"object"` | N/A |
| [Undefined](#undefined_type) | `"undefined"` | N/A |
| [Boolean](#boolean_type) | `"boolean"` | {{jsxref("Boolean")}} |
| [Number](#number_type) | `"number"` | {{jsxref("Number")}} |
| [BigInt](#bigint_type) | `"bigint"` | {{jsxref("BigInt")}} |
| [String](#string_type) | `"string"` | {{jsxref("String")}} |
| [Symbol](#symbol_type) | `"symbol"` | {{jsxref("Symbol")}} |
The object wrapper classes' reference pages contain more information about the methods and properties available for each type, as well as detailed descriptions for the semantics of the primitive types themselves.
### Null type
The Null type is inhabited by exactly one value: [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
### Undefined type
The Undefined type is inhabited by exactly one value: [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).
Conceptually, `undefined` indicates the absence of a _value_, while `null` indicates the absence of an _object_ (which could also make up an excuse for [`typeof null === "object"`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null)). The language usually defaults to `undefined` when something is devoid of a value:
- A [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement with no value (`return;`) implicitly returns `undefined`.
- Accessing a nonexistent [object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) property (`obj.iDontExist`) returns `undefined`.
- A variable declaration without initialization (`let x;`) implicitly initializes the variable to `undefined`.
- Many methods, such as {{jsxref("Array.prototype.find()")}} and {{jsxref("Map.prototype.get()")}}, return `undefined` when no element is found.
`null` is used much less often in the core language. The most important place is the end of the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) β subsequently, methods that interact with prototypes, such as {{jsxref("Object.getPrototypeOf()")}}, {{jsxref("Object.create()")}}, etc., accept or return `null` instead of `undefined`.
`null` is a [keyword](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords), but `undefined` is a normal [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) that happens to be a global property. In practice, the difference is minor, since `undefined` should not be redefined or shadowed.
### Boolean type
The {{jsxref("Boolean")}} type represents a logical entity and is inhabited by two values: `true` and `false`.
Boolean values are usually used for conditional operations, including [ternary operators](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator), [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else), [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while), etc.
### Number type
The {{jsxref("Number")}} type is a [double-precision 64-bit binary format IEEE 754 value](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding). It is capable of storing positive floating-point numbers between 2<sup>-1074</sup> ({{jsxref("Number.MIN_VALUE")}}) and 2<sup>1024</sup> ({{jsxref("Number.MAX_VALUE")}}) as well as negative floating-point numbers between -2<sup>-1074</sup> and -2<sup>1024</sup>, but it can only safely store integers in the range -(2<sup>53</sup> β 1) ({{jsxref("Number.MIN_SAFE_INTEGER")}}) to 2<sup>53</sup> β 1 ({{jsxref("Number.MAX_SAFE_INTEGER")}}). Outside this range, JavaScript can no longer safely represent integers; they will instead be represented by a double-precision floating point approximation. You can check if a number is within the range of safe integers using {{jsxref("Number.isSafeInteger()")}}.
Values outside the range Β±(2<sup>-1074</sup> to 2<sup>1024</sup>) are automatically converted:
- Positive values greater than {{jsxref("Number.MAX_VALUE")}} are converted to `+Infinity`.
- Positive values smaller than {{jsxref("Number.MIN_VALUE")}} are converted to `+0`.
- Negative values smaller than -{{jsxref("Number.MAX_VALUE")}} are converted to `-Infinity`.
- Negative values greater than -{{jsxref("Number.MIN_VALUE")}} are converted to `-0`.
`+Infinity` and `-Infinity` behave similarly to mathematical infinity, but with some slight differences; see {{jsxref("Number.POSITIVE_INFINITY")}} and {{jsxref("Number.NEGATIVE_INFINITY")}} for details.
The Number type has only one value with multiple representations: `0` is represented as both `-0` and `+0` (where `0` is an alias for `+0`). In practice, there is almost no difference between the different representations; for example, `+0 === -0` is `true`. However, you are able to notice this when you divide by zero:
```js
console.log(42 / +0); // Infinity
console.log(42 / -0); // -Infinity
```
{{jsxref("NaN")}} ("**N**ot **a** **N**umber") is a special kind of number value that's typically encountered when the result of an arithmetic operation cannot be expressed as a number. It is also the only value in JavaScript that is not equal to itself.
Although a number is conceptually a "mathematical value" and is always implicitly floating-point-encoded, JavaScript provides [bitwise operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators). When applying bitwise operators, the number is first converted to a 32-bit integer.
> **Note:** Although bitwise operators _can_ be used to represent several Boolean values within a single number using [bit masking](https://en.wikipedia.org/wiki/Mask_%28computing%29), this is usually considered a bad practice. JavaScript offers other means to represent a set of Booleans (like an array of Booleans, or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain.
It may be necessary to use such techniques in very constrained environments, like when trying to cope with the limitations of local storage, or in extreme cases (such as when each bit over the network counts). This technique should only be considered when it is the last measure that can be taken to optimize size.
### BigInt type
The {{jsxref("BigInt")}} type is a numeric primitive in JavaScript that can represent integers with arbitrary magnitude. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit ({{jsxref("Number.MAX_SAFE_INTEGER")}}) for Numbers.
A BigInt is created by appending `n` to the end of an integer or by calling the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function.
This example demonstrates where incrementing the {{jsxref("Number.MAX_SAFE_INTEGER")}} returns the expected result:
```js
// BigInt
const x = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n
x + 1n === x + 2n; // false because 9007199254740992n and 9007199254740993n are unequal
// Number
Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true because both are 9007199254740992
```
You can use most operators to work with BigInts, including `+`, `*`, `-`, `**`, and `%` β the only forbidden one is [`>>>`](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift). A BigInt is not [strictly equal](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) to a Number with the same mathematical value, but it is [loosely](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) so.
BigInt values are neither always more precise nor always less precise than numbers, since BigInts cannot represent fractional numbers, but can represent big integers more accurately. Neither type entails the other, and they are not mutually substitutable. A {{jsxref("TypeError")}} is thrown if BigInt values are mixed with regular numbers in arithmetic expressions, or if they are [implicitly converted](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to each other.
### String type
The {{jsxref("String")}} type represents textual data and is encoded as a sequence of 16-bit unsigned integer values representing [UTF-16 code units](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters). Each element in the string occupies a position in the string. The first element is at index `0`, the next at index `1`, and so on. The [length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) of a string is the number of UTF-16 code units in it, which may not correspond to the actual number of Unicode characters; see the [`String`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) reference page for more details.
JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. String methods create new strings based on the content of the current string β for example:
- A substring of the original using [`substring()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring).
- A concatenation of two strings using the concatenation operator (`+`) or [`concat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat).
#### Beware of "stringly-typing" your code!
It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:
- It is easy to build complex strings with concatenation.
- Strings are easy to debug (what you see printed is always what is in the string).
- Strings are the common denominator of a lot of APIs ([input fields](/en-US/docs/Web/API/HTMLInputElement), [local storage](/en-US/docs/Web/API/Web_Storage_API) values, [`fetch()`](/en-US/docs/Web/API/fetch) responses when using {{domxref("Response.text()")}}, etc.) and it can be tempting to only work with strings.
With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.
Use strings for textual data. When representing complex data, _parse_ strings, and use the appropriate abstraction.
### Symbol type
A {{jsxref("Symbol")}} is a **unique** and **immutable** primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms". The purpose of symbols is to create unique property keys that are guaranteed not to clash with keys from other code.
## Objects
In computer science, an object is a value in memory which is possibly referenced by an [identifier](/en-US/docs/Glossary/Identifier). In JavaScript, objects are the only [mutable](/en-US/docs/Glossary/Mutable) values. [Functions](/en-US/docs/Web/JavaScript/Reference/Functions) are, in fact, also objects with the additional capability of being _callable_.
### Properties
In JavaScript, objects can be seen as a collection of properties. With the [object literal syntax](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#object_literals), a limited set of properties are initialized; then properties can be added and removed. Object properties are equivalent to key-value pairs. Property keys are either [strings](#string_type) or [symbols](#symbol_type). Property values can be values of any type, including other objects, which enables building complex data structures.
There are two types of object properties: The [_data_ property](#data_property) and the [_accessor_ property](#accessor_property). Each property has corresponding _attributes_. Each attribute is accessed internally by the JavaScript engine, but you can set them through {{jsxref("Object.defineProperty()")}}, or read them through {{jsxref("Object.getOwnPropertyDescriptor()")}}. You can read more about the various nuances on the {{jsxref("Object.defineProperty()")}} page.
#### Data property
Data properties associate a key with a value. It can be described by the following attributes:
- `value`
- : The value retrieved by a get access of the property. Can be any JavaScript value.
- `writable`
- : A boolean value indicating if the property can be changed with an assignment.
- `enumerable`
- : A boolean value indicating if the property can be enumerated by a [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop. See also [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) for how enumerability interacts with other functions and syntaxes.
- `configurable`
- : A boolean value indicating if the property can be deleted, can be changed to an accessor property, and can have its attributes changed.
#### Accessor property
Associates a key with one of two accessor functions (`get` and `set`) to retrieve or store a value.
> **Note:** It's important to recognize it's accessor _property_ β not accessor _method_. We can give a JavaScript object class-like accessors by using a function as a value β but that doesn't make the object a class.
An accessor property has the following attributes:
- `get`
- : A function called with an empty argument list to retrieve the property value whenever a get access to the value is performed. See also [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get). May be `undefined`.
- `set`
- : A function called with an argument that contains the assigned value. Executed whenever a specified property is attempted to be changed. See also [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set). May be `undefined`.
- `enumerable`
- : A boolean value indicating if the property can be enumerated by a [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop. See also [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) for how enumerability interacts with other functions and syntaxes.
- `configurable`
- : A boolean value indicating if the property can be deleted, can be changed to a data property, and can have its attributes changed.
The [prototype](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of an object points to another object or to `null` β it's conceptually a hidden property of the object, commonly represented as `[[Prototype]]`. Properties of the object's `[[Prototype]]` can also be accessed on the object itself.
Objects are ad-hoc key-value pairs, so they are often used as maps. However, there can be ergonomics, security, and performance issues. Use a {{jsxref("Map")}} for storing arbitrary data instead. The [`Map` reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps) contains a more detailed discussion of the pros & cons between plain objects and maps for storing key-value associations.
### Dates
When representing dates, the best choice is to use the built-in [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) utility in JavaScript.
### Indexed collections: Arrays and typed Arrays
[Arrays](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) are regular objects for which there is a particular relationship between integer-keyed properties and the `length` property.
Additionally, arrays inherit from `Array.prototype`, which provides a handful of convenient methods to manipulate arrays. For example, [`indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) searches a value in the array and [`push()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) appends an element to the array. This makes Arrays a perfect candidate to represent ordered lists.
[Typed Arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) present an array-like view of an underlying binary data buffer, and offer many methods that have similar semantics to the array counterparts. "Typed array" is an umbrella term for a range of data structures, including `Int8Array`, `Float32Array`, etc. Check the [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) page for more information. Typed arrays are often used in conjunction with {{jsxref("ArrayBuffer")}} and {{jsxref("DataView")}}.
### Keyed collections: Maps, Sets, WeakMaps, WeakSets
These data structures take object references as keys. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a collection of unique values, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} represent a collection of key-value associations.
You could implement `Map`s and `Set`s yourself. However, since objects cannot be compared (in the sense of `<` "less than", for instance), neither does the engine expose its hash function for objects, look-up performance would necessarily be linear. Native implementations of them (including `WeakMap`s) can have look-up performance that is approximately logarithmic to constant time.
Usually, to bind data to a DOM node, one could set properties directly on the object, or use `data-*` attributes. This has the downside that the data is available to any script running in the same context. `Map`s and `WeakMap`s make it easy to _privately_ bind data to an object.
`WeakMap` and `WeakSet` only allow garbage-collectable values as keys, which are either objects or [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry), and the keys may be collected even when they remain in the collection. They are specifically used for [memory usage optimization](/en-US/docs/Web/JavaScript/Memory_management#data_structures_aiding_memory_management).
### Structured data: JSON
JSON (**J**ava**S**cript **O**bject **N**otation) is a lightweight data-interchange format, derived from JavaScript, but used by many programming languages. JSON builds universal data structures that can be transferred between different environments and even across languages. See {{jsxref("JSON")}} for more details.
### More objects in the standard library
JavaScript has a standard library of built-in objects. Read the [reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects) to find out more about the built-in objects.
## Type coercion
As mentioned above, JavaScript is a [weakly typed](#dynamic_and_weak_typing) language. This means that you can often use a value of one type where another type is expected, and the language will convert it to the right type for you. To do so, JavaScript defines a handful of coercion rules.
### Primitive coercion
The [primitive coercion](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-toprimitive) process is used where a primitive value is expected, but there's no strong preference for what the actual type should be. This is usually when a [string](#string_type), a [number](#number_type), or a [BigInt](#bigint_type) are equally acceptable. For example:
- The [`Date()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) constructor, when it receives one argument that's not a `Date` instance β strings represent date strings, while numbers represent timestamps.
- The [`+`](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) operator β if one operand is a string, string concatenation is performed; otherwise, numeric addition is performed.
- The [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) operator β if one operand is a primitive while the other is an object, the object is converted to a primitive value with no preferred type.
This operation does not do any conversion if the value is already a primitive. Objects are converted to primitives by calling its [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"default"` as hint), `valueOf()`, and `toString()` methods, in that order. Note that primitive conversion calls `valueOf()` before `toString()`, which is similar to the behavior of [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) but different from [string coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion).
The `[@@toPrimitive]()` method, if present, must return a primitive β returning an object results in a {{jsxref("TypeError")}}. For `valueOf()` and `toString()`, if one returns an object, the return value is ignored and the other's return value is used instead; if neither is present, or neither returns a primitive, a {{jsxref("TypeError")}} is thrown. For example, in the following code:
```js
console.log({} + []); // "[object Object]"
```
Neither `{}` nor `[]` have a `[@@toPrimitive]()` method. Both `{}` and `[]` inherit `valueOf()` from {{jsxref("Object.prototype.valueOf")}}, which returns the object itself. Since the return value is an object, it is ignored. Therefore, `toString()` is called instead. [`{}.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) returns `"[object Object]"`, while [`[].toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) returns `""`, so the result is their concatenation: `"[object Object]"`.
The `[@@toPrimitive]()` method always takes precedence when doing conversion to any primitive type. Primitive conversion generally behaves like number conversion, because `valueOf()` is called in priority; however, objects with custom `[@@toPrimitive]()` methods can choose to return any primitive. {{jsxref("Date")}} and {{jsxref("Symbol")}} objects are the only built-in objects that override the `[@@toPrimitive]()` method. [`Date.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) treats the `"default"` hint as if it's `"string"`, while [`Symbol.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) ignores the hint and always returns a symbol.
### Numeric coercion
There are two numeric types: [Number](#number_type) and [BigInt](#bigint_type). Sometimes the language specifically expects a number or a BigInt (such as {{jsxref("Array.prototype.slice()")}}, where the index must be a number); other times, it may tolerate either and perform different operations depending on the operand's type. For strict coercion processes that do not allow implicit conversion from the other type, see [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) and [BigInt coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#bigint_coercion).
Numeric coercion is nearly the same as [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), except that BigInts are returned as-is instead of causing a {{jsxref("TypeError")}}. Numeric coercion is used by all arithmetic operators, since they are overloaded for both numbers and BigInts. The only exception is [unary plus](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus), which always does number coercion.
### Other coercions
All data types, except Null, Undefined, and Symbol, have their respective coercion process. See [string coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), [boolean coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion), and [object coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_coercion) for more details.
As you may have noticed, there are three distinct paths through which objects may be converted to primitives:
- [Primitive coercion](#primitive_coercion): `[@@toPrimitive]("default")` β `valueOf()` β `toString()`
- [Numeric coercion](#numeric_coercion), [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), [BigInt coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#bigint_coercion): `[@@toPrimitive]("number")` β `valueOf()` β `toString()`
- [String coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion): `[@@toPrimitive]("string")` β `toString()` β `valueOf()`
In all cases, `[@@toPrimitive]()`, if present, must be callable and return a primitive, while `valueOf` or `toString` will be ignored if they are not callable or return an object. At the end of the process, if successful, the result is guaranteed to be a primitive. The resulting primitive is then subject to further coercions depending on the context.
## See also
- [JavaScript Data Structures and Algorithms](https://github.com/trekhleb/javascript-algorithms) by Oleksii Trekhleb
- [Computer Science in JavaScript](https://github.com/humanwhocodes/computer-science-in-javascript) by Nicholas C. Zakas
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/closures/index.md | ---
title: Closures
slug: Web/JavaScript/Closures
page-type: guide
---
{{jsSidebar("Intermediate")}}
A **closure** is the combination of a function bundled together (enclosed) with references to its surrounding state (the **lexical environment**). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
## Lexical scoping
Consider the following example code:
```js
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, that forms the closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
init();
```
`init()` creates a local variable called `name` and a function called `displayName()`. The `displayName()` function is an inner function that is defined inside `init()` and is available only within the body of the `init()` function. Note that the `displayName()` function has no local variables of its own. However, since inner functions have access to the variables of outer functions, `displayName()` can access the variable `name` declared in the parent function, `init()`.
Run the code using [this JSFiddle link](https://jsfiddle.net/3dxck52m/) and notice that the `console.log()` statement within the `displayName()` function successfully displays the value of the `name` variable, which is declared in its parent function. This is an example of _lexical scoping_, which describes how a parser resolves variable names when functions are nested. The word _lexical_ refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.
In this particular example, the scope is called a _function scope_, because the variable is accessible and only accessible within the function body where it's declared.
### Scoping with let and const
Traditionally (before ES6), JavaScript only had two kinds of scopes: _function scope_ and _global scope_. Variables declared with `var` are either function-scoped or global-scoped, depending on whether they are declared within a function or outside a function. This can be tricky, because blocks with curly braces do not create scopes:
```js
if (Math.random() > 0.5) {
var x = 1;
} else {
var x = 2;
}
console.log(x);
```
For people from other languages (e.g. C, Java) where blocks create scopes, the above code should throw an error on the `console.log` line, because we are outside the scope of `x` in either block. However, because blocks don't create scopes for `var`, the `var` statements here actually create a global variable. There is also [a practical example](#creating_closures_in_loops_a_common_mistake) introduced below that illustrates how this can cause actual bugs when combined with closures.
In ES6, JavaScript introduced the `let` and `const` declarations, which, among other things like [temporal dead zones](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz), allow you to create block-scoped variables.
```js
if (Math.random() > 0.5) {
const x = 1;
} else {
const x = 2;
}
console.log(x); // ReferenceError: x is not defined
```
In essence, blocks are finally treated as scopes in ES6, but only if you declare variables with `let` or `const`. In addition, ES6 introduced [modules](/en-US/docs/Web/JavaScript/Guide/Modules), which introduced another kind of scope. Closures are able to capture variables in all these scopes, which we will introduce later.
## Closure
Consider the following code example:
```js
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();
```
Running this code has exactly the same effect as the previous example of the `init()` function above. What's different (and interesting) is that the `displayName()` inner function is returned from the outer function _before being executed_.
At first glance, it might seem unintuitive that this code still works. In some programming languages, the local variables within a function exist for just the duration of that function's execution. Once `makeFunc()` finishes executing, you might expect that the `name` variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.
The reason is that functions in JavaScript form closures. A _closure_ is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, `myFunc` is a reference to the instance of the function `displayName` that is created when `makeFunc` is run. The instance of `displayName` maintains a reference to its lexical environment, within which the variable `name` exists. For this reason, when `myFunc` is invoked, the variable `name` remains available for use, and "Mozilla" is passed to `console.log`.
Here's a slightly more interesting exampleβa `makeAdder` function:
```js
function makeAdder(x) {
return function (y) {
return x + y;
};
}
const add5 = makeAdder(5);
const add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
```
In this example, we have defined a function `makeAdder(x)`, that takes a single argument `x`, and returns a new function. The function it returns takes a single argument `y`, and returns the sum of `x` and `y`.
In essence, `makeAdder` is a function factory. It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functionsβone that adds five to its argument, and one that adds 10.
`add5` and `add10` both form closures. They share the same function body definition, but store different lexical environments. In `add5`'s lexical environment, `x` is 5, while in the lexical environment for `add10`, `x` is 10.
## Practical closures
Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.
Situations where you might want to do this are particularly common on the web. Much of the code written in front-end JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event).
For instance, suppose we want to add buttons to a page to adjust the text size. One way of doing this is to specify the font-size of the `body` element (in pixels), and then set the size of the other elements on the page (such as headers) using the relative `em` unit:
```css
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
```
Such interactive text size buttons can change the `font-size` property of the `body` element, and the adjustments are picked up by other elements on the page thanks to the relative units.
Here's the JavaScript:
```js
function makeSizer(size) {
return function () {
document.body.style.fontSize = `${size}px`;
};
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
```
`size12`, `size14`, and `size16` are now functions that resize the body text to 12, 14, and 16 pixels, respectively. You can attach them to buttons as demonstrated in the following code example.
```js
document.getElementById("size-12").onclick = size12;
document.getElementById("size-14").onclick = size14;
document.getElementById("size-16").onclick = size16;
```
```html
<button id="size-12">12</button>
<button id="size-14">14</button>
<button id="size-16">16</button>
```
Run the code using [JSFiddle](https://jsfiddle.net/hotae160/).
## Emulating private methods with closures
Languages such as Java allow you to declare methods as private, meaning that they can be called only by other methods in the same class.
JavaScript, prior to [classes](/en-US/docs/Web/JavaScript/Reference/Classes), didn't have a native way of declaring [private methods](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties#private_methods), but it was possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code. They also provide a powerful way of managing your global namespace.
The following code illustrates how to use closures to define public functions that can access private functions and variables. Note that these closures follow the [Module Design Pattern](https://www.google.com/search?q=javascript+module+pattern).
```js
const counter = (function () {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment() {
changeBy(1);
},
decrement() {
changeBy(-1);
},
value() {
return privateCounter;
},
};
})();
console.log(counter.value()); // 0.
counter.increment();
counter.increment();
console.log(counter.value()); // 2.
counter.decrement();
console.log(counter.value()); // 1.
```
In previous examples, each closure had its own lexical environment. Here though, there is a single lexical environment that is shared by the three functions: `counter.increment`, `counter.decrement`, and `counter.value`.
The shared lexical environment is created in the body of an anonymous function, _which is executed as soon as it has been defined_ (also known as an [IIFE](/en-US/docs/Glossary/IIFE)). The lexical environment contains two private items: a variable called `privateCounter`, and a function called `changeBy`. You can't access either of these private members from outside the anonymous function. Instead, you can access them using the three public functions that are returned from the anonymous wrapper.
Those three public functions form closures that share the same lexical environment. Thanks to JavaScript's lexical scoping, they each have access to the `privateCounter` variable and the `changeBy` function.
```js
const makeCounter = function () {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment() {
changeBy(1);
},
decrement() {
changeBy(-1);
},
value() {
return privateCounter;
},
};
};
const counter1 = makeCounter();
const counter2 = makeCounter();
console.log(counter1.value()); // 0.
counter1.increment();
counter1.increment();
console.log(counter1.value()); // 2.
counter1.decrement();
console.log(counter1.value()); // 1.
console.log(counter2.value()); // 0.
```
Notice how the two counters maintain their independence from one another. Each closure references a different version of the `privateCounter` variable through its own closure. Each time one of the counters is called, its lexical environment changes by changing the value of this variable. Changes to the variable value in one closure don't affect the value in the other closure.
> **Note:** Using closures in this way provides benefits that are normally associated with object-oriented programming. In particular, _data hiding_ and _encapsulation_.
## Closure scope chain
Every closure has three scopes:
- Local scope (Own scope)
- Enclosing scope (can be block, function, or module scope)
- Global scope
A common mistake is not realizing that in the case where the outer function is itself a nested function, access to the outer function's scope includes the enclosing scope of the outer functionβeffectively creating a chain of function scopes. To demonstrate, consider the following example code.
```js
// global scope
const e = 10;
function sum(a) {
return function (b) {
return function (c) {
// outer functions scope
return function (d) {
// local scope
return a + b + c + d + e;
};
};
};
}
console.log(sum(1)(2)(3)(4)); // 20
```
You can also write without anonymous functions:
```js
// global scope
const e = 10;
function sum(a) {
return function sum2(b) {
return function sum3(c) {
// outer functions scope
return function sum4(d) {
// local scope
return a + b + c + d + e;
};
};
};
}
const sum2 = sum(1);
const sum3 = sum2(2);
const sum4 = sum3(3);
const result = sum4(4);
console.log(result); // 20
```
In the example above, there's a series of nested functions, all of which have access to the outer functions' scope. In this context, we can say that closures have access to _all_ outer function scopes.
Closures can capture variables in block scopes and module scopes as well. For example, the following creates a closure over the block-scoped variable `y`:
```js
function outer() {
let getY;
{
const y = 6;
getY = () => y;
}
console.log(typeof y); // undefined
console.log(getY()); // 6
}
outer();
```
Closures over modules can be more interesting.
```js
// myModule.js
let x = 5;
export const getX = () => x;
export const setX = (val) => {
x = val;
};
```
Here, the module exports a pair of getter-setter functions, which close over the module-scoped variable `x`. Even when `x` is not directly accessible from other modules, it can be read and written with the functions.
```js
import { getX, setX } from "./myModule.js";
console.log(getX()); // 5
setX(6);
console.log(getX()); // 6
```
Closures can close over imported values as well, which are regarded as _live {{Glossary("binding", "bindings")}}_, because when the original value changes, the imported one changes accordingly.
```js
// myModule.js
export let x = 1;
export const setX = (val) => {
x = val;
};
```
```js
// closureCreator.js
import { x } from "./myModule.js";
export const getX = () => x; // Close over an imported live binding
```
```js
import { getX } from "./closureCreator.js";
import { setX } from "./myModule.js";
console.log(getX()); // 1
setX(2);
console.log(getX()); // 2
```
## Creating closures in loops: A common mistake
Prior to the introduction of the [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) keyword, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code.
```html
<p id="help">Helpful notes will appear here</p>
<p>Email: <input type="text" id="email" name="email" /></p>
<p>Name: <input type="text" id="name" name="name" /></p>
<p>Age: <input type="text" id="age" name="age" /></p>
```
```js
function showHelp(help) {
document.getElementById("help").textContent = help;
}
function setupHelp() {
var helpText = [
{ id: "email", help: "Your email address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
for (var i = 0; i < helpText.length; i++) {
// Culprit is the use of `var` on this line
var item = helpText[i];
document.getElementById(item.id).onfocus = function () {
showHelp(item.help);
};
}
}
setupHelp();
```
Try running the code in [JSFiddle](https://jsfiddle.net/v7gjv/8164/).
The `helpText` array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an `onfocus` event to each one that shows the associated help method.
If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed.
The reason for this is that the functions assigned to `onfocus` form closures; they consist of the function definition and the captured environment from the `setupHelp` function's scope. Three closures have been created by the loop, but each one shares the same single lexical environment, which has a variable with changing values (`item`). This is because the variable `item` is declared with `var` and thus has function scope due to hoisting. The value of `item.help` is determined when the `onfocus` callbacks are executed. Because the loop has already run its course by that time, the `item` variable object (shared by all three closures) has been left pointing to the last entry in the `helpText` list.
One solution in this case is to use more closures: in particular, to use a function factory as described earlier:
```js
function showHelp(help) {
document.getElementById("help").textContent = help;
}
function makeHelpCallback(help) {
return function () {
showHelp(help);
};
}
function setupHelp() {
var helpText = [
{ id: "email", help: "Your email address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
}
}
setupHelp();
```
Run the code using [this JSFiddle link](https://jsfiddle.net/v7gjv/9573/).
This works as expected. Rather than the callbacks all sharing a single lexical environment, the `makeHelpCallback` function creates _a new lexical environment_ for each callback, in which `help` refers to the corresponding string from the `helpText` array.
One other way to write the above using anonymous closures is:
```js
function showHelp(help) {
document.getElementById("help").textContent = help;
}
function setupHelp() {
var helpText = [
{ id: "email", help: "Your email address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
for (var i = 0; i < helpText.length; i++) {
(function () {
var item = helpText[i];
document.getElementById(item.id).onfocus = function () {
showHelp(item.help);
};
})(); // Immediate event listener attachment with the current value of item (preserved until iteration).
}
}
setupHelp();
```
If you don't want to use more closures, you can use the [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) keyword:
```js
function showHelp(help) {
document.getElementById("help").textContent = help;
}
function setupHelp() {
const helpText = [
{ id: "email", help: "Your email address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
for (let i = 0; i < helpText.length; i++) {
const item = helpText[i];
document.getElementById(item.id).onfocus = () => {
showHelp(item.help);
};
}
}
setupHelp();
```
This example uses `const` instead of `var`, so every closure binds the block-scoped variable, meaning that no additional closures are required.
Another alternative could be to use `forEach()` to iterate over the `helpText` array and attach a listener to each [`<input>`](/en-US/docs/Web/HTML/Element/input), as shown:
```js
function showHelp(help) {
document.getElementById("help").textContent = help;
}
function setupHelp() {
var helpText = [
{ id: "email", help: "Your email address" },
{ id: "name", help: "Your full name" },
{ id: "age", help: "Your age (you must be over 16)" },
];
helpText.forEach(function (text) {
document.getElementById(text.id).onfocus = function () {
showHelp(text.help);
};
});
}
setupHelp();
```
## Performance considerations
As mentioned previously, each function instance manages its own scope and closure. Therefore, it is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.
For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).
Consider the following case:
```js
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
this.getName = function () {
return this.name;
};
this.getMessage = function () {
return this.message;
};
}
```
Because the previous code does not take advantage of the benefits of using closures in this particular instance, we could instead rewrite it to avoid using closures as follows:
```js
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype = {
getName() {
return this.name;
},
getMessage() {
return this.message;
},
};
```
However, redefining the prototype is not recommended. The following example instead appends to the existing prototype:
```js
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype.getName = function () {
return this.name;
};
MyObject.prototype.getMessage = function () {
return this.message;
};
```
In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) for more.
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/javascript_technologies_overview/index.md | ---
title: JavaScript technologies overview
slug: Web/JavaScript/JavaScript_technologies_overview
page-type: guide
---
{{jsSidebar("Introductory")}}
Whereas [HTML](/en-US/docs/Web/HTML) defines a webpage's structure and content and [CSS](/en-US/docs/Web/CSS) sets the formatting and appearance, [JavaScript](/en-US/docs/Web/JavaScript) adds interactivity to a webpage and creates rich web applications.
However, the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the [Web APIs](/en-US/docs/Web/API), including the DOM (Document Object Model).
## JavaScript, the core language (ECMAScript)
The core language of JavaScript is standardized by the ECMA TC39 committee as a language named ECMAScript. "ECMAScript" is the term for the language standard, but "ECMAScript" and "JavaScript" can be used interchangeably.
This core language is also used in non-browser environments, for example in [Node.js](https://nodejs.org).
### What falls under the ECMAScript scope?
Among other things, ECMAScript defines:
- Language syntax (parsing rules, keywords, control flow, object literal initialization, ...)
- Error handling mechanisms ({{jsxref("Statements/throw", "throw")}}, {{jsxref("Statements/try...catch", "try...catch")}}, ability to create user-defined {{jsxref("Error")}} types)
- Types (boolean, number, string, function, object, ...)
- A prototype-based inheritance mechanism
- Built-in objects and functions, including {{jsxref("JSON")}}, {{jsxref("Math")}}, [Array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) methods, {{jsxref("parseInt")}}, {{jsxref("decodeURI")}}, etc.
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- A [module system](/en-US/docs/Web/JavaScript/Guide/Modules)
- Basic memory model
### Standardization process
ECMAScript editions are approved and published as a standard by the ECMA General Assembly on a yearly basis. All development is public on the [Ecma TC39 GitHub organization](https://github.com/tc39), which hosts proposals, the official specification text, and meeting notes.
Before the 6th edition of ECMAScript (known as ES6), specifications were published once every several years, and are commonly referred by their major version numbers β ES3, ES5, etc. After ES6, the specification is named by the publishing year β ES2017, ES2018, etc. ES6 is synonymous with ES2015. _ESNext_ is a dynamic name that refers to whatever the next version is at the time of writing. ESNext features are more correctly called proposals, because, by definition, the specification has not been finalized yet.
The current committee-approved snapshot of ECMA-262 is available in PDF and HTML format on Ecma International's [ECMA-262 language specification page](https://ecma-international.org/publications-and-standards/standards/ecma-262/). ECMA-262 and ECMA-402 are continuously maintained and kept up to date by the specification editors; the TC39 website hosts the latest, up-to-date [ECMA-262](https://tc39.es/ecma262/) and [ECMA-402](https://tc39.es/ecma402/) versions.
New language features, including introduction of new syntaxes and APIs and revision of existing behaviors, are discussed in the form of proposals. Each proposal goes through a [4-stage process](https://tc39.es/process-document/), and is typically implemented by JavaScript engines at stage 3 or stage 4 and thus available for public consumption.
See [Wikipedia ECMAScript entry](https://en.wikipedia.org/wiki/ECMAScript) for more information on ECMAScript history.
### Internationalization API
The [ECMAScript Internationalization API Specification](https://402.ecma-international.org/1.0/) is an addition to the ECMAScript Language Specification, also standardized by Ecma TC39. The internationalization API provides collation (string comparison), number formatting, and date-and-time formatting for JavaScript applications, letting the applications choose the language and tailor the functionality to their needs. The initial standard was approved in December 2012; the status of implementations in browsers is tracked in the documentation of the {{jsxref("Intl")}} object. The Internationalization specification is nowadays also ratified on a yearly basis and browsers constantly improve their implementation.
### Related resources
There are a variety of ways you can participate in or just track current work on the ECMAScript Language Specification and the ECMAScript Internationalization API Specification and related resources:
- [ECMAScript Language Specification repo](https://github.com/tc39/ecma262)
- [ECMAScript Internationalization API Specification repo](https://github.com/tc39/ecma402)
- [ECMAScript proposals repo](https://github.com/tc39/proposals)
- [ECMAScript conformance test suite repo](https://github.com/tc39/test262)
- [TC39 meeting notes](https://github.com/tc39/notes)
- [ECMAScript spec discussion; current mailing list](https://es.discourse.group/)
- [ECMAScript spec discussion; historical mailing-list archives (until March 2021)](https://esdiscuss.org/)
## DOM APIs
### WebIDL
The [WebIDL specification](https://webidl.spec.whatwg.org/) provides the glue between the DOM technologies and ECMAScript.
### The Core of the DOM
The Document Object Model (DOM) is a cross-platform, **language-independent convention** for representing and interacting with objects in HTML, XHTML and XML documents. Objects in the **DOM tree** may be addressed and manipulated by using methods on the objects. The [W3C](/en-US/docs/Glossary/W3C) standardizes the Core Document Object Model, which defines language-agnostic interfaces that abstract HTML and XML documents as objects, and also defines mechanisms to manipulate this abstraction. Among the things defined by the DOM, we can find:
- The document structure, a tree model, and the DOM Event architecture in [DOM core](https://dom.spec.whatwg.org/): [`Node`](/en-US/docs/Web/API/Node), [`Element`](/en-US/docs/Web/API/Element), [`DocumentFragment`](/en-US/docs/Web/API/DocumentFragment), [`Document`](/en-US/docs/Web/API/Document), [`DOMImplementation`](/en-US/docs/Web/API/DOMImplementation), [`Event`](/en-US/docs/Web/API/Event), [`EventTarget`](/en-US/docs/Web/API/EventTarget), β¦
- A less rigorous definition of the DOM Event Architecture, as well as specific events in [DOM events](https://w3c.github.io/uievents/).
- Other things such as [DOM Traversal](https://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html) and [DOM Range](https://dom.spec.whatwg.org/#ranges).
From the ECMAScript point of view, objects defined in the DOM specification are called "host objects".
### HTML DOM
[HTML](https://html.spec.whatwg.org/multipage/), the Web's markup language, is specified in terms of the DOM. Layered above the abstract concepts defined in DOM Core, HTML also defines the _meaning_ of elements. The HTML DOM includes such things as the `className` property on HTML elements, or APIs such as [`document.body`](/en-US/docs/Web/API/Document/body).
The HTML specification also defines restrictions on documents; for example, it requires all children of a [`<ul>`](/en-US/docs/Web/HTML/Element/ul) element, which represents an unordered list, to be [`<li>`](/en-US/docs/Web/HTML/Element/li) elements, as those represent list items. In general, it also forbids using elements and attributes that aren't defined in a standard.
Looking for the [`Document`](/en-US/docs/Web/API/Document) object, [`Window`](/en-US/docs/Web/API/Window) object, and the other DOM elements? Read the [DOM documentation](/en-US/docs/Web/API/Document_Object_Model).
## Other notable APIs
- The [`setTimeout`](/en-US/docs/Web/API/setTimeout) and [`setInterval`](/en-US/docs/Web/API/setInterval) functions were first specified on the [`Window`](/en-US/docs/Web/API/Window) interface in HTML Standard.
- [XMLHttpRequest](https://xhr.spec.whatwg.org/) makes it possible to send asynchronous HTTP requests.
- The [Fetch API](https://fetch.spec.whatwg.org/) provides a more ergonomic abstraction for network requests.
- The [CSS Object Model](https://drafts.csswg.org/cssom/) abstract CSS rules as objects.
- [WebWorkers](https://html.spec.whatwg.org/multipage/workers.html) allows parallel computation.
- [WebSockets](https://html.spec.whatwg.org/multipage/#network) allows low-level bidirectional communication.
- [Canvas 2D Context](https://html.spec.whatwg.org/multipage//#2dcontext) is a drawing API for [`<canvas>`](/en-US/docs/Web/HTML/Element/canvas).
- The [WebAssembly interface](https://webassembly.github.io/spec/js-api) provides utilities for communication between JavaScript code and [WebAssembly](/en-US/docs/WebAssembly) modules.
Non-browser environments (like Node.js) often do not have DOM APIs β because they don't interact with a document β but they still usually implement many web APIs, such as [`fetch()`](/en-US/docs/Web/API/fetch) and [`setTimeout()`](/en-US/docs/Web/API/setTimeout).
## JavaScript implementations
There are three main JavaScript implementations used in browser environments and beyond:
- Mozilla's [SpiderMonkey](https://spidermonkey.dev/), used in Firefox. This was the first _ever_ JavaScript engine, created by Brendan Eich at Netscape.
- Google's [V8](https://v8.dev/), used in Google Chrome, Opera, Edge, [Node.js](https://nodejs.org), [Deno](https://deno.land/), [Electron](https://www.electronjs.org/), and more.
- Apple's [JavaScriptCore](https://trac.webkit.org/wiki/JavaScriptCore) (also known as SquirrelFish/Nitro), used in WebKit browsers such as Apple Safari, and [Bun](https://bun.sh/).
Besides the above implementations, there are other popular JavaScript engines such as:
- [Carakan](https://dev.opera.com/blog/carakan-faq/), used in earlier versions of Opera.
- Microsoft's [Chakra](<https://en.wikipedia.org/wiki/Chakra_(JScript_engine)>) engine, used in Internet Explorer (although the language it implements is formally called "JScript" to avoid trademark issues). Earlier versions of Edge used a new JavaScript engine, confusingly also called [Chakra](<https://en.wikipedia.org/wiki/Chakra_(JavaScript_engine)>).
- [LibJS](https://libjs.dev/), used in the browser implementation of [SerenityOS](https://serenityos.org/).
- Mozilla's [Rhino](<https://en.wikipedia.org/wiki/Rhino_(JavaScript_engine)>) engine, a JavaScript implementation written in Java, created primarily by Norris Boyd (also at Netscape).
There are some engines specifically tailored for non-browser purposes:
- [Engine262](https://engine262.js.org/), a JavaScript engine written in JavaScript. It is created for JavaScript developers to explore new language features and find bugs in the specification.
- [Moddable XS](https://www.moddable.com/), used in embedded systems such as IoT.
- [QuickJS](https://bellard.org/quickjs/), a small and embeddable JavaScript engine.
- Meta's [Hermes](https://hermesengine.dev/) engine, an engine optimized for [React Native](https://reactnative.dev/docs/hermes).
- Oracle's [GraalJS](https://www.graalvm.org/), a high performance implementation built on the GraalVM by Oracle Labs.
JavaScript engines expose a public API which application developers can use to integrate JavaScript into their software. By far, the most common host environment for JavaScript is web browsers. Web browsers typically use the public API to create **host objects** responsible for reflecting the [DOM](https://dom.spec.whatwg.org/) into JavaScript.
Another common application for JavaScript is as a (Web) server-side scripting language. A JavaScript web server exposes host objects representing a HTTP request and response objects, which can then be manipulated by a JavaScript program to dynamically generate web pages. [Node.js](https://nodejs.org) is a popular example of this.
## Shells
A JavaScript shell allows you to quickly test snippets of JavaScript code without having to reload a web page. They are extremely useful for developing and debugging code.
### Standalone JavaScript shells
The following JavaScript shells are stand-alone environments, like Perl or Python.
- [Node.js](https://nodejs.org/) - Node.js is a platform for easily building fast, scalable network applications.
- [ShellJS](https://github.com/shelljs/shelljs) - Portable Unix shell commands for Node.js.
### Browser-based JavaScript shells
The following JavaScript shells run code through the browser's JavaScript engine.
- Firefox has a [built-in JavaScript console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/the_command_line_interpreter/index.html), which support multi-line editing.
- [Babel REPL](https://babeljs.io/repl) - A browser-based [REPL](https://en.wikipedia.org/wiki/REPL) for experimenting with future JavaScript.
- [TypeScript playground](https://www.typescriptlang.org/play) β A browser-based playground for experimenting both new JavaScript features (via the tsc compiler) and TypeScript syntax.
## Tools & resources
Helpful tools for writing and debugging your JavaScript code.
- [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html)
- : [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html), [JavaScript Profiler](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html), [Debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html), and more.
- [Learn JavaScript](https://learnjavascript.online/)
- : An excellent resource for aspiring web developers β Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
- [TogetherJS](https://togetherjs.com/)
- : Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real-time!
- [Stack Overflow](https://stackoverflow.com/questions/tagged/javascript)
- : Stack Overflow questions tagged with "JavaScript".
- [JSFiddle](https://jsfiddle.net/)
- : Edit JavaScript, CSS, and HTML and get live results. Use external resources and collaborate with your team online.
- [Plunker](https://plnkr.co/)
- : Plunker is an online community for creating, collaborating on, and sharing your web development ideas. Edit your JavaScript, CSS, and HTML files and get live results and file structure.
- [JSBin](https://jsbin.com/)
- : JS Bin is an open-source collaborative web development debugging tool.
- [Codepen](https://codepen.io/)
- : Codepen is another collaborative web development tool used as a live result playground.
- [StackBlitz](https://stackblitz.com/)
- : StackBlitz is another online playground/debugging tool, which can host and deploy full-stack applications using React, Angular, etc.
- [RunJS](https://runjs.app/)
- : RunJS is a desktop playground/scratchpad tool, which provides live results and access to both Node and Browser APIs.
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/inheritance_and_the_prototype_chain/index.md | ---
title: Inheritance and the prototype chain
slug: Web/JavaScript/Inheritance_and_the_prototype_chain
page-type: guide
---
{{jsSidebar("Advanced")}}
In programming, _inheritance_ refers to passing down characteristics from a parent to a child so that a new piece of code can reuse and build upon the features of an existing one. JavaScript implements inheritance by using [objects](/en-US/docs/Web/JavaScript/Data_structures#objects). Each object has an internal link to another object called its _prototype_. That prototype object has a prototype of its own, and so on until an object is reached with `null` as its prototype. By definition, `null` has no prototype and acts as the final link in this **prototype chain**. It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like [static dispatching](https://en.wikipedia.org/wiki/Static_dispatch) do not exist in JavaScript.
JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is [dynamic](/en-US/docs/Web/JavaScript/Data_structures#dynamic_and_weak_typing) and does not have static types. While this confusion is often considered to be one of JavaScript's weaknesses, the prototypal inheritance model itself is, in fact, more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model β which is how [classes](/en-US/docs/Web/JavaScript/Reference/Classes) are implemented.
Although classes are now widely adopted and have become a new paradigm in JavaScript, classes do not bring a new inheritance pattern. While classes abstract most of the prototypal mechanism away, understanding how prototypes work under the hood is still useful.
## Inheritance with the prototype chain
### Inheriting properties
JavaScript objects are dynamic "bags" of properties (referred to as **own properties**). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
> **Note:** Following the ECMAScript standard, the notation `someObject.[[Prototype]]` is used to designate the prototype of `someObject`. The `[[Prototype]]` internal slot can be accessed and modified with the {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}} functions respectively. This is equivalent to the JavaScript accessor [`__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) which is non-standard but de-facto implemented by many JavaScript engines. To prevent confusion while keeping it succinct, in our notation we will avoid using `obj.__proto__` but use `obj.[[Prototype]]` instead. This corresponds to `Object.getPrototypeOf(obj)`.
>
> It should not be confused with the `func.prototype` property of functions, which instead specifies the `[[Prototype]]` to be assigned to all _instances_ of objects created by the given function when used as a constructor. We will discuss the `prototype` property of constructor functions in [a later section](#constructors).
There are several ways to specify the `[[Prototype]]` of an object, which are listed in [a later section](#different_ways_of_creating_and_mutating_prototype_chains). For now, we will use the [`__proto__` syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#prototype_setter) for illustration. It's worth noting that the `{ __proto__: ... }` syntax is different from the `obj.__proto__` accessor: the former is standard and not deprecated.
In an object literal like `{ a: 1, b: 2, __proto__: c }`, the value `c` (which has to be either `null` or another object) will become the `[[Prototype]]` of the object represented by the literal, while the other keys like `a` and `b` will become the _own properties_ of the object. This syntax reads very naturally, since `[[Prototype]]` is just an "internal property" of the object.
Here is what happens when trying to access a property:
```js
const o = {
a: 1,
b: 2,
// __proto__ sets the [[Prototype]]. It's specified here
// as another object literal.
__proto__: {
b: 3,
c: 4,
},
};
// o.[[Prototype]] has properties b and c.
// o.[[Prototype]].[[Prototype]] is Object.prototype (we will explain
// what that means later).
// Finally, o.[[Prototype]].[[Prototype]].[[Prototype]] is null.
// This is the end of the prototype chain, as null,
// by definition, has no [[Prototype]].
// Thus, the full prototype chain looks like:
// { a: 1, b: 2 } ---> { b: 3, c: 4 } ---> Object.prototype ---> null
console.log(o.a); // 1
// Is there an 'a' own property on o? Yes, and its value is 1.
console.log(o.b); // 2
// Is there a 'b' own property on o? Yes, and its value is 2.
// The prototype also has a 'b' property, but it's not visited.
// This is called Property Shadowing
console.log(o.c); // 4
// Is there a 'c' own property on o? No, check its prototype.
// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
console.log(o.d); // undefined
// Is there a 'd' own property on o? No, check its prototype.
// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
// o.[[Prototype]].[[Prototype]] is Object.prototype and
// there is no 'd' property by default, check its prototype.
// o.[[Prototype]].[[Prototype]].[[Prototype]] is null, stop searching,
// no property found, return undefined.
```
Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when it's intercepted by a [getter or setter](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters).
Similarly, you can create longer prototype chains, and a property will be sought on all of them.
```js
const o = {
a: 1,
b: 2,
// __proto__ sets the [[Prototype]]. It's specified here
// as another object literal.
__proto__: {
b: 3,
c: 4,
__proto__: {
d: 5,
},
},
};
// { a: 1, b: 2 } ---> { b: 3, c: 4 } ---> { d: 5 } ---> Object.prototype ---> null
console.log(o.d); // 5
```
### Inheriting "methods"
JavaScript does not have "[methods](/en-US/docs/Glossary/Method)" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of _method overriding_).
When an inherited function is executed, the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) points to the inheriting object, not to the prototype object where the function is an own property.
```js
const parent = {
value: 2,
method() {
return this.value + 1;
},
};
console.log(parent.method()); // 3
// When calling parent.method in this case, 'this' refers to parent
// child is an object that inherits from parent
const child = {
__proto__: parent,
};
console.log(child.method()); // 3
// When child.method is called, 'this' refers to child.
// So when child inherits the method of parent,
// The property 'value' is sought on child. However, since child
// doesn't have an own property called 'value', the property is
// found on the [[Prototype]], which is parent.value.
child.value = 4; // assign the value 4 to the property 'value' on child.
// This shadows the 'value' property on parent.
// The child object now looks like:
// { value: 4, __proto__: { value: 2, method: [Function] } }
console.log(child.method()); // 5
// Since child now has the 'value' property, 'this.value' means
// child.value instead
```
## Constructors
The power of prototypes is that we can reuse a set of properties if they should be present on every instance β especially for methods. Suppose we are to create a series of boxes, where each box is an object that contains a value which can be accessed through a `getValue` function. A naive implementation would be:
```js-nolint
const boxes = [
{ value: 1, getValue() { return this.value; } },
{ value: 2, getValue() { return this.value; } },
{ value: 3, getValue() { return this.value; } },
];
```
This is subpar, because each instance has its own function property that does the same thing, which is redundant and unnecessary. Instead, we can move `getValue` to the `[[Prototype]]` of all boxes:
```js
const boxPrototype = {
getValue() {
return this.value;
},
};
const boxes = [
{ value: 1, __proto__: boxPrototype },
{ value: 2, __proto__: boxPrototype },
{ value: 3, __proto__: boxPrototype },
];
```
This way, all boxes' `getValue` method will refer to the same function, lowering memory usage. However, manually binding the `__proto__` for every object creation is still very inconvenient. This is when we would use a _constructor_ function, which automatically sets the `[[Prototype]]` for every object manufactured. Constructors are functions called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new).
```js
// A constructor function
function Box(value) {
this.value = value;
}
// Properties all boxes created from the Box() constructor
// will have
Box.prototype.getValue = function () {
return this.value;
};
const boxes = [new Box(1), new Box(2), new Box(3)];
```
We say that `new Box(1)` is an _instance_ created from the `Box` constructor function. `Box.prototype` is not much different from the `boxPrototype` object we created previously β it's just a plain object. Every instance created from a constructor function will automatically have the constructor's [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property as its `[[Prototype]]` β that is, `Object.getPrototypeOf(new Box()) === Box.prototype`. `Constructor.prototype` by default has one own property: [`constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor), which references the constructor function itself β that is, `Box.prototype.constructor === Box`. This allows one to access the original constructor from any instance.
> **Note:** If a non-primitive is returned from the constructor function, that value will become the result of the `new` expression. In this case the `[[Prototype]]` may not be correctly bound β but this should not happen much in practice.
The above constructor function can be rewritten in [classes](/en-US/docs/Web/JavaScript/Reference/Classes) as:
```js
class Box {
constructor(value) {
this.value = value;
}
// Methods are created on Box.prototype
getValue() {
return this.value;
}
}
```
Classes are syntax sugar over constructor functions, which means you can still manipulate `Box.prototype` to change the behavior of all instances. However, because classes are designed to be an abstraction over the underlying prototype mechanism, we will use the more-lightweight constructor function syntax for this tutorial to fully demonstrate how prototypes work.
Because `Box.prototype` references the same object as the `[[Prototype]]` of all instances, we can change the behavior of all instances by mutating `Box.prototype`.
```js
function Box(value) {
this.value = value;
}
Box.prototype.getValue = function () {
return this.value;
};
const box = new Box(1);
// Mutate Box.prototype after an instance has already been created
Box.prototype.getValue = function () {
return this.value + 1;
};
box.getValue(); // 2
```
A corollary is, _re-assigning_ `Constructor.prototype` (`Constructor.prototype = ...`) is a bad idea for two reasons:
- The `[[Prototype]]` of instances created before the reassignment is now referencing a different object from the `[[Prototype]]` of instances created after the reassignment β mutating one's `[[Prototype]]` no longer mutates the other.
- Unless you manually re-set the `constructor` property, the constructor function can no longer be traced from `instance.constructor`, which may break user expectation. Some built-in operations will read the `constructor` property as well, and if it is not set, they may not work as expected.
`Constructor.prototype` is only useful when constructing instances. It has nothing to do with `Constructor.[[Prototype]]`, which is the constructor function's _own_ prototype, which is `Function.prototype` β that is, `Object.getPrototypeOf(Constructor) === Function.prototype`.
### Implicit constructors of literals
Some literal syntaxes in JavaScript create instances that implicitly set the `[[Prototype]]`. For example:
```js
// Object literals (without the `__proto__` key) automatically
// have `Object.prototype` as their `[[Prototype]]`
const object = { a: 1 };
Object.getPrototypeOf(object) === Object.prototype; // true
// Array literals automatically have `Array.prototype` as their `[[Prototype]]`
const array = [1, 2, 3];
Object.getPrototypeOf(array) === Array.prototype; // true
// RegExp literals automatically have `RegExp.prototype` as their `[[Prototype]]`
const regexp = /abc/;
Object.getPrototypeOf(regexp) === RegExp.prototype; // true
```
We can "de-sugar" them into their constructor form.
```js
const array = new Array(1, 2, 3);
const regexp = new RegExp("abc");
```
For example, "array methods" like [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) are simply methods defined on `Array.prototype`, which is why they are automatically available on all array instances.
> **Warning:** There is one misfeature that used to be prevalent β extending `Object.prototype` or one of the other built-in prototypes. An example of this misfeature is, defining `Array.prototype.myMethod = function () {...}` and then using `myMethod` on all array instances.
>
> This misfeature is called _monkey patching_. Doing monkey patching risks forward compatibility, because if the language adds this method in the future but with a different signature, your code will break. It has led to incidents like the [SmooshGate](https://developer.chrome.com/blog/smooshgate/), and can be a great nuisance for the language to advance since JavaScript tries to "not break the web".
>
> The **only** good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like `Array.prototype.forEach`.
It may be interesting to note that due to historical reasons, some built-in constructors' `prototype` property are instances themselves. For example, `Number.prototype` is a number 0, `Array.prototype` is an empty array, and `RegExp.prototype` is `/(?:)/`.
```js
Number.prototype + 1; // 1
Array.prototype.map((x) => x + 1); // []
String.prototype + "a"; // "a"
RegExp.prototype.source; // "(?:)"
Function.prototype(); // Function.prototype is a no-op function by itself
```
However, this is not the case for user-defined constructors, nor for modern constructors like `Map`.
```js
Map.prototype.get(1);
// Uncaught TypeError: get method called on incompatible Map.prototype
```
### Building longer inheritance chains
The `Constructor.prototype` property will become the `[[Prototype]]` of the constructor's instances, as-is β including `Constructor.prototype`'s own `[[Prototype]]`. By default, `Constructor.prototype` is a _plain object_ β that is, `Object.getPrototypeOf(Constructor.prototype) === Object.prototype`. The only exception is `Object.prototype` itself, whose `[[Prototype]]` is `null` β that is, `Object.getPrototypeOf(Object.prototype) === null`. Therefore, a typical constructor will build the following prototype chain:
```js
function Constructor() {}
const obj = new Constructor();
// obj ---> Constructor.prototype ---> Object.prototype ---> null
```
To build longer prototype chains, we can set the `[[Prototype]]` of `Constructor.prototype` via the [`Object.setPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) function.
```js
function Base() {}
function Derived() {}
// Set the `[[Prototype]]` of `Derived.prototype`
// to `Base.prototype`
Object.setPrototypeOf(Derived.prototype, Base.prototype);
const obj = new Derived();
// obj ---> Derived.prototype ---> Base.prototype ---> Object.prototype ---> null
```
In class terms, this is equivalent to using the [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) syntax.
```js
class Base {}
class Derived extends Base {}
const obj = new Derived();
// obj ---> Derived.prototype ---> Base.prototype ---> Object.prototype ---> null
```
You may also see some legacy code using {{jsxref("Object.create()")}} to build the inheritance chain. However, because this reassigns the `prototype` property and removes the [`constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) property, it can be more error-prone, while performance gains may not be apparent if the constructors haven't created any instances yet.
```js example-bad
function Base() {}
function Derived() {}
// Re-assigns `Derived.prototype` to a new object
// with `Base.prototype` as its `[[Prototype]]`
// DON'T DO THIS β use Object.setPrototypeOf to mutate it instead
Derived.prototype = Object.create(Base.prototype);
```
## Inspecting prototypes: a deeper dive
Let's look at what happens behind the scenes in a bit more detail.
In JavaScript, as mentioned above, functions are able to have properties. All functions have a special property named `prototype`. Please note that the code below is free-standing (it is safe to assume there is no other JavaScript on the webpage other than the below code). For the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below JavaScript code, and run it by pressing the Enter/Return key. (The console is included in most web browser's Developer Tools. More information is available for [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html), [Chrome DevTools](https://developer.chrome.com/docs/devtools/), and [Edge DevTools](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/).)
```js
function doSomething() {}
console.log(doSomething.prototype);
// It does not matter how you declare the function; a
// function in JavaScript will always have a default
// prototype property β with one exception: an arrow
// function doesn't have a default prototype property:
const doSomethingFromArrowFunction = () => {};
console.log(doSomethingFromArrowFunction.prototype);
```
As seen above, `doSomething()` has a default `prototype` property, as demonstrated by the console. After running this code, the console should have displayed an object that looks similar to this.
```plain
{
constructor: Ζ doSomething(),
[[Prototype]]: {
constructor: Ζ Object(),
hasOwnProperty: Ζ hasOwnProperty(),
isPrototypeOf: Ζ isPrototypeOf(),
propertyIsEnumerable: Ζ propertyIsEnumerable(),
toLocaleString: Ζ toLocaleString(),
toString: Ζ toString(),
valueOf: Ζ valueOf()
}
}
```
> **Note:** The Chrome console uses `[[Prototype]]` to denote the object's prototype, following the spec's terms; Firefox uses `<prototype>`. For consistency we will use `[[Prototype]]`.
We can add properties to the prototype of `doSomething()`, as shown below.
```js
function doSomething() {}
doSomething.prototype.foo = "bar";
console.log(doSomething.prototype);
```
This results in:
```plain
{
foo: "bar",
constructor: Ζ doSomething(),
[[Prototype]]: {
constructor: Ζ Object(),
hasOwnProperty: Ζ hasOwnProperty(),
isPrototypeOf: Ζ isPrototypeOf(),
propertyIsEnumerable: Ζ propertyIsEnumerable(),
toLocaleString: Ζ toLocaleString(),
toString: Ζ toString(),
valueOf: Ζ valueOf()
}
}
```
We can now use the `new` operator to create an instance of `doSomething()` based on this prototype. To use the new operator, call the function normally except prefix it with `new`. Calling a function with the `new` operator returns an object that is an instance of the function. Properties can then be added onto this object.
Try the following code:
```js
function doSomething() {}
doSomething.prototype.foo = "bar"; // add a property onto the prototype
const doSomeInstancing = new doSomething();
doSomeInstancing.prop = "some value"; // add a property onto the object
console.log(doSomeInstancing);
```
This results in an output similar to the following:
```plain
{
prop: "some value",
[[Prototype]]: {
foo: "bar",
constructor: Ζ doSomething(),
[[Prototype]]: {
constructor: Ζ Object(),
hasOwnProperty: Ζ hasOwnProperty(),
isPrototypeOf: Ζ isPrototypeOf(),
propertyIsEnumerable: Ζ propertyIsEnumerable(),
toLocaleString: Ζ toLocaleString(),
toString: Ζ toString(),
valueOf: Ζ valueOf()
}
}
}
```
As seen above, the `[[Prototype]]` of `doSomeInstancing` is `doSomething.prototype`. But, what does this do? When you access a property of `doSomeInstancing`, the runtime first looks to see if `doSomeInstancing` has that property.
If `doSomeInstancing` does not have the property, then the runtime looks for the property in `doSomeInstancing.[[Prototype]]` (a.k.a. `doSomething.prototype`). If `doSomeInstancing.[[Prototype]]` has the property being looked for, then that property on `doSomeInstancing.[[Prototype]]` is used.
Otherwise, if `doSomeInstancing.[[Prototype]]` does not have the property, then `doSomeInstancing.[[Prototype]].[[Prototype]]` is checked for the property. By default, the `[[Prototype]]` of any function's `prototype` property is `Object.prototype`. So, `doSomeInstancing.[[Prototype]].[[Prototype]]` (a.k.a. `doSomething.prototype.[[Prototype]]` (a.k.a. `Object.prototype`)) is then looked through for the property being searched for.
If the property is not found in `doSomeInstancing.[[Prototype]].[[Prototype]]`, then `doSomeInstancing.[[Prototype]].[[Prototype]].[[Prototype]]` is looked through. However, there is a problem: `doSomeInstancing.[[Prototype]].[[Prototype]].[[Prototype]]` does not exist, because `Object.prototype.[[Prototype]]` is `null`. Then, and only then, after the entire prototype chain of `[[Prototype]]`'s is looked through, the runtime asserts that the property does not exist and conclude that the value at the property is `undefined`.
Let's try entering some more code into the console:
```js
function doSomething() {}
doSomething.prototype.foo = "bar";
const doSomeInstancing = new doSomething();
doSomeInstancing.prop = "some value";
console.log("doSomeInstancing.prop: ", doSomeInstancing.prop);
console.log("doSomeInstancing.foo: ", doSomeInstancing.foo);
console.log("doSomething.prop: ", doSomething.prop);
console.log("doSomething.foo: ", doSomething.foo);
console.log("doSomething.prototype.prop:", doSomething.prototype.prop);
console.log("doSomething.prototype.foo: ", doSomething.prototype.foo);
```
This results in the following:
```plain
doSomeInstancing.prop: some value
doSomeInstancing.foo: bar
doSomething.prop: undefined
doSomething.foo: undefined
doSomething.prototype.prop: undefined
doSomething.prototype.foo: bar
```
## Different ways of creating and mutating prototype chains
We have encountered many ways to create objects and change their prototype chains. We will systematically summarize the different ways, comparing each approach's pros and cons.
### Objects created with syntax constructs
```js
const o = { a: 1 };
// The newly created object o has Object.prototype as its [[Prototype]]
// Object.prototype has null as its prototype.
// o ---> Object.prototype ---> null
const b = ["yo", "whadup", "?"];
// Arrays inherit from Array.prototype
// (which has methods indexOf, forEach, etc.)
// The prototype chain looks like:
// b ---> Array.prototype ---> Object.prototype ---> null
function f() {
return 2;
}
// Functions inherit from Function.prototype
// (which has methods call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null
const p = { b: 2, __proto__: o };
// It is possible to point the newly created object's [[Prototype]] to
// another object via the __proto__ literal property. (Not to be confused
// with Object.prototype.__proto__ accessors)
// p ---> o ---> Object.prototype ---> null
```
<table class="standard-table">
<caption>
Pros and cons of using the <code>__proto__</code> key in <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializers</a>
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all modern engines. Pointing the <code>__proto__</code>
key to something that is not an object only fails silently without
throwing an exception. Contrary to the
{{jsxref("Object/proto", "Object.prototype.__proto__")}} setter,
<code>__proto__</code> in object literal initializers is standardized
and optimized, and can even be more performant than
{{jsxref("Object.create")}}. Declaring extra own properties on the
object at creation is more ergonomic than
{{jsxref("Object.create")}}.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
Not supported in IE10 and below. Likely to be confused with
{{jsxref("Object/proto", "Object.prototype.__proto__")}} accessors for
people unaware of the difference.
</td>
</tr>
</tbody>
</table>
### With constructor functions
```js
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype.addVertex = function (v) {
this.vertices.push(v);
};
const g = new Graph();
// g is an object with own properties 'vertices' and 'edges'.
// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
```
<table class="standard-table">
<caption>
Pros and cons of using constructor functions
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all engines β going all the way back to IE 5.5. Also, it
is very fast, very standard, and very JIT-optimizable.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
<ul>
<li>In order to use this method, the function in question must be
initialized. During this initialization, the constructor may store
unique information that must be generated per-object. This unique
information would only be generated once, potentially leading to
problems.</li>
<li>The initialization of the constructor may put unwanted methods onto
the object.</li>
</ul>
<p>Both of those are generally not problems in practice.</p>
</td>
</tr>
</tbody>
</table>
### With Object.create()
Calling {{jsxref("Object.create()")}} creates a new object. The `[[Prototype]]` of this object is the first argument of the function:
```js
const a = { a: 1 };
// a ---> Object.prototype ---> null
const b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)
const c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null
const d = Object.create(null);
// d ---> null (d is an object that has null directly as its prototype)
console.log(d.hasOwnProperty);
// undefined, because d doesn't inherit from Object.prototype
```
<table class="standard-table">
<caption>
Pros and cons of {{jsxref("Object.create")}}
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all modern engines. Allows directly setting
<code>[[Prototype]]</code> of an object at creation time, which permits
the runtime to further optimize the object. Also allows the creation of
objects without a prototype, using <code>Object.create(null)</code>.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
Not supported in IE8 and below. However, as Microsoft has discontinued
extended support for systems running IE8 and below, that should not be a
concern for most applications. Additionally, the slow object
initialization can be a performance black hole if using the second
argument, because each object-descriptor property has its own separate
descriptor object. When dealing with hundreds of thousands of object
descriptors in the form of objects, that lag time might become a serious
issue.
</td>
</tr>
</tbody>
</table>
### With classes
```js
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
class FilledRectangle extends Rectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Filled rectangle";
this.color = color;
}
}
const filledRectangle = new FilledRectangle(5, 10, "blue");
// filledRectangle ---> FilledRectangle.prototype ---> Rectangle.prototype ---> Object.prototype ---> null
```
<table class="standard-table">
<caption>
Pros and cons of classes
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all modern engines. Very high readability and maintainability.
<a href="/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties">Private properties</a>
are a feature with no trivial replacement in prototypal inheritance.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
Classes, especially with private properties, are less optimized than
traditional ones (although engine implementors are working to improve
this). Not supported in older environments and transpilers are usually
needed to use classes in production.
</td>
</tr>
</tbody>
</table>
### With Object.setPrototypeOf()
While all methods above will set the prototype chain at object creation time, [`Object.setPrototypeOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) allows mutating the `[[Prototype]]` internal property of an existing object.
```js
const obj = { a: 1 };
const anotherObj = { b: 2 };
Object.setPrototypeOf(obj, anotherObj);
// obj ---> anotherObj ---> Object.prototype ---> null
```
<table class="standard-table">
<caption>
Pros and cons of {{jsxref("Object.setPrototypeOf")}}
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all modern engines. Allows the dynamic manipulation of an
object's prototype and can even force a prototype on a prototype-less
object created with <code>Object.create(null)</code>.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
Ill-performing. Should be avoided if it's possible to set the prototype
at object creation time. Many engines optimize the prototype and try to
guess the location of the method in memory when calling an instance in
advance; but setting the prototype dynamically disrupts all those
optimizations. It might cause some engines to recompile your code for
de-optimization, to make it work according to the specs. Not supported
in IE8 and below.
</td>
</tr>
</tbody>
</table>
### With the \_\_proto\_\_ accessor
All objects inherit the [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) setter, which can be used to set the `[[Prototype]]` of an existing object (if the `__proto__` key is not overridden on the object).
> **Warning:** `Object.prototype.__proto__` accessors are **non-standard** and deprecated. You should almost always use `Object.setPrototypeOf` instead.
```js
const obj = {};
// DON'T USE THIS: for example only.
obj.__proto__ = { barProp: "bar val" };
obj.__proto__.__proto__ = { fooProp: "foo val" };
console.log(obj.fooProp);
console.log(obj.barProp);
```
<table class="standard-table">
<caption>
Pros and cons of setting the
{{jsxref("Object/proto","__proto__")}} property
</caption>
<tbody>
<tr>
<th scope="row">Pro(s)</th>
<td>
Supported in all modern engines. Setting
{{jsxref("Object/proto","__proto__")}} to something that
is not an object only fails silently. It does not throw an exception.
</td>
</tr>
<tr>
<th scope="row">Con(s)</th>
<td>
Non-performant and deprecated. Many engines optimize the prototype and
try to guess the location of the method in the memory when calling an
instance in advance; but setting the prototype dynamically disrupts all
those optimizations and can even force some engines to recompile for
de-optimization of your code, to make it work according to the specs.
Not supported in IE10 and below. The {{jsxref("Object/proto","__proto__")}}
setter is normative optional, so it may not work across all platforms.
You should almost always use {{jsxref("Object.setPrototypeOf")}}
instead.
</td>
</tr>
</tbody>
</table>
## Performance
The lookup time for properties that are high up on the prototype chain can have a negative impact on the performance, and this may be significant in the code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.
Also, when iterating over the properties of an object, **every** enumerable property that is on the prototype chain will be enumerated. To check whether an object has a property defined on _itself_ and not somewhere on its prototype chain, it is necessary to use the [`hasOwnProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) or [`Object.hasOwn`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) methods. All objects, except those with `null` as `[[Prototype]]`, inherit [`hasOwnProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) from `Object.prototype` β unless it has been overridden further down the prototype chain. To give you a concrete example, let's take the above graph example code to illustrate it:
```js
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype.addVertex = function (v) {
this.vertices.push(v);
};
const g = new Graph();
// g ---> Graph.prototype ---> Object.prototype ---> null
g.hasOwnProperty("vertices"); // true
Object.hasOwn(g, "vertices"); // true
g.hasOwnProperty("nope"); // false
Object.hasOwn(g, "nope"); // false
g.hasOwnProperty("addVertex"); // false
Object.hasOwn(g, "addVertex"); // false
Object.getPrototypeOf(g).hasOwnProperty("addVertex"); // true
```
Note: It is **not** enough to check whether a property is [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined). The property might very well exist, but its value just happens to be set to `undefined`.
## Conclusion
JavaScript may be a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no static types at all. Everything is either an object (instance) or a function (constructor), and even functions themselves are instances of the `Function` constructor. Even the "classes" as syntax constructs are just constructor functions at runtime.
All constructor functions in JavaScript have a special property called `prototype`, which works with the `new` operator. The reference to the prototype object is copied to the internal `[[Prototype]]` property of the new instance. For example, when you do `const a1 = new A()`, JavaScript (after creating the object in memory and before running function `A()` with `this` defined to it) sets `a1.[[Prototype]] = A.prototype`. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in `[[Prototype]]`. `[[Prototype]]` is looked at _recursively_, i.e. `a1.doSomething`, `Object.getPrototypeOf(a1).doSomething`, `Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething` etc., until it's found or `Object.getPrototypeOf` returns `null`. This means that all properties defined on `prototype` are effectively shared by all instances, and you can even later change parts of `prototype` and have the changes appear in all existing instances.
If, in the example above, you do `const a1 = new A(); const a2 = new A();`, then `a1.doSomething` would actually refer to `Object.getPrototypeOf(a1).doSomething` β which is the same as the `A.prototype.doSomething` you defined, i.e. `Object.getPrototypeOf(a1).doSomething === Object.getPrototypeOf(a2).doSomething === A.prototype.doSomething`.
It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should **never** be extended unless it is for the sake of compatibility with newer JavaScript features.
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/enumerability_and_ownership_of_properties/index.md | ---
title: Enumerability and ownership of properties
slug: Web/JavaScript/Enumerability_and_ownership_of_properties
page-type: guide
---
{{jsSidebar("More")}}
Every property in JavaScript objects can be classified by three factors:
- Enumerable or non-enumerable;
- String or [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol);
- Own property or inherited property from the prototype chain.
_Enumerable properties_ are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via [`Object.defineProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) and such are not enumerable by default. Most iteration means (such as [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops and [`Object.keys`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)) only visit enumerable keys.
Ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain.
All properties, enumerable or not, string or symbol, own or inherited, can be accessed with [dot notation or bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). In this section, we will focus on JavaScript means that visit a group of object properties one-by-one.
## Querying object properties
There are four built-in ways to query a property of an object. They all support both string and symbol keys. The following table summarizes when each method returns `true`.
| | Enumerable, own | Enumerable, inherited | Non-enumerable, own | Non-enumerable, inherited |
| ----------------------------------------------------------------------------------------------------------- | --------------- | --------------------- | ------------------- | ------------------------- |
| [`propertyIsEnumerable()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable) | `true β
` | `false β` | `false β` | `false β` |
| [`hasOwnProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) | `true β
` | `false β` | `true β
` | `false β` |
| [`Object.hasOwn()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) | `true β
` | `false β` | `true β
` | `false β` |
| [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) | `true β
` | `true β
` | `true β
` | `true β
` |
## Traversing object properties
There are many methods in JavaScript that traverse a group of properties of an object. Sometimes, these properties are returned as an array; sometimes, they are iterated one-by-one in a loop; sometimes, they are used for constructing or mutating another object. The following table summarizes when a property may be visited.
Methods that only visit string properties or only symbol properties will have an extra note. β
means a property of this type will be visited; β means it will not.
| | Enumerable, own | Enumerable, inherited | Non-enumerable, own | Non-enumerable, inherited |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | --------------------- | ------------------- | ------------------------- |
| [`Object.keys`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)<br />[`Object.values`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)<br />[`Object.entries`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) | β
<br />(strings) | β | β | β |
| [`Object.getOwnPropertyNames`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) | β
<br />(strings) | β | β
<br />(strings) | β |
| [`Object.getOwnPropertySymbols`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols) | β
<br />(symbols) | β | β
<br />(symbols) | β |
| [`Object.getOwnPropertyDescriptors`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors) | β
| β | β
| β |
| [`Reflect.ownKeys`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys) | β
| β | β
| β |
| [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) | β
<br />(strings) | β
<br />(strings) | β | β |
| [`Object.assign`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)<br />(After the first parameter) | β
| β | β | β |
| [Object spread](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) | β
| β | β | β |
## Obtaining properties by enumerability/ownership
Note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration.
- Detection can occur by `SimplePropertyRetriever.theGetMethodYouWant(obj).includes(prop)`
- Iteration can occur by `SimplePropertyRetriever.theGetMethodYouWant(obj).forEach((value, prop) => {});` (or use `filter()`, `map()`, etc.)
```js
const SimplePropertyRetriever = {
getOwnEnumerables(obj) {
return this._getPropertyNames(obj, true, false, this._enumerable);
// Or could use for...in filtered with Object.hasOwn or just this: return Object.keys(obj);
},
getOwnNonenumerables(obj) {
return this._getPropertyNames(obj, true, false, this._notEnumerable);
},
getOwnEnumerablesAndNonenumerables(obj) {
return this._getPropertyNames(
obj,
true,
false,
this._enumerableAndNotEnumerable,
);
// Or just use: return Object.getOwnPropertyNames(obj);
},
getPrototypeEnumerables(obj) {
return this._getPropertyNames(obj, false, true, this._enumerable);
},
getPrototypeNonenumerables(obj) {
return this._getPropertyNames(obj, false, true, this._notEnumerable);
},
getPrototypeEnumerablesAndNonenumerables(obj) {
return this._getPropertyNames(
obj,
false,
true,
this._enumerableAndNotEnumerable,
);
},
getOwnAndPrototypeEnumerables(obj) {
return this._getPropertyNames(obj, true, true, this._enumerable);
// Or could use unfiltered for...in
},
getOwnAndPrototypeNonenumerables(obj) {
return this._getPropertyNames(obj, true, true, this._notEnumerable);
},
getOwnAndPrototypeEnumerablesAndNonenumerables(obj) {
return this._getPropertyNames(
obj,
true,
true,
this._enumerableAndNotEnumerable,
);
},
// Private static property checker callbacks
_enumerable(obj, prop) {
return Object.prototype.propertyIsEnumerable.call(obj, prop);
},
_notEnumerable(obj, prop) {
return !Object.prototype.propertyIsEnumerable.call(obj, prop);
},
_enumerableAndNotEnumerable(obj, prop) {
return true;
},
// Inspired by http://stackoverflow.com/a/8024294/271577
_getPropertyNames(obj, iterateSelf, iteratePrototype, shouldInclude) {
const props = [];
do {
if (iterateSelf) {
Object.getOwnPropertyNames(obj).forEach((prop) => {
if (props.indexOf(prop) === -1 && shouldInclude(obj, prop)) {
props.push(prop);
}
});
}
if (!iteratePrototype) {
break;
}
iterateSelf = true;
obj = Object.getPrototypeOf(obj);
} while (obj);
return props;
},
};
```
## See also
- [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in)
- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
- [`Object.prototype.hasOwnProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)
- [`Object.prototype.propertyIsEnumerable()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable)
- [`Object.getOwnPropertyNames()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)
- [`Object.getOwnPropertySymbols()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols)
- [`Object.keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
- [`Object.getOwnPropertyDescriptors()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors)
- [`Object.hasOwn()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
- [`Reflect.ownKeys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys)
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/memory_management/index.md | ---
title: Memory management
slug: Web/JavaScript/Memory_management
page-type: guide
---
{{jsSidebar("Advanced")}}
Low-level languages like C, have manual memory management primitives such as [`malloc()`](https://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html) and [`free()`](https://en.wikipedia.org/wiki/C_dynamic_memory_allocation#Overview_of_functions). In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (_garbage collection_). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.
## Memory life cycle
Regardless of the programming language, the memory life cycle is pretty much always the same:
1. Allocate the memory you need
2. Use the allocated memory (read, write)
3. Release the allocated memory when it is not needed anymore
The second part is explicit in all languages. The first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like JavaScript.
### Allocation in JavaScript
#### Value initialization
In order to not bother the programmer with allocations, JavaScript will automatically allocate memory when values are initially declared.
```js
const n = 123; // allocates memory for a number
const s = "azerty"; // allocates memory for a string
const o = {
a: 1,
b: null,
}; // allocates memory for an object and contained values
// (like object) allocates memory for the array and
// contained values
const a = [1, null, "abra"];
function f(a) {
return a + 2;
} // allocates a function (which is a callable object)
// function expressions also allocate an object
someElement.addEventListener(
"click",
() => {
someElement.style.backgroundColor = "blue";
},
false,
);
```
#### Allocation via function calls
Some function calls result in object allocation.
```js
const d = new Date(); // allocates a Date object
const e = document.createElement("div"); // allocates a DOM element
```
Some methods allocate new values or objects:
```js
const s = "azerty";
const s2 = s.substr(0, 3); // s2 is a new string
// Since strings are immutable values,
// JavaScript may decide to not allocate memory,
// but just store the [0, 3] range.
const a = ["ouais ouais", "nan nan"];
const a2 = ["generation", "nan nan"];
const a3 = a.concat(a2);
// new array with 4 elements being
// the concatenation of a and a2 elements.
```
### Using values
Using values basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.
### Release when the memory is not needed anymore
The majority of memory management issues occur at this phase. The most difficult aspect of this stage is determining when the allocated memory is no longer needed.
Low-level languages require the developer to manually determine at which point in the program the allocated memory is no longer needed and to release it.
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as [garbage collection](<https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)>) (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it. This automatic process is an approximation since the general problem of determining whether or not a specific piece of memory is still needed is [undecidable](https://en.wikipedia.org/wiki/Decidability_%28logic%29).
## Garbage collection
As stated above, the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem. This section will explain the concepts that are necessary for understanding the main garbage collection algorithms and their respective limitations.
### References
The main concept that garbage collection algorithms rely on is the concept of _reference_. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to its [prototype](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) (implicit reference) and to its properties values (explicit reference).
In this context, the notion of an "object" is extended to something broader than regular JavaScript objects and also contain function scopes (or the global lexical scope).
### Reference-counting garbage collection
> **Note:** no modern JavaScript engine uses reference-counting for garbage collection anymore.
This is the most naΓ―ve garbage collection algorithm. This algorithm reduces the problem from determining whether or not an object is still needed to determining if an object still has any other objects referencing it. An object is said to be "garbage", or collectible if there are zero references pointing to it.
For example:
```js
let x = {
a: {
b: 2,
},
};
// 2 objects are created. One is referenced by the other as one of its properties.
// The other is referenced by virtue of being assigned to the 'x' variable.
// Obviously, none can be garbage-collected.
let y = x;
// The 'y' variable is the second thing that has a reference to the object.
x = 1;
// Now, the object that was originally in 'x' has a unique reference
// embodied by the 'y' variable.
let z = y.a;
// Reference to 'a' property of the object.
// This object now has 2 references: one as a property,
// the other as the 'z' variable.
y = "mozilla";
// The object that was originally in 'x' has now zero
// references to it. It can be garbage-collected.
// However its 'a' property is still referenced by
// the 'z' variable, so it cannot be freed.
z = null;
// The 'a' property of the object originally in x
// has zero references to it. It can be garbage collected.
```
There is a limitation when it comes to circular references. In the following example, two objects are created with properties that reference one another, thus creating a cycle. They will go out of scope after the function call has completed. At that point they become unneeded and their allocated memory should be reclaimed. However, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. Circular references are a common cause of memory leaks.
```js
function f() {
const x = {};
const y = {};
x.a = y; // x references y
y.a = x; // y references x
return "azerty";
}
f();
```
### Mark-and-sweep algorithm
This algorithm reduces the definition of "an object is no longer needed" to "an object is unreachable".
This algorithm assumes the knowledge of a set of objects called _roots._ In JavaScript, the root is the global object. Periodically, the garbage collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all _reachable_ objects and collect all non-reachable objects.
This algorithm is an improvement over the previous one since an object having zero references is effectively unreachable. The opposite does not hold true as we have seen with circular references.
Currently, all modern engines ship a mark-and-sweep garbage collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is no longer needed".
The immediate benefit of this approach is that cycles are no longer a problem. In the first example above, after the function call returns, the two objects are no longer referenced by any resource that is reachable from the global object. Consequently, they will be found unreachable by the garbage collector and have their allocated memory reclaimed.
However, the inability to manually control garbage collection remains. There are times when it would be convenient to manually decide when and what memory is released. In order to release the memory of an object, it needs to be made explicitly unreachable. It is also not possible to programmatically trigger garbage collection in JavaScript β and will likely never be within the core language, although engines may expose APIs behind opt-in flags.
## Configuring an engine's memory model
JavaScript engines typically offer flags that expose the memory model. For example, Node.js offers additional options and tools that expose the underlying V8 mechanisms for configuring and debugging memory issues. This configuration may not be available in browsers, and even less so for web pages (via HTTP headers, etc.).
The max amount of available heap memory can be increased with a flag:
```bash
node --max-old-space-size=6000 index.js
```
We can also expose the garbage collector for debugging memory issues using a flag and the [Chrome Debugger](https://nodejs.org/en/docs/guides/debugging-getting-started/):
```bash
node --expose-gc --inspect index.js
```
## Data structures aiding memory management
Although JavaScript does not directly expose the garbage collector API, the language offers several data structures that indirectly observe garbage collection and can be used to manage memory usage.
### WeakMaps and WeakSets
[`WeakMap`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and [`WeakSet`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) are data structures whose APIs closely mirror their non-weak counterparts: [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Set`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). `WeakMap` allows you to maintain a collection of key-value pairs, while `WeakSet` allows you to maintain a collection of unique values, both with performant addition, deletion, and querying.
`WeakMap` and `WeakSet` got the name from the concept of _weakly held_ values. If `x` is weakly held by `y`, it means that although you can access the value of `x` via `y`, the mark-and-sweep algorithm won't consider `x` as reachable if nothing else _strongly holds_ to it. Most data structures, except the ones discussed here, strongly holds to the objects passed in so that you can retrieve them at any time. The keys of `WeakMap` and `WeakSet` can be garbage-collected (for `WeakMap` objects, the values would then be eligible for garbage collection as well) as long as nothing else in the program is referencing the key. This is ensured by two characteristics:
- `WeakMap` and `WeakSet` can only store objects or symbols. This is because only objects are garbage collected β primitive values can always be forged (that is, `1 === 1` but `{} !== {}`), making them stay in the collection forever. [Registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) (like `Symbol.for("key")`) can also be forged and thus not garbage collectable, but symbols created with `Symbol("key")` are garbage collectable. [Well-known symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) like `Symbol.iterator` 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 as keys.
- `WeakMap` and `WeakSet` are not iterable. This prevents you from using `Array.from(map.keys()).length` to observe the liveliness of objects, or get hold of an arbitrary key which should otherwise be eligible for garbage collection. (Garbage collection should be as invisible as possible.)
In typical explanations of `WeakMap` and `WeakSet` (such as the one above), it's often implied that the key is garbage-collected first, freeing the value for garbage collection as well. However, consider the case of the value referencing the key:
```js
const wm = new WeakMap();
const key = {};
wm.set(key, { key });
// Now `key` cannot be garbage collected,
// because the value holds a reference to the key,
// and the value is strongly held in the map!
```
If `key` is stored as an actual reference, it would create a cyclic reference and make both the key and value ineligible for garbage collection, even when nothing else references `key` β because if `key` is garbage collected, it means that at some particular instant, `value.key` would point to a non-existent address, which is not legal. To fix this, the entries of `WeakMap` and `WeakSet` aren't actual references, but [ephemerons](https://dl.acm.org/doi/pdf/10.1145/263700.263733), an enhancement to the mark-and-sweep mechanism. [Barros et al.](https://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak/jucs_14_21_3481_3497_barros.pdf) offers a good summary of the algorithm (page 4). To quote a paragraph:
> Ephemerons are a refinement of weak pairs where neither the key nor the value can be classified as weak or strong. The connectivity of the key determines the connectivity of the value, but the connectivity of the value does not affect the connectivity of the key. [β¦] when the garbage collection offers support to ephemerons, it occurs in three phases instead of two (mark and sweep).
As a rough mental model, think of a `WeakMap` as the following implementation:
> **Warning:** This is not a polyfill nor is anywhere close to how it's implemented in the engine (which hooks into the garbage collection mechanism).
```js
class MyWeakMap {
#marker = Symbol("MyWeakMapData");
get(key) {
return key[this.#marker];
}
set(key, value) {
key[this.#marker] = value;
}
has(key) {
return this.#marker in key;
}
delete(key) {
delete key[this.#marker];
}
}
```
As you can see, the `MyWeakMap` never actually holds a collection of keys. It simply adds metadata to each object being passed in. The object is then garbage-collectable via mark-and-sweep. Therefore, it's not possible to iterate over the keys in a `WeakMap`, nor clear the `WeakMap` (as that also relies on the knowledge of the entire key collection).
For more information on their APIs, see the [keyed collections](/en-US/docs/Web/JavaScript/Guide/Keyed_collections) guide.
### WeakRefs and FinalizationRegistry
> **Note:** `WeakRef` and `FinalizationRegistry` offer direct introspection into the garbage collection machinery. [Avoid using them where possible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#avoid_where_possible) because the runtime semantics are almost completely unguaranteed.
All variables with an object as value are references to that object. However, such references are _strong_ β their existence would prevent the garbage collector from marking the object as eligible for collection. A [`WeakRef`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef) is a _weak reference_ to an object that allows the object to be garbage collected, while still retaining the ability to read the object's content during its lifetime.
One use case for `WeakRef` is a cache system which maps string URLs to large objects. We cannot use a `WeakMap` for this purpose, because `WeakMap` objects have their _keys_ weakly held, but not their _values_ β if you access a key, you would always deterministically get the value (since having access to the key means it's still alive). Here, we are okay to get `undefined` for a key (if the corresponding value is no longer alive) since we can just re-compute it, but we don't want unreachable objects to stay in the cache. In this case, we can use a normal `Map`, but with each value being a `WeakRef` of the object instead of the actual object value.
```js
function cached(getter) {
// A Map from string URLs to WeakRefs of results
const cache = new Map();
return async (key) => {
if (cache.has(key)) {
return cache.get(key).deref();
}
const value = await getter(key);
cache.set(key, new WeakRef(value));
return value;
};
}
const getImage = cached((url) => fetch(url).then((res) => res.blob()));
```
[`FinalizationRegistry`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry) provides an even stronger mechanism to observe garbage collection. It allows you to register objects and be notified when they are garbage collected. For example, for the cache system exemplified above, even when the blobs themselves are free for collection, the `WeakRef` objects that hold them are not β and over time, the `Map` may accumulate a lot of useless entries. Using a `FinalizationRegistry` allows one to perform cleanup in this case.
```js
function cached(getter) {
// A Map from string URLs to WeakRefs of results
const cache = new Map();
// Every time after a value is garbage collected, the callback is
// called with the key in the cache as argument, allowing us to remove
// the cache entry
const registry = new FinalizationRegistry((key) => {
// Note: it's important to test that the WeakRef is indeed empty.
// Otherwise, the callback may be called after a new object has been
// added with this key, and that new, alive object gets deleted
if (!cache.get(key)?.deref()) {
cache.delete(key);
}
});
return async (key) => {
if (cache.has(key)) {
return cache.get(key).deref();
}
const value = await getter(key);
cache.set(key, new WeakRef(value));
registry.register(value, key);
return value;
};
}
const getImage = cached((url) => fetch(url).then((res) => res.blob()));
```
Due to performance and security concerns, there is no guarantee of when the callback will be called, or if it will be called at all. It should only be used for cleanup β and non-critical cleanup. There are other ways for more deterministic resource management, such as [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch), which will always execute the `finally` block. `WeakRef` and `FinalizationRegistry` exist solely for optimization of memory usage in long-running programs.
For more information on the API of [`WeakRef`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef) and [`FinalizationRegistry`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry), see their reference pages.
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/language_overview/index.md | ---
title: JavaScript language overview
slug: Web/JavaScript/Language_overview
page-type: guide
---
{{jsSidebar}}
JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages β many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with [object prototypes](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) and classes. It also supports functional programming since functions are [first-class](/en-US/docs/Glossary/First-class_Function) objects that can be easily created via expressions and passed around like any other object.
This page serves as a quick overview of various JavaScript language features, written for readers with background in other languages, such as C or Java.
## Data types
Let's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript offers seven _primitive types_:
- [Number](/en-US/docs/Web/JavaScript/Data_structures#number_type): used for all number values (integer and floating point) except for _very_ big integers.
- [BigInt](/en-US/docs/Web/JavaScript/Data_structures#bigint_type): used for arbitrarily large integers.
- [String](/en-US/docs/Web/JavaScript/Data_structures#string_type): used to store text.
- [Boolean](/en-US/docs/Web/JavaScript/Data_structures#boolean_type): `true` and `false` β usually used for conditional logic.
- [Symbol](/en-US/docs/Web/JavaScript/Data_structures#symbol_type): used for creating unique identifiers that won't collide.
- [Undefined](/en-US/docs/Web/JavaScript/Data_structures#undefined_type): indicating that a variable has not been assigned a value.
- [Null](/en-US/docs/Web/JavaScript/Data_structures#null_type): indicating a deliberate non-value.
Everything else is known as an [Object](/en-US/docs/Web/JavaScript/Data_structures#objects). Common object types include:
- {{jsxref("Function")}}
- {{jsxref("Array")}}
- {{jsxref("Date")}}
- {{jsxref("RegExp")}}
- {{jsxref("Error")}}
Functions aren't special data structures in JavaScript β they are just a special type of object that can be called.
### Numbers
JavaScript has two built-in numeric types: Number and BigInt.
The Number type is a [IEEE 754 64-bit double-precision floating point value](https://en.wikipedia.org/wiki/Double_precision_floating-point_format), which means integers can be safely represented between [-(2<sup>53</sup> β 1)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER) and [2<sup>53</sup> β 1](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) without loss of precision, and floating point numbers can be stored all the way up to [1.79 Γ 10<sup>308</sup>](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE). Within numbers, JavaScript does not distinguish between floating point numbers and integers.
```js
console.log(3 / 2); // 1.5, not 1
```
So an _apparent integer_ is in fact _implicitly a float_. Because of IEEE 754 encoding, sometimes floating point arithmetic can be imprecise.
```js
console.log(0.1 + 0.2); // 0.30000000000000004
```
For operations that expect integers, such as bitwise operations, the number will be converted to a 32-bit integer.
[Number literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals) can also have prefixes to indicate the base (binary, octal, decimal, or hexadecimal), or an exponent suffix.
```js
console.log(0b111110111); // 503
console.log(0o767); // 503
console.log(0x1f7); // 503
console.log(5.03e2); // 503
```
The [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type is an arbitrary length integer. Its behavior is similar to C's integer types (e.g. division truncates to zero), except it can grow indefinitely. BigInts are specified with a number literal and an `n` suffix.
```js
console.log(-3n / 2n); // -1n
```
The standard [arithmetic operators](/en-US/docs/Web/JavaScript/Reference/Operators#arithmetic_operators) are supported, including addition, subtraction, remainder arithmetic, etc. BigInts and numbers cannot be mixed in arithmetic operations.
The {{jsxref("Math")}} object provides standard mathematical functions and constants.
```js
Math.sin(3.5);
const circumference = 2 * Math.PI * r;
```
There are three ways to convert a string to a number:
- {{jsxref("parseInt()")}}, which parses the string for an integer.
- {{jsxref("parseFloat()")}}, which parses the string for a floating-point number.
- The [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) function, which parses a string as if it's a number literal and supports many different number representations.
You can also use the [unary plus `+`](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) as a shorthand for `Number()`.
Number values also include {{jsxref("NaN")}} (short for "Not a Number") and {{jsxref("Infinity")}}. Many "invalid math" operations will return `NaN` β for example, if attempting to parse a non-numeric string, or using [`Math.log()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on a negative value. Division by zero produces `Infinity` (positive or negative).
`NaN` is contagious: if you provide it as an operand to any mathematical operation, the result will also be `NaN`. `NaN` is the only value in JavaScript that's not equal to itself (per IEEE 754 specification).
### Strings
Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are [UTF-16 encoded](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
```js
console.log("Hello, world");
console.log("δ½ ε₯½οΌδΈηοΌ"); // Nearly all Unicode characters can be written literally in string literals
```
Strings can be written with either single or double quotes β JavaScript does not have the distinction between characters and strings. If you want to represent a single character, you just use a string consisting of that single character.
```js
console.log("Hello"[1] === "e"); // true
```
To find the length of a string (in [code units](/en-US/docs/Glossary/Code_unit)), access its [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) property.
Strings have [utility methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods) to manipulate the string and access information about the string. Because all primitives are immutable by design, these methods return new strings.
The `+` operator is overloaded for strings: when one of the operands is a string, it performs string concatenation instead of number addition. A special [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals) syntax allows you to write strings with embedded expressions more succinctly. Unlike Python's f-strings or C#'s interpolated strings, template literals use backticks (not single or double quotes).
```js
const age = 25;
console.log("I am " + age + " years old."); // String concatenation
console.log(`I am ${age} years old.`); // Template literal
```
### Other types
JavaScript distinguishes between [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), which indicates a deliberate non-value (and is only accessible through the `null` keyword), and {{jsxref("undefined")}}, which indicates absence of value. There are many ways to obtain `undefined`:
- A [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement with no value (`return;`) implicitly returns `undefined`.
- Accessing a nonexistent [object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) property (`obj.iDontExist`) returns `undefined`.
- A variable declaration without initialization (`let x;`) will implicitly initialize the variable to `undefined`.
JavaScript has a Boolean type, with possible values `true` and `false` β both of which are keywords. Any value can be converted to a boolean according to the following rules:
1. `false`, `0`, empty strings (`""`), `NaN`, `null`, and `undefined` all become `false`.
2. All other values become `true`.
You can perform this conversion explicitly using the [`Boolean()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/Boolean) function:
```js
Boolean(""); // false
Boolean(234); // true
```
However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an `if` statement (see [Control structures](#control_structures)). For this reason, we sometimes speak of "[truthy](/en-US/docs/Glossary/Truthy)" and "[falsy](/en-US/docs/Glossary/Falsy)", meaning values that become `true` and `false`, respectively, when used in boolean contexts.
Boolean operations such as `&&` (logical _and_), `||` (logical _or_), and `!` (logical _not_) are supported; see [Operators](#operators).
The Symbol type is often used to create unique identifiers. Every symbol created with the [`Symbol()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) function is guaranteed to be unique. In addition, there are registered symbols, which are shared constants, and well-known symbols, which are utilized by the language as "protocols" for certain operations. You can read more about them in the [symbol reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol).
## Variables
Variables in JavaScript are declared using one of three keywords: [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var).
`let` allows you to declare block-level variables. The declared variable is available from the _block_ it is enclosed in.
```js
let a;
let name = "Simon";
// myLetVariable is *not* visible out here
for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
// myLetVariable is only visible in here
}
// myLetVariable is *not* visible out here
```
`const` allows you to declare variables whose values are never intended to change. The variable is available from the _block_ it is declared in.
```js
const Pi = 3.14; // Declare variable Pi
console.log(Pi); // 3.14
```
A variable declared with `const` cannot be reassigned.
```js-nolint example-bad
const Pi = 3.14;
Pi = 1; // will throw an error because you cannot change a constant variable.
```
`const` declarations only prevent _reassignments_ β they don't prevent _mutations_ of the variable's value, if it's an object.
```js
const obj = {};
obj.a = 1; // no error
console.log(obj); // { a: 1 }
```
`var` declarations can have surprising behaviors (for example, they are not block-scoped), and they are discouraged in modern JavaScript code.
If you declare a variable without assigning any value to it, its value is `undefined`. You can't declare a `const` variable without an initializer, because you can't change it later anyway.
`let` and `const` declared variables still occupy the entire scope they are defined in, and are in a region known as the [temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz) before the actual line of declaration. This has some interesting interactions with variable shadowing, which don't occur in other languages.
```js
function foo(x, condition) {
if (condition) {
console.log(x);
const x = 2;
console.log(x);
}
}
foo(1, true);
```
In most other languages, this would log "1" and "2", because before the `const x = 2` line, `x` should still refer to the parameter `x` in the upper scope. In JavaScript, because each declaration occupies the entire scope, this would throw an error on the first `console.log`: "Cannot access 'x' before initialization". For more information, see the reference page of [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let).
JavaScript is _dynamically typed_. Types (as described in [the previous section](#data_types)) are only associated with values, but not with variables. For `let`-declared variables, you can always change its type through reassignment.
```js
let a = 1;
a = "foo";
```
## Operators
JavaScript's numeric operators include `+`, `-`, `*`, `/`, `%` (remainder), and `**` (exponentiation). Values are assigned using `=`. Each binary operator also has a compound assignment counterpart such as `+=` and `-=`, which extend out to `x = x operator y`.
```js
x += 5;
x = x + 5;
```
You can use `++` and `--` to increment and decrement respectively. These can be used as a prefix or postfix operators.
The [`+` operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) also does string concatenation:
```js
"hello" + " world"; // "hello world"
```
If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:
```js
"3" + 4 + 5; // "345"
3 + 4 + "5"; // "75"
```
Adding an empty string to something is a useful way of converting it to a string itself.
[Comparisons](/en-US/docs/Web/JavaScript/Reference/Operators#relational_operators) in JavaScript can be made using `<`, `>`, `<=` and `>=`, which work for both strings and numbers. For equality, the [double-equals operator](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) performs type coercion if you give it different types, with sometimes interesting results. On the other hand, the [triple-equals operator](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) does not attempt type coercion, and is usually preferred.
```js
123 == "123"; // true
1 == true; // true
123 === "123"; // false
1 === true; // false
```
The double-equals and triple-equals also have their inequality counterparts: `!=` and `!==`.
JavaScript also has [bitwise operators](/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators) and [logical operators](/en-US/docs/Web/JavaScript/Reference/Operators#binary_logical_operators). Notably, logical operators don't work with boolean values only β they work by the "truthiness" of the value.
```js
const a = 0 && "Hello"; // 0 because 0 is "falsy"
const b = "Hello" || "world"; // "Hello" because both "Hello" and "world" are "truthy"
```
The `&&` and `||` operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:
```js
const name = o && o.getName();
```
Or for caching values (when falsy values are invalid):
```js
const name = cachedName || (cachedName = getName());
```
For a comprehensive list of operators, see the [guide page](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators) or [reference section](/en-US/docs/Web/JavaScript/Reference/Operators). You may be especially interested in the [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence).
## Grammar
JavaScript grammar is very similar to the C family. There are a few points worth mentioning:
- [Identifiers](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) can have Unicode characters, but they cannot be one of the [reserved words](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords).
- [Comments](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#comments) are commonly `//` or `/* */`, while many other scripting languages like Perl, Python, and Bash use `#`.
- Semicolons are optional in JavaScript β the language [automatically inserts them](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) when needed. However, there are certain caveats to watch out for, since unlike Python, semicolons are still part of the syntax.
For an in-depth look at the JavaScript grammar, see the [reference page for lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar).
## Control structures
JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by [`if` and `else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else); you can chain them together:
```js
let name = "kittens";
if (name === "puppies") {
name += " woof";
} else if (name === "kittens") {
name += " meow";
} else {
name += "!";
}
name === "kittens meow";
```
JavaScript doesn't have `elif`, and `else if` is really just an `else` branch comprised of a single `if` statement.
JavaScript has [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while) loops and [`do...while`](/en-US/docs/Web/JavaScript/Reference/Statements/do...while) loops. The first is good for basic looping; the second is for loops where you wish to ensure that the body of the loop is executed at least once:
```js
while (true) {
// an infinite loop!
}
let input;
do {
input = get_input();
} while (inputIsNotValid(input));
```
JavaScript's [`for` loop](/en-US/docs/Web/JavaScript/Reference/Statements/for) is the same as that in C and Java: it lets you provide the control information for your loop on a single line.
```js
for (let i = 0; i < 5; i++) {
// Will execute 5 times
}
```
JavaScript also contains two other prominent for loops: [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of), which iterates over [iterables](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), most notably arrays, and [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in), which visits all [enumerable](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) properties of an object.
```js
for (const value of array) {
// do something with value
}
for (const property in object) {
// do something with object property
}
```
The `switch` statement can be used for multiple branches based on equality checking.
```js
switch (action) {
case "draw":
drawIt();
break;
case "eat":
eatIt();
break;
default:
doNothing();
}
```
Similar to C, case clauses are conceptually the same as [labels](/en-US/docs/Web/JavaScript/Reference/Statements/label), so if you don't add a `break` statement, execution will "fall through" to the next level. However, they are not actually jump tables β any expression can be part of the `case` clause, not just string or number literals, and they would be evaluated one-by-one until one equals the value being matched. Comparison takes place between the two using the `===` operator.
Unlike some languages like Rust, control-flow structures are statements in JavaScript, meaning you can't assign them to a variable, like `const a = if (x) { 1 } else { 2 }`.
JavaScript errors are handled using the [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement.
```js
try {
buildMySite("./website");
} catch (e) {
console.error("Building site failed:", e);
}
```
Errors can be thrown using the [`throw`](/en-US/docs/Web/JavaScript/Reference/Statements/throw) statement. Many built-in operations may throw as well.
```js
function buildMySite(siteDirectory) {
if (!pathExists(siteDirectory)) {
throw new Error("Site directory does not exist");
}
}
```
In general, you can't tell the type of the error you just caught, because anything can be thrown from a `throw` statement. However, you can usually assume it's an [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) instance, as is the example above. There are some subclasses of `Error` built-in, like [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) and [`RangeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError), that you can use to provide extra semantics about the error. There's no conditional catch in JavaScript β if you only want to handle one type of error, you need to catch everything, identify the type of error using [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof), and then rethrow the other cases.
```js
try {
buildMySite("./website");
} catch (e) {
if (e instanceof RangeError) {
console.error("Seems like a parameter is out of range:", e);
console.log("Retrying...");
buildMySite("./website");
} else {
// Don't know how to handle other error types; throw them so
// something else up in the call stack may catch and handle it
throw e;
}
}
```
If an error is uncaught by any `try...catch` in the call stack, the program will exit.
For a comprehensive list of control flow statements, see the [reference section](/en-US/docs/Web/JavaScript/Reference/Statements).
## Objects
JavaScript objects can be thought of as collections of key-value pairs. As such, they are similar to:
- Dictionaries in Python.
- Hashes in Perl and Ruby.
- Hash tables in C and C++.
- HashMaps in Java.
- Associative arrays in PHP.
JavaScript objects are hashes. Unlike objects in statically typed languages, objects in JavaScript do not have fixed shapes β properties can be added, deleted, re-ordered, mutated, or dynamically queried at any time. Object keys are always [strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or [symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) β even array indices, which are canonically integers, are actually strings under the hood.
Objects are usually created using the literal syntax:
```js
const obj = {
name: "Carrot",
for: "Max",
details: {
color: "orange",
size: 12,
},
};
```
Object properties can be [accessed](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) using dot (`.`) or square brackets (`[]`). When using the dot notation, the key must be a valid [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers). Square brackets, on the other hand, allow indexing the object with a dynamic key value.
```js
// Dot notation
obj.name = "Simon";
const name = obj.name;
// Bracket notation
obj["name"] = "Simon";
const name = obj["name"];
// Can use a variable to define a key
const userName = prompt("what is your key?");
obj[userName] = prompt("what is its value?");
```
Property access can be chained together:
```js
obj.details.color; // orange
obj["details"]["size"]; // 12
```
Objects are always references, so unless something is explicitly copying the object, mutations to an object would be visible to the outside.
```js
const obj = {};
function doSomething(o) {
o.x = 1;
}
doSomething(obj);
console.log(obj.x); // 1
```
This also means two separately created objects will never be equal (`!==`), because they are different references. If you hold two references of the same object, mutating one would be observable through the other.
```js
const me = {};
const stillMe = me;
me.x = 1;
console.log(stillMe.x); // 1
```
For more on objects and prototypes, see the [`Object` reference page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). For more information on the object initializer syntax, see its [reference page](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer).
This page has omitted all details about object prototypes and inheritance because you can usually achieve inheritance with [classes](#classes) without touching the underlying mechanism (which you may have heard to be abstruse). To learn about them, see [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
## Arrays
Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using `[]` syntax) but they have one magic property called `length`. This is always one more than the highest index in the array.
Arrays are usually created with array literals:
```js
const a = ["dog", "cat", "hen"];
a.length; // 3
```
JavaScript arrays are still objects β you can assign any properties to them, including arbitrary number indices. The only "magic" is that `length` will be automatically updated when you set a particular index.
```js
const a = ["dog", "cat", "hen"];
a[100] = "fox";
console.log(a.length); // 101
console.log(a); // ['dog', 'cat', 'hen', empty Γ 97, 'fox']
```
The array we got above is called a [_sparse array_](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) because there are uninhabited slots in the middle, and will cause the engine to deoptimize it from an array to a hash table. Make sure your array is densely populated!
Out-of-bounds indexing doesn't throw. If you query a non-existent array index, you'll get a value of `undefined` in return:
```js
const a = ["dog", "cat", "hen"];
console.log(typeof a[90]); // undefined
```
Arrays can have any elements and can grow or shrink arbitrarily.
```js
const arr = [1, "foo", true];
arr.push({});
// arr = [1, "foo", true, {}]
```
Arrays can be iterated with the `for` loop, as you can in other C-like languages:
```js
for (let i = 0; i < a.length; i++) {
// Do something with a[i]
}
```
Or, since arrays are iterable, you can use the [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, which is synonymous to C++/Java's `for (int x : arr)` syntax:
```js
for (const currentValue of a) {
// Do something with currentValue
}
```
Arrays come with a plethora of [array methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). Many of them would iterate the array β for example, [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) would apply a callback to every array element, and return a new array:
```js
const babies = ["dog", "cat", "hen"].map((name) => `baby ${name}`);
// babies = ['baby dog', 'baby cat', 'baby hen']
```
## Functions
Along with objects, functions are the core component in understanding JavaScript. The most basic function declaration looks like this:
```js
function add(x, y) {
const total = x + y;
return total;
}
```
A JavaScript function can take 0 or more parameters. The function body can contain as many statements as you like and can declare its own variables which are local to that function. The [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns `undefined`.
Functions can be called with more or fewer parameters than it specifies. If you call a function without passing the parameters it expects, they will be set to `undefined`. If you pass more parameters than it expects, the function will ignore the extra parameters.
```js
add(); // NaN
// Equivalent to add(undefined, undefined)
add(2, 3, 4); // 5
// added the first two; 4 was ignored
```
There are a number of other parameter syntaxes available. For example, the [rest parameter syntax](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) allows collecting all the extra parameters passed by the caller into an array, similar to Python's `*args`. (Since JS doesn't have named parameters on the language level, there's no `**kwargs`.)
```js
function avg(...args) {
let sum = 0;
for (const item of args) {
sum += item;
}
return sum / args.length;
}
avg(2, 3, 4, 5); // 3.5
```
In the above code, the variable `args` holds all the values that were passed into the function.
The rest parameter will store all arguments _after_ where it's declared, but not before. In other words, `function avg(firstValue, ...args)` will store the first value passed into the function in the `firstValue` variable and the remaining arguments in `args`.
If a function accepts a list of arguments and you already hold them in an array, you can use the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) in the function call to _spread_ the array as a list of elements. For instance: `avg(...numbers)`.
We mentioned that JavaScript doesn't have named parameters. It's possible, though, to implement them using [object destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), which allows objects to be conveniently packed and unpacked.
```js
// Note the { } braces: this is destructuring an object
function area({ width, height }) {
return width * height;
}
// The { } braces here create a new object
console.log(area({ width: 2, height: 3 }));
```
There's also the [_default parameter_](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) syntax, which allows omitted parameters (or those passed as `undefined`) to have a default value.
```js
function avg(firstValue, secondValue, thirdValue = 0) {
return (firstValue + secondValue + thirdValue) / 3;
}
avg(1, 2); // 1, instead of NaN
```
### Anonymous functions
JavaScript lets you create anonymous functions β that is, functions without names. In practice, anonymous functions are typically used as arguments to other functions, immediately assigned to a variable that can be used to invoke the function, or returned from another function.
```js
// Note that there's no function name before the parentheses
const avg = function (...args) {
let sum = 0;
for (const item of args) {
sum += item;
}
return sum / args.length;
};
```
That makes the anonymous function invocable by calling `avg()` with some arguments β that is, it's semantically equivalent to declaring the function using the `function avg() {}` declaration syntax.
There's another way to define anonymous functions β using an [arrow function expression](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
```js
// Note that there's no function name before the parentheses
const avg = (...args) => {
let sum = 0;
for (const item of args) {
sum += item;
}
return sum / args.length;
};
// You can omit the `return` when simply returning an expression
const sum = (a, b, c) => a + b + c;
```
Arrow functions are not semantically equivalent to function expressions β for more information, see its [reference page](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
There's another way that anonymous functions can be useful: it can be simultaneously declared and invoked in a single expression, called an [Immediately invoked function expression (IIFE)](/en-US/docs/Glossary/IIFE):
```js
(function () {
// β¦
})();
```
For use-cases of IIFEs, you can read [emulating private methods with closures](/en-US/docs/Web/JavaScript/Closures#emulating_private_methods_with_closures).
### Recursive functions
JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.
```js
function countChars(elm) {
if (elm.nodeType === 3) {
// TEXT_NODE
return elm.nodeValue.length;
}
let count = 0;
for (let i = 0, child; (child = elm.childNodes[i]); i++) {
count += countChars(child);
}
return count;
}
```
Function expressions can be named as well, which allows them to be recursive.
```js
const charsInBody = (function counter(elm) {
if (elm.nodeType === 3) {
// TEXT_NODE
return elm.nodeValue.length;
}
let count = 0;
for (let i = 0, child; (child = elm.childNodes[i]); i++) {
count += counter(child);
}
return count;
})(document.body);
```
The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.
If you are used to functional programming, beware of the performance implications of recursion in JavaScript. Although the language specification specifies [tail-call optimization](https://en.wikipedia.org/wiki/Tail_call), only JavaScriptCore (used by Safari) has implemented it, due to the difficulty of recovering stack traces and debuggability. For deep recursion, consider using iteration instead to avoid stack overflow.
### Functions are first-class objects
JavaScript functions are first-class objects. This means that they can be assigned to variables, passed as arguments to other functions, and returned from other functions. In addition, JavaScript supports [closures](/en-US/docs/Web/JavaScript/Closures) out-of-the-box without explicit capturing, allowing you to conveniently apply functional programming styles.
```js
// Function returning function
const add = (x) => (y) => x + y;
// Function accepting function
const babies = ["dog", "cat", "hen"].map((name) => `baby ${name}`);
```
Note that JavaScript functions are themselves objects β like everything else in JavaScript β and you can add or change properties on them just like we've seen earlier in the Objects section.
### Inner functions
JavaScript function declarations are allowed inside other functions. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:
```js
function parentFunc() {
const a = 1;
function nestedFunc() {
const b = 4; // parentFunc can't use this
return a + b;
}
return nestedFunc(); // 5
}
```
This provides a great deal of utility in writing more maintainable code. If a called function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside it. This keeps the number of functions that are in the global scope down.
This is also a great counter to the lure of global variables. When writing complex code, it is often tempting to use global variables to share values between multiple functions, which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together without polluting your global namespace.
## Classes
JavaScript offers the [class](/en-US/docs/Web/JavaScript/Reference/Classes) syntax that's very similar to languages like Java.
```js
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
return `Hello, I'm ${this.name}!`;
}
}
const p = new Person("Maria");
console.log(p.sayHello());
```
JavaScript classes are just functions that must be instantiated with the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator. Every time a class is instantiated, it returns an object containing the methods and properties that the class specified. Classes don't enforce any code organization β for example, you can have functions returning classes, or you can have multiple classes per file. Here's an example of how ad hoc the creation of a class can be: it's just an expression returned from an arrow function. This pattern is called a [mixin](/en-US/docs/Web/JavaScript/Reference/Classes/extends#mix-ins).
```js
const withAuthentication = (cls) =>
class extends cls {
authenticate() {
// β¦
}
};
class Admin extends withAuthentication(Person) {
// β¦
}
```
Static properties are created by prepending `static`. Private properties are created by prepending a hash `#` (not `private`). The hash is an integral part of the property name. (Think about `#` as `_` in Python.) Unlike most other languages, there's absolutely no way to read a private property outside the class body β not even in derived classes.
For a detailed guide on various class features, you can read the [guide page](/en-US/docs/Web/JavaScript/Guide/Using_classes).
## Asynchronous programming
JavaScript is single-threaded by nature. There's no [paralleling](https://en.wikipedia.org/wiki/Parallel_computing); only [concurrency](https://en.wikipedia.org/wiki/Concurrent_computing). Asynchronous programming is powered by an [event loop](/en-US/docs/Web/JavaScript/Event_loop), which allows a set of tasks to be queued and polled for completion.
There are three idiomatic ways to write asynchronous code in JavaScript:
- Callback-based (such as [`setTimeout()`](/en-US/docs/Web/API/setTimeout))
- [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)-based
- [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function)/[`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await), which is a syntactic sugar for Promises
For example, here's what a file-read operation might look like in JavaScript:
```js
// Callback-based
fs.readFile(filename, (err, content) => {
// This callback is invoked when the file is read, which could be after a while
if (err) {
throw err;
}
console.log(content);
});
// Code here will be executed while the file is waiting to be read
// Promise-based
fs.readFile(filename)
.then((content) => {
// What to do when the file is read
console.log(content);
})
.catch((err) => {
throw err;
});
// Code here will be executed while the file is waiting to be read
// Async/await
async function readFile(filename) {
const content = await fs.readFile(filename);
console.log(content);
}
```
The core language doesn't specify any asynchronous programming features, but it's crucial when interacting with the external environment β from [asking user permissions](/en-US/docs/Web/API/Permissions_API), to [fetching data](/en-US/docs/Web/API/Fetch_API/Using_Fetch), to [reading files](https://nodejs.org/api/fs.html). Keeping the potentially long-running operations async ensures that other processes can still run while this one waits β for example, the browser will not freeze while waiting for the user to click a button to grant permission.
If you have an async value, it's not possible to get its value synchronously. For example, if you have a promise, you can only access the eventual result via the [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) method. Similarly, [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) can only be used in an async context, which is usually an async function or a module. Promises are _never blocking_ β only the logic depending on the promise's result will be deferred; everything else continues to execute in the meantime. If you are a functional programmer, you may recognize promises as [monads](<https://en.wikipedia.org/wiki/Monad_(functional_programming)>) which can be mapped with `then()` (however, they are not _proper_ monads because they auto-flatten; i.e. you can't have a `Promise<Promise<T>>`).
In fact, the single-threaded model has made Node.js a popular choice for server-side programming due to its non-blocking IO, making handling a large number of database or file-system requests very performant. However, CPU-bound (computationally intensive) tasks that are pure JavaScript will still block the main thread. To achieve real paralleling, you may need to use [workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers).
To learn more about asynchronous programming, you can read about [using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) or follow the [asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) tutorial.
## Modules
JavaScript also specifies a module system supported by most runtimes. A module is usually a file, identified by its file path or URL. You can use the [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) and [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) statements to exchange data between modules:
```js
import { foo } from "./foo.js";
// Unexported variables are local to the module
const b = 2;
export const a = 1;
```
Unlike Haskell, Python, Java, etc., JavaScript module resolution is entirely host-defined β it's usually based on URLs or file paths, so relative file paths "just work" and are relative to the current module's path instead of some project root path.
However, the JavaScript language doesn't offer standard library modules β all core functionalities are powered by global variables like [`Math`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) and [`Intl`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) instead. This is due to the long history of JavaScript lacking a module system, and the fact that opting into the module system involves some changes to the runtime setup.
Different runtimes may use different module systems. For example, [Node.js](https://nodejs.org/en/) uses the package manager [npm](https://www.npmjs.com/) and is mostly file-system based, while [Deno](https://deno.land/) and browsers are fully URL-based and modules can be resolved from HTTP URLs.
For more information, see the [modules guide page](/en-US/docs/Web/JavaScript/Guide/Modules).
## Language and runtime
Throughout this page, we've constantly mentioned that certain features are _language-level_ while others are _runtime-level_.
JavaScript is a general-purpose scripting language. The [core language specification](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview#javascript_the_core_language_ecmascript) focuses on pure computational logic. It doesn't deal with any input/output β in fact, without extra runtime-level APIs (most notably [`console.log()`](/en-US/docs/Web/API/console/log_static)), a JavaScript program's behavior is entirely unobservable.
A runtime, or a host, is something that feeds data to the JavaScript engine (the interpreter), provides extra global properties, and provides hooks for the engine to interact with the outside world. Module resolution, reading data, printing messages, sending network requests, etc. are all runtime-level operations. Since its inception, JavaScript has been adopted in various environments, such as browsers (which provide APIs like [DOM](/en-US/docs/Web/API/Document_Object_Model)), Node.js (which provides APIs like [file system access](https://nodejs.org/api/fs.html)), etc. JavaScript has been successfully integrated in web (which was its primary purpose), mobile apps, desktop apps, server-side apps, serverless, embedded systems, and more. While you learn about JavaScript core features, it's also important to understand host-provided features in order to put the knowledge to use. For example, you can read about all [web platform APIs](/en-US/docs/Web/API), which are implemented by browsers, and sometimes non-browsers.
## Further exploration
This page offers a very basic insight into how various JavaScript features compare with other languages. If you want to learn more about the language itself and the nuances of each feature, you can read the [JavaScript guide](/en-US/docs/Web/JavaScript/Guide) and the [JavaScript reference](/en-US/docs/Web/JavaScript/Reference).
There are some essential parts of the language that we have omitted due to space and complexity, but you can explore on your own:
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
- [Closures](/en-US/docs/Web/JavaScript/Closures)
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
- [Iteration](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators)
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/guide/index.md | ---
title: JavaScript Guide
slug: Web/JavaScript/Guide
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
The JavaScript Guide shows you how to use [JavaScript](/en-US/docs/Web/JavaScript) and gives an overview of the language. If you need exhaustive information about a language feature, have a look at the [JavaScript reference](/en-US/docs/Web/JavaScript/Reference).
This Guide is divided into the following chapters.
## Introduction
Overview: [Introduction](/en-US/docs/Web/JavaScript/Guide/Introduction)
- [About this guide](/en-US/docs/Web/JavaScript/Guide/Introduction#where_to_find_javascript_information)
- [About JavaScript](/en-US/docs/Web/JavaScript/Guide/Introduction#what_is_javascript)
- [JavaScript and Java](/en-US/docs/Web/JavaScript/Guide/Introduction#javascript_and_java)
- [ECMAScript](/en-US/docs/Web/JavaScript/Guide/Introduction#javascript_and_the_ecmascript_specification)
- [Tools](/en-US/docs/Web/JavaScript/Guide/Introduction#getting_started_with_javascript)
- [Hello World](/en-US/docs/Web/JavaScript/Guide/Introduction#hello_world)
## Grammar and types
Overview: [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types)
- [Basic syntax & comments](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#basics)
- [Declarations](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations)
- [Variable scope](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_scope)
- [Variable hoisting](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_hoisting)
- [Data structures and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#data_structures_and_types)
- [Literals](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#literals)
## Control flow and error handling
Overview: [Control flow and error handling](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling)
- [`if...else`](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement)
- [`switch`](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement)
- [`try`/`catch`/`throw`](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements)
- [Error objects](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#utilizing_error_objects)
## Loops and iteration
Overview: [Loops and iteration](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
- [`for`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement)
- [`while`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement)
- [`do...while`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement)
- [`continue`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement)
- [`break`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement)
- [`for...in`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement)
- [`for...of`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement)
## Functions
Overview: [Functions](/en-US/docs/Web/JavaScript/Guide/Functions)
- [Defining functions](/en-US/docs/Web/JavaScript/Guide/Functions#defining_functions)
- [Calling functions](/en-US/docs/Web/JavaScript/Guide/Functions#calling_functions)
- [Function scope](/en-US/docs/Web/JavaScript/Guide/Functions#function_scope)
- [Closures](/en-US/docs/Web/JavaScript/Guide/Functions#closures)
- [Arguments](/en-US/docs/Web/JavaScript/Guide/Functions#using_the_arguments_object) & [parameters](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters)
- [Arrow functions](/en-US/docs/Web/JavaScript/Guide/Functions#arrow_functions)
## Expressions and operators
Overview: [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators)
- [Assignment](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators) & [Comparisons](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#comparison_operators)
- [Arithmetic operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#arithmetic_operators)
- [Bitwise](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators) & [logical operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#logical_operators)
- [Conditional (ternary) operator](</en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#conditional_(ternary)_operator>)
## Numbers and dates
Overview: [Numbers and dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates)
- [Number literals](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#numbers)
- [`Number` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#number_object)
- [`Math` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#math_object)
- [`Date` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#date_object)
## Text formatting
Overview: [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting)
- [String literals](/en-US/docs/Web/JavaScript/Guide/Text_formatting#string_literals)
- [`String` object](/en-US/docs/Web/JavaScript/Guide/Text_formatting#string_objects)
- [Template literals](/en-US/docs/Web/JavaScript/Guide/Text_formatting#multi-line_template_literals)
- [Internationalization](/en-US/docs/Web/JavaScript/Guide/Text_formatting#internationalization)
- [Regular Expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
## Indexed collections
Overview: [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections)
## Keyed collections
Overview: [Keyed collections](/en-US/docs/Web/JavaScript/Guide/Keyed_collections)
- [`Map`](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#map_object)
- [`WeakMap`](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object)
- [`Set`](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#set_object)
- [`WeakSet`](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakset_object)
## Working with objects
Overview: [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects)
- [Objects and properties](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#objects_and_properties)
- [Creating objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#creating_new_objects)
- [Defining methods](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_methods)
- [Getter and setter](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#defining_getters_and_setters)
## Using classes
Overview: [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes)
- [Declaring a class](/en-US/docs/Web/JavaScript/Guide/Using_classes#declaring_a_class)
- [Various class features](/en-US/docs/Web/JavaScript/Guide/Using_classes#constructor)
- [Extends and inheritance](/en-US/docs/Web/JavaScript/Guide/Using_classes#extends_and_inheritance)
- [Why classes?](/en-US/docs/Web/JavaScript/Guide/Using_classes#why_classes)
## Promises
Overview: [Promises](/en-US/docs/Web/JavaScript/Guide/Using_promises)
- [Guarantees](/en-US/docs/Web/JavaScript/Guide/Using_promises#guarantees)
- [Chaining](/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining)
- [Error handling](/en-US/docs/Web/JavaScript/Guide/Using_promises#error_handling)
- [Composition](/en-US/docs/Web/JavaScript/Guide/Using_promises#composition)
- [Timing](/en-US/docs/Web/JavaScript/Guide/Using_promises#timing)
## Typed arrays
Overview: [Typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays)
## Iterators and generators
Overview: [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators)
- [Iterators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#iterators)
- [Iterables](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#iterables)
- [Generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#generator_functions)
## Meta programming
Overview: [Meta programming](/en-US/docs/Web/JavaScript/Guide/Meta_programming)
- [`Proxy`](/en-US/docs/Web/JavaScript/Guide/Meta_programming#proxies)
- [Handlers and traps](/en-US/docs/Web/JavaScript/Guide/Meta_programming#handlers_and_traps)
- [Revocable Proxy](/en-US/docs/Web/JavaScript/Guide/Meta_programming#revocable_proxy)
- [`Reflect`](/en-US/docs/Web/JavaScript/Guide/Meta_programming#reflection)
## JavaScript modules
Overview: [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules)
- [Exporting](/en-US/docs/Web/JavaScript/Guide/Modules#exporting_module_features)
- [Importing](/en-US/docs/Web/JavaScript/Guide/Modules#importing_features_into_your_script)
- [Default exports](/en-US/docs/Web/JavaScript/Guide/Modules#default_exports_versus_named_exports)
- [Renaming features](/en-US/docs/Web/JavaScript/Guide/Modules#renaming_imports_and_exports)
- [Aggregating modules](/en-US/docs/Web/JavaScript/Guide/Modules#aggregating_modules)
- [Dynamic module loading](/en-US/docs/Web/JavaScript/Guide/Modules#dynamic_module_loading)
{{Next("Web/JavaScript/Guide/Introduction")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/loops_and_iteration/index.md | ---
title: Loops and iteration
slug: Web/JavaScript/Guide/Loops_and_iteration
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
Loops offer a quick and easy way to do something repeatedly. This
chapter of the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide)
introduces the different iteration statements available to JavaScript.
You can think of a loop as a computerized version of the game where you tell someone to
take _X_ steps in one direction, then _Y_ steps in another. For example,
the idea "Go five steps to the east" could be expressed this way as a loop:
```js
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log("Walking east one step");
}
```
There are many different kinds of loops, but they all essentially do the same thing:
they repeat an action some number of times. (Note that it's possible that number could
be zero!)
The various loop mechanisms offer different ways to determine the start and end points
of the loop. There are various situations that are more easily served by one type of
loop over the others.
The statements for loops provided in JavaScript are:
- [for statement](#for_statement)
- [do...while statement](#do...while_statement)
- [while statement](#while_statement)
- [labeled statement](#labeled_statement)
- [break statement](#break_statement)
- [continue statement](#continue_statement)
- [for...in statement](#for...in_statement)
- [for...of statement](#for...of_statement)
## for statement
A {{jsxref("Statements/for", "for")}} loop repeats until a specified condition evaluates to false. The JavaScript `for` loop is similar to the Java and C `for` loop.
A `for` statement looks as follows:
```js-nolint
for (initialization; condition; afterthought)
statement
```
When a `for` loop executes, the following occurs:
1. The initializing expression `initialization`, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
2. The `condition` expression is evaluated. If the value of `condition` is true, the loop statements execute. Otherwise, the `for` loop terminates. (If the `condition` expression is omitted entirely, the condition is assumed to be true.)
3. The `statement` executes. To execute multiple statements, use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) (`{ }`) to group those statements.
4. If present, the update expression `afterthought` is executed.
5. Control returns to Step 2.
### Example
In the example below, the function contains a `for` statement that counts
the number of selected options in a scrolling list (a [`<select>`](/en-US/docs/Web/HTML/Element/select)
element that allows multiple selections).
#### HTML
```html
<form name="selectForm">
<label for="musicTypes"
>Choose some music types, then click the button below:</label
>
<select id="musicTypes" name="musicTypes" multiple>
<option selected>R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
<button id="btn" type="button">How many are selected?</button>
</form>
```
#### JavaScript
Here, the `for` statement declares the variable `i` and initializes it to `0`. It checks that `i` is less than the number of options in the `<select>` element, performs the succeeding `if` statement, and increments `i` by 1 after each pass through the loop.
```js
function countSelected(selectObject) {
let numberSelected = 0;
for (let i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
const musicTypes = document.selectForm.musicTypes;
console.log(`You have selected ${countSelected(musicTypes)} option(s).`);
});
```
## do...while statement
The {{jsxref("statements/do...while", "do...while")}} statement repeats until a
specified condition evaluates to false.
A `do...while` statement looks as follows:
```js-nolint
do
statement
while (condition);
```
`statement` is always executed once before the condition is
checked. (To execute multiple statements, use a block statement (`{ }`)
to group those statements.)
If `condition` is `true`, the statement executes again. At the
end of every execution, the condition is checked. When the condition is
`false`, execution stops, and control passes to the statement following
`do...while`.
### Example
In the following example, the `do` loop iterates at least once and
reiterates until `i` is no longer less than `5`.
```js
let i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
```
## while statement
A {{jsxref("Statements/while", "while")}} statement executes its statements as long as a
specified condition evaluates to `true`. A `while` statement looks
as follows:
```js-nolint
while (condition)
statement
```
If the `condition` becomes `false`,
`statement` within the loop stops executing and control passes to the
statement following the loop.
The condition test occurs _before_ `statement` in the loop is
executed. If the condition returns `true`, `statement` is executed
and the `condition` is tested again. If the condition returns
`false`, execution stops, and control is passed to the statement following
`while`.
To execute multiple statements, use a block statement (`{ }`) to group
those statements.
### Example 1
The following `while` loop iterates as long as `n` is
less than `3`:
```js
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
```
With each iteration, the loop increments `n` and adds that value to
`x`. Therefore, `x` and `n` take on the following
values:
- After the first pass: `n` = `1` and `x` =
`1`
- After the second pass: `n` = `2` and `x` =
`3`
- After the third pass: `n` = `3` and `x` =
`6`
After completing the third pass, the condition `n < 3` is no longer
`true`, so the loop terminates.
### Example 2
Avoid infinite loops. Make sure the condition in a loop eventually becomes
`false`βotherwise, the loop will never terminate! The statements in the
following `while` loop execute forever because the condition never becomes
`false`:
```js example-bad
// Infinite loops are bad!
while (true) {
console.log("Hello, world!");
}
```
## labeled statement
A {{jsxref("Statements/label", "label")}} provides a statement with an identifier that
lets you refer to it elsewhere in your program. For example, you can use a label to
identify a loop, and then use the `break` or `continue` statements
to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the labeled statement looks like the following:
```js-nolint
label:
statement
```
The value of `label` may be any JavaScript identifier that is not a
reserved word. The `statement` that you identify with a label may be
any statement. For examples of using labeled statements, see the examples of `break` and `continue` below.
## break statement
Use the {{jsxref("Statements/break", "break")}} statement to terminate a loop,
`switch`, or in conjunction with a labeled statement.
- When you use `break` without a label, it terminates the innermost
enclosing `while`, `do-while`, `for`, or
`switch` immediately and transfers control to the following statement.
- When you use `break` with a label, it terminates the specified labeled
statement.
The syntax of the `break` statement looks like this:
```js-nolint
break;
break label;
```
1. The first form of the syntax terminates the innermost enclosing loop or `switch`.
2. The second form of the syntax terminates the specified enclosing labeled statement.
### Example 1
The following example iterates through the elements in an array until it finds the
index of an element whose value is `theValue`:
```js
for (let i = 0; i < a.length; i++) {
if (a[i] === theValue) {
break;
}
}
```
### Example 2: Breaking to a label
```js
let x = 0;
let z = 0;
labelCancelLoops: while (true) {
console.log("Outer loops:", x);
x += 1;
z = 1;
while (true) {
console.log("Inner loops:", z);
z += 1;
if (z === 10 && x === 10) {
break labelCancelLoops;
} else if (z === 10) {
break;
}
}
}
```
## continue statement
The {{jsxref("Statements/continue", "continue")}} statement can be used to restart a
`while`, `do-while`, `for`, or `label`
statement.
- When you use `continue` without a label, it terminates the current
iteration of the innermost enclosing `while`, `do-while`, or
`for` statement and continues execution of the loop with the next
iteration. In contrast to the `break` statement, `continue` does
not terminate the execution of the loop entirely. In a `while` loop, it
jumps back to the condition. In a `for` loop, it jumps to the
`increment-expression`.
- When you use `continue` with a label, it applies to the looping statement
identified with that label.
The syntax of the `continue` statement looks like the following:
```js-nolint
continue;
continue label;
```
### Example 1
The following example shows a `while` loop with a `continue`
statement that executes when the value of `i` is `3`. Thus,
`n` takes on the values `1`, `3`, `7`, and
`12`.
```js
let i = 0;
let n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
console.log(n);
}
// Logs:
// 1 3 7 12
```
If you comment out the `continue;`, the loop would run till the end and you would see `1,3,6,10,15`.
### Example 2
A statement labeled `checkiandj` contains a statement labeled
`checkj`. If `continue` is encountered, the program
terminates the current iteration of `checkj` and begins the next
iteration. Each time `continue` is encountered, `checkj`
reiterates until its condition returns `false`. When `false` is
returned, the remainder of the `checkiandj` statement is completed,
and `checkiandj` reiterates until its condition returns
`false`. When `false` is returned, the program continues at the
statement following `checkiandj`.
If `continue` had a label of `checkiandj`, the program
would continue at the top of the `checkiandj` statement.
```js
let i = 0;
let j = 10;
checkiandj: while (i < 4) {
console.log(i);
i += 1;
checkj: while (j > 4) {
console.log(j);
j -= 1;
if (j % 2 === 0) {
continue checkj;
}
console.log(j, "is odd.");
}
console.log("i =", i);
console.log("j =", j);
}
```
## for...in statement
The {{jsxref("Statements/for...in", "for...in")}} statement iterates a specified
variable over all the enumerable properties of an object. For each distinct property,
JavaScript executes the specified statements. A `for...in` statement looks as
follows:
```js-nolint
for (variable in object)
statement
```
### Example
The following function takes as its argument an object and the object's name. It then
iterates over all the object's properties and returns a string that lists the property
names and their values.
```js
function dumpProps(obj, objName) {
let result = "";
for (const i in obj) {
result += `${objName}.${i} = ${obj[i]}<br>`;
}
result += "<hr>";
return result;
}
```
For an object `car` with properties `make` and `model`, `result` would be:
```plain
car.make = Ford
car.model = Mustang
```
### Arrays
Although it may be tempting to use this as a way to iterate over {{jsxref("Array")}}
elements, the `for...in` statement will return the name of your user-defined
properties in addition to the numeric indexes.
Therefore, it is better to use a traditional {{jsxref("Statements/for", "for")}} loop
with a numeric index when iterating over arrays, because the `for...in`
statement iterates over user-defined properties in addition to the array elements, if
you modify the Array object (such as adding custom properties or methods).
## for...of statement
The {{jsxref("Statements/for...of", "for...of")}} statement creates a loop Iterating
over [iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) (including
{{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}},
{{jsxref("Functions/arguments", "arguments")}} object and so on), invoking a custom
iteration hook with statements to be executed for the value of each distinct property.
```js-nolint
for (variable of object)
statement
```
The following example shows the difference between a `for...of` loop and a
{{jsxref("Statements/for...in", "for...in")}} loop. While `for...in` iterates
over property names, `for...of` iterates over property values:
```js
const arr = [3, 5, 7];
arr.foo = "hello";
for (const i in arr) {
console.log(i);
}
// "0" "1" "2" "foo"
for (const i of arr) {
console.log(i);
}
// Logs: 3 5 7
```
The `for...of` and `for...in` statements can also be used with [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). For example, you can simultaneously loop over the keys and values of an object using {{jsxref("Object.entries()")}}.
```js
const obj = { foo: 1, bar: 2 };
for (const [key, val] of Object.entries(obj)) {
console.log(key, val);
}
// "foo" 1
// "bar" 2
```
{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/working_with_objects/index.md | ---
title: Working with objects
slug: Web/JavaScript/Guide/Working_with_objects
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Keyed_collections", "Web/JavaScript/Guide/Using_classes")}}
JavaScript is designed on a simple object-based paradigm. An object is a collection of [properties](/en-US/docs/Glossary/Property/JavaScript), and a property is an association between a name (or _key_) and a value. A property's value can be a function, in which case the property is known as a [method](/en-US/docs/Glossary/Method).
Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.
In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, and methods, and how to create your own objects.
## Creating new objects
You can create an object using an [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the `new` operator.
### Using object initializers
Object initializers are also called _object literals_. "Object initializer" is consistent with the terminology used by C++.
The syntax for an object using an object initializer is:
```js
const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
"property n": value3, // or a string
};
```
Each property name before colons is an identifier (either a name, a number, or a string literal), and each `valueN` is an expression whose value is assigned to the property name. The property name can also be an expression; computed keys need to be wrapped in square brackets. The [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) reference contains a more detailed explanation of the syntax.
In this example, the newly created object is assigned to a variable `obj` β this is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)
Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that do not compare to each other as equal.
The following statement creates an object and assigns it to the variable `x` if and only if the expression `cond` is true:
```js
let x;
if (cond) {
x = { greeting: "hi there" };
}
```
The following example creates `myHonda` with three properties. Note that the `engine` property is also an object with its own properties.
```js
const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
```
Objects created with initializers are called _plain objects_, because they are instances of {{jsxref("Object")}}, but not any other object type. Some object types have special initializer syntaxes β for example, [array initializers](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) and [regex literals](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#creating_a_regular_expression).
### Using a constructor function
Alternatively, you can create an object with these two steps:
1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
2. Create an instance of the object with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new).
To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, 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:
```js
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
```
Notice the use of `this` to assign values to the object's properties based on the values passed to the function.
Now you can create an object called `myCar` as follows:
```js
const myCar = new Car("Eagle", "Talon TSi", 1993);
```
This statement creates `myCar` and assigns it the specified values for its properties. Then the value of `myCar.make` is the string `"Eagle"`, `myCar.model` is the string `"Talon TSi"`, `myCar.year` is the integer `1993`, and so on. The order of arguments and parameters should be the same.
You can create any number of `Car` objects by calls to `new`. For example,
```js
const kenscar = new Car("Nissan", "300ZX", 1992);
const vpgscar = new Car("Mazda", "Miata", 1990);
```
An object can have a property that is itself another object. For example, suppose you define an object called `Person` as follows:
```js
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
```
and then instantiate two new `Person` objects as follows:
```js
const rand = new Person("Rand McKinnon", 33, "M");
const ken = new Person("Ken Jones", 39, "M");
```
Then, you can rewrite the definition of `Car` to include an `owner` property that takes a `Person` object, as follows:
```js
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
```
To instantiate the new objects, you then use the following:
```js
const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);
```
Notice that 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 arguments for the owners. Then if you want to find out the name of the owner of `car2`, you can access the following property:
```js
car2.owner.name;
```
You can always add a property to a previously defined object. For example, the statement
```js
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 have to add the property to the definition of the `Car` object type.
You can also use the [`class`](/en-US/docs/Web/JavaScript/Reference/Classes) syntax instead of the `function` syntax to define a constructor function. For more information, see the [class guide](/en-US/docs/Web/JavaScript/Guide/Using_classes).
### Using the Object.create() method
Objects can also be created using the {{jsxref("Object.create()")}} method. This method can be very useful, because it allows you to choose the [prototype](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) object for the object you want to create, without having to define a constructor function.
```js
// Animal properties and method encapsulation
const Animal = {
type: "Invertebrates", // Default value of properties
displayType() {
// Method which will display type of Animal
console.log(this.type);
},
};
// Create new animal type called animal1
const animal1 = Object.create(Animal);
animal1.displayType(); // Logs: Invertebrates
// Create new animal type called fish
const fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Logs: Fishes
```
## Objects and properties
A JavaScript object has properties associated with it. Object properties are basically the same as variables, except that they are associated with objects, not [scopes](/en-US/docs/Glossary/Scope). The properties of an object define the characteristics of the object.
For example, this example creates an object named `myCar`, with properties named `make`, `model`, and `year`, with their values set to `"Ford"`, `"Mustang"`, and `1969`:
```js
const myCar = {
make: "Ford",
model: "Mustang",
year: 1969,
};
```
Like JavaScript variables, property names are case sensitive. Property names can only be strings or Symbols β all keys are [converted to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) unless they are Symbols. [Array indices](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices) are, in fact, properties with string keys that contain integers.
### Accessing properties
You can access a property of an object by its property name. [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) come in two syntaxes: _dot notation_ and _bracket notation_. For example, you could access the properties of the `myCar` object as follows:
```js
// Dot notation
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
// Bracket notation
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
```
An object property name can be any JavaScript string or [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), including an empty string. However, you cannot use dot notation to access a property whose name is not a valid JavaScript identifier. For example, a property name that has a space or a hyphen, that starts with a number, or that is held inside a variable can only be accessed using the bracket notation. This notation is also very useful when property names are to be dynamically determined, i.e. not determinable until runtime. Examples are as follows:
```js
const myObj = {};
const str = "myString";
const rand = Math.random();
const anotherObj = {};
// Create additional properties on myObj
myObj.type = "Dot syntax for a key named type";
myObj["date created"] = "This key has a space";
myObj[str] = "This key is in variable str";
myObj[rand] = "A random number is the key here";
myObj[anotherObj] = "This key is object anotherObj";
myObj[""] = "This key is an empty string";
console.log(myObj);
// {
// type: 'Dot syntax for a key named type',
// 'date created': 'This key has a space',
// myString: 'This key is in variable str',
// '0.6398914448618778': 'A random number is the key here',
// '[object Object]': 'This key is object anotherObj',
// '': 'This key is an empty string'
// }
console.log(myObj.myString); // 'This key is in variable str'
```
In the above code, the key `anotherObj` is an object, which is neither a string nor a symbol. When it is added to the `myObj`, JavaScript calls the {{jsxref("Object/toString", "toString()")}} method of `anotherObj`, and use the resulting string as the new key.
You can also access properties with a string value stored in a variable. The variable must be passed in bracket notation. In the example above, the variable `str` held `"myString"` and it is `"myString"` that is the property name. Therefore, `myObj.str` will return as undefined.
```js
str = "myString";
myObj[str] = "This key is in variable str";
console.log(myObj.str); // undefined
console.log(myObj[str]); // 'This key is in variable str'
console.log(myObj.myString); // 'This key is in variable str'
```
This allows accessing any property as determined at runtime:
```js
let propertyName = "make";
myCar[propertyName] = "Ford";
// access different properties by changing the contents of the variable
propertyName = "model";
myCar[propertyName] = "Mustang";
console.log(myCar); // { make: 'Ford', model: 'Mustang' }
```
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](https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md).
Nonexistent properties of an object have value {{jsxref("undefined")}} (and not [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)).
```js
myCar.nonexistentProperty; // undefined
```
### Enumerating properties
There are three native ways to list/traverse object properties:
- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops. This method traverses all of the enumerable string properties of an object as well as its prototype chain.
- {{jsxref("Object.keys()")}}. This method returns an array with only the enumerable own string property names ("keys") in the object `myObj`, but not those in the prototype chain.
- {{jsxref("Object.getOwnPropertyNames()")}}. This method returns an array containing all the own string property names in the object `myObj`, regardless of if they are enumerable or not.
You can use the bracket notation with [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:
```js
function showProps(obj, objName) {
let result = "";
for (const i in obj) {
// Object.hasOwn() is used to exclude properties from the object's
// prototype chain and only show "own properties"
if (Object.hasOwn(obj, i)) {
result += `${objName}.${i} = ${obj[i]}\n`;
}
}
console.log(result);
}
```
The term "own property" refers to the properties of the object, but excluding those of the prototype chain. So, the function call `showProps(myCar, 'myCar')` would print the following:
```plain
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
```
The above is equivalent to:
```js
function showProps(obj, objName) {
let result = "";
Object.keys(obj).forEach((i) => {
result += `${objName}.${i} = ${obj[i]}\n`;
});
console.log(result);
}
```
There is no native way to list inherited non-enumerable properties. However, this can be achieved with the following function:
```js
function listAllProperties(myObj) {
let objectToInspect = myObj;
let result = [];
while (objectToInspect !== null) {
result = result.concat(Object.getOwnPropertyNames(objectToInspect));
objectToInspect = Object.getPrototypeOf(objectToInspect);
}
return result;
}
```
For more information, see [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties).
### Deleting properties
You can remove a non-inherited property using the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator. The following code shows how to remove a property.
```js
// Creates a new object, myobj, with two properties, a and b.
const myobj = new Object();
myobj.a = 5;
myobj.b = 12;
// Removes the a property, leaving myobj with only the b property.
delete myobj.a;
console.log("a" in myobj); // false
```
## Inheritance
All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the `prototype` object of the constructor. See [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) for more information.
### Defining properties for all objects of one type
You can add a property to all objects created through a certain [constructor](#using_a_constructor_function) using the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a `color` property to all objects of type `Car`, and then reads the property's value from an instance `car1`.
```js
Car.prototype.color = "red";
console.log(car1.color); // "red"
```
## Defining methods
A _method_ is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also [method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) for more details. An example is:
```js
objectName.methodName = functionName;
const myObj = {
myMethod: function (params) {
// do something
},
// this works too!
myOtherMethod(params) {
// do something else
},
};
```
where `objectName` is an existing object, `methodName` is the name you are assigning to the method, and `functionName` is the name of the function.
You can then call the method in the context of the object as follows:
```js
objectName.methodName(params);
```
Methods are typically defined on the `prototype` object of the constructor, so that all objects of the same type share the same method. For example, you can define a function that formats and displays the properties of the previously-defined `Car` objects.
```js
Car.prototype.displayCar = function () {
const result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
console.log(result);
};
```
Notice the use of `this` to refer to the object to which the method belongs. Then you can call the `displayCar` method for each of the objects as follows:
```js
car1.displayCar();
car2.displayCar();
```
### Using this for object references
JavaScript has a special keyword, [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), that you can use within a method to refer to the current object. For example, suppose you have 2 objects, `Manager` and `Intern`. Each object has its own `name`, `age` and `job`. In the function `sayHi()`, notice the use of `this.name`. When added to the 2 objects, the same function will print the message with the name of the respective object it's attached to.
```js
const Manager = {
name: "Karina",
age: 27,
job: "Software Engineer",
};
const Intern = {
name: "Tyrone",
age: 21,
job: "Software Engineer Intern",
};
function sayHi() {
console.log(`Hello, my name is ${this.name}`);
}
// add sayHi function to both objects
Manager.sayHi = sayHi;
Intern.sayHi = sayHi;
Manager.sayHi(); // Hello, my name is Karina
Intern.sayHi(); // Hello, my name is Tyrone
```
`this` is a "hidden parameter" of a function call that's passed in by specifying the object before the function that was called. For example, in `Manager.sayHi()`, `this` is the `Manager` object, because `Manager` comes before the function `sayHi()`. If you access the same function from another object, `this` will change as well. If you use other methods to call the function, like {{jsxref("Function.prototype.call()")}} or {{jsxref("Reflect.apply()")}}, you can explicitly pass the value of `this` as an argument.
## Defining getters and setters
A [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) is a function associated with a property that gets the value of a specific property. A [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) is a function associated with a property that sets the value of a specific property. Together, they can indirectly represent the value of a property.
Getters and setters can be either
- defined within [object initializers](#using_object_initializers), or
- added later to any existing object.
Within [object initializers](#using_object_initializers), getters and setters are defined like regular [methods](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), but prefixed with the keywords `get` or `set`. The getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:
```js
const myObj = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2;
},
};
console.log(myObj.a); // 7
console.log(myObj.b); // 8, returned from the get b() method
myObj.c = 50; // Calls the set c(x) method
console.log(myObj.a); // 25
```
The `myObj` object's properties are:
- `myObj.a` β a number
- `myObj.b` β a getter that returns `myObj.a` plus 1
- `myObj.c` β a setter that sets the value of `myObj.a` to half of the value `myObj.c` is being set to
Getters and setters can also be added to an object at any time after creation using the {{jsxref("Object.defineProperties()")}} method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:
```js
const myObj = { a: 0 };
Object.defineProperties(myObj, {
b: {
get() {
return this.a + 1;
},
},
c: {
set(x) {
this.a = x / 2;
},
},
});
myObj.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(myObj.b); // Runs the getter, which yields a + 1 or 6
```
Which of the two forms to choose depends on your programming style and task at hand. If you can change the definition of the original object, you will probably define getters and setters through the original initializer. This form is more compact and natural. However, if you need to add getters and setters later β maybe because you did not write the particular object β then the second form is the only possible form. The second form better represents the dynamic nature of JavaScript, but it can make the code hard to read and understand.
## Comparing objects
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.
```js
// Two variables, two distinct objects with the same properties
const fruit = { name: "apple" };
const fruitbear = { name: "apple" };
fruit == fruitbear; // return false
fruit === fruitbear; // return false
```
```js
// Two variables, a single object
const fruit = { name: "apple" };
const fruitbear = fruit; // Assign fruit object reference to fruitbear
// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true
fruit.name = "grape";
console.log(fruitbear); // { name: "grape" }; not { name: "apple" }
```
For more information about comparison operators, see [equality operators](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators).
## See also
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
{{PreviousNext("Web/JavaScript/Guide/Regular_expressions", "Web/JavaScript/Guide/Using_classes")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/expressions_and_operators/index.md | ---
title: Expressions and operators
slug: Web/JavaScript/Guide/Expressions_and_operators
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
At a high level, an _expression_ is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely _evaluate_.
The expression `x = 7` is an example of the first type. This expression uses the `=` _operator_ to assign the value seven to the variable `x`. The expression itself evaluates to `7`.
The expression `3 + 4` is an example of the second type. This expression uses the `+` operator to add `3` and `4` together and produces a value, `7`. However, if it's not eventually part of a bigger construct (for example, a [variable declaration](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations) like `const z = 3 + 4`), its result will be immediately discarded β this is usually a programmer mistake because the evaluation doesn't produce any effects.
As the examples above also illustrate, all complex expressions are joined by _operators_, such as `=` and `+`. In this section, we will introduce the following operators:
- [Assignment operators](#assignment_operators)
- [Comparison operators](#comparison_operators)
- [Arithmetic operators](#arithmetic_operators)
- [Bitwise operators](#bitwise_operators)
- [Logical operators](#logical_operators)
- [BigInt operators](#bigint_operators)
- [String operators](#string_operators)
- [Conditional (ternary) operator](#conditional_ternary_operator)
- [Comma operator](#comma_operator)
- [Unary operators](#unary_operators)
- [Relational operators](#relational_operators)
These operators join operands either formed by higher-precedence operators or one of the [basic expressions](#basic_expressions). A complete and detailed list of operators and expressions is also available in the [reference](/en-US/docs/Web/JavaScript/Reference/Operators).
The _precedence_ of operators determines the order they are applied when evaluating an expression. For example:
```js
const x = 1 + 2 * 3;
const y = 2 * 3 + 1;
```
Despite `*` and `+` coming in different orders, both expressions would result in `7` because `*` has precedence over `+`, so the `*`-joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a [grouped expression](#grouping_operator) β the basic expression). To see a complete table of operator precedence as well as various caveats, see the [Operator Precedence Reference](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table) page.
JavaScript has both _binary_ and _unary_ operators, and one special ternary operator, the conditional operator.
A binary operator requires two operands, one before the operator and one after the operator:
```plain
operand1 operator operand2
```
For example, `3 + 4` or `x * y`. This form is called an _infix_ binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.
A unary operator requires a single operand, either before or after the operator:
```plain
operator operand
operand operator
```
For example, `x++` or `++x`. The `operator operand` form is called a _prefix_ unary operator, and the `operand operator` form is called a _postfix_ unary operator. `++` and `--` are the only postfix operators in JavaScript β all other operators, like `!`, `typeof`, etc. are prefix.
## Assignment operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
The simple assignment operator is equal (`=`), which assigns the value of its right operand to its left operand.
That is, `x = f()` is an assignment expression that assigns the value of `f()` to `x`.
There are also compound assignment operators that are shorthand for the operations listed in the following table:
| Name | Shorthand operator | Meaning |
| ----------------------------------------------------------------------------------------------------------------- | ------------------ | ------------------ |
| [Assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) | `x = f()` | `x = f()` |
| [Addition assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment) | `x += f()` | `x = x + f()` |
| [Subtraction assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction_assignment) | `x -= f()` | `x = x - f()` |
| [Multiplication assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication_assignment) | `x *= f()` | `x = x * f()` |
| [Division assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Division_assignment) | `x /= f()` | `x = x / f()` |
| [Remainder assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder_assignment) | `x %= f()` | `x = x % f()` |
| [Exponentiation assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation_assignment) | `x **= f()` | `x = x ** f()` |
| [Left shift assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift_assignment) | `x <<= f()` | `x = x << f()` |
| [Right shift assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment) | `x >>= f()` | `x = x >> f()` |
| [Unsigned right shift assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment) | `x >>>= f()` | `x = x >>> f()` |
| [Bitwise AND assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment) | `x &= f()` | `x = x & f()` |
| [Bitwise XOR assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment) | `x ^= f()` | `x = x ^ f()` |
| [Bitwise OR assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment) | `x \|= f()` | `x = x \| f()` |
| [Logical AND assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment) | `x &&= f()` | `x && (x = f())` |
| [Logical OR assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment) | `x \|\|= f()` | `x \|\| (x = f())` |
| [Nullish coalescing assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment) | `x ??= f()` | `x ?? (x = f())` |
### Assigning to properties
If an expression evaluates to an [object](/en-US/docs/Web/JavaScript/Guide/Working_with_objects), then the left-hand side of an assignment expression may make assignments to properties of that expression.
For example:
```js
const obj = {};
obj.x = 3;
console.log(obj.x); // Prints 3.
console.log(obj); // Prints { x: 3 }.
const key = "y";
obj[key] = 5;
console.log(obj[key]); // Prints 5.
console.log(obj); // Prints { x: 3, y: 5 }.
```
For more information about objects, read [Working with Objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects).
If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:
```js
const val = 0;
val.x = 3;
console.log(val.x); // Prints undefined.
console.log(val); // Prints 0.
```
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#converting_mistakes_into_errors), the code above throws, because one cannot assign properties to primitives.
It is an error to assign values to unmodifiable properties or to properties of an expression without properties (`null` or `undefined`).
### Destructuring
For more complex assignments, the [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and
object literals.
Without destructuring, it takes multiple statements to extract values from arrays and objects:
```js
const foo = ["one", "two", "three"];
const one = foo[0];
const two = foo[1];
const three = foo[2];
```
With destructuring, you can extract multiple values into distinct variables using a single statement:
```js
const [one, two, three] = foo;
```
### Evaluation and nesting
In general, assignments are used within a variable declaration (i.e., with [`const`][], [`let`][], or [`var`][]) or as standalone statements).
```js
// Declares a variable x and initializes it to the result of f().
// The result of the x = f() assignment expression is discarded.
let x = f();
x = g(); // Reassigns the variable x to the result of g().
```
[`const`]: /en-US/docs/Web/JavaScript/Reference/Statements/const
[`let`]: /en-US/docs/Web/JavaScript/Reference/Statements/let
[`var`]: /en-US/docs/Web/JavaScript/Reference/Statements/var
However, like other expressions, assignment expressions like `x = f()` evaluate into a result value.
Although this result value is usually not used, it can then be used by another expression.
Chaining assignments or nesting assignments in other expressions can result in surprising behavior.
For this reason, some JavaScript style guides [discourage chaining or nesting assignments][discourage assign chain].
Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.
[discourage assign chain]: https://github.com/airbnb/javascript/blob/master/README.md#variables--no-chain-assignment
By chaining or nesting an assignment expression, its result can itself be assigned to another variable.
It can be logged, it can be put inside an array literal or function call, and so on.
```js-nolint
let x;
const y = (x = f()); // Or equivalently: const y = x = f();
console.log(y); // Logs the return value of the assignment x = f().
console.log(x = f()); // Logs the return value directly.
// An assignment expression can be nested in any place
// where expressions are generally allowed,
// such as array literals' elements or as function calls' arguments.
console.log([0, x = f(), 0]);
console.log(f(0, x = f(), 0));
```
The evaluation result matches the expression to the right of the `=` sign in the
"Meaning" column of the table above. That means that `x = f()` evaluates into
whatever `f()`'s result is, `x += f()` evaluates into the resulting sum `x + f()`,
`x **= f()` evaluates into the resulting power `x ** f()`, and so on.
In the case of logical assignments, `x &&= f()`,
`x ||= f()`, and `x ??= f()`, the return value is that of the
logical operation without the assignment, so `x && f()`,
`x || f()`, and `x ?? f()`, respectively.
When chaining these expressions without parentheses or other grouping operators
like array literals, the assignment expressions are **grouped right to left**
(they are [right-associative][]), but they are **evaluated left to right**.
[right-associative]: https://en.wikipedia.org/wiki/Operator_associativity
Note that, for all assignment operators other than `=` itself,
the resulting values are always based on the operands' values _before_
the operation.
For example, assume that the following functions `f` and `g`
and the variables `x` and `y` have been declared:
```js
function f() {
console.log("F!");
return 2;
}
function g() {
console.log("G!");
return 3;
}
let x, y;
```
Consider these three examples:
```js-nolint
y = x = f();
y = [f(), x = g()];
x[f()] = g();
```
#### Evaluation example 1
`y = x = f()` is equivalent to `y = (x = f())`,
because the assignment operator `=` is [right-associative][].
However, it evaluates from left to right:
1. The assignment expression `y = x = f()` starts to evaluate.
1. The `y` on this assignment's left-hand side evaluates
into a reference to the variable named `y`.
2. The assignment expression `x = f()` starts to evaluate.
1. The `x` on this assignment's left-hand side evaluates
into a reference to the variable named `x`.
2. The function call `f()` prints "F!" to the console and
then evaluates to the number `2`.
3. That `2` result from `f()` is assigned to `x`.
3. The assignment expression `x = f()` has now finished evaluating;
its result is the new value of `x`, which is `2`.
4. That `2` result in turn is also assigned to `y`.
2. The assignment expression `y = x = f()` has now finished evaluating;
its result is the new value of `y` β which happens to be `2`.
`x` and `y` are assigned to `2`,
and the console has printed "F!".
#### Evaluation example 2
`y = [ f(), x = g() ]` also evaluates from left to right:
1. The assignment expression `y = [ f(), x = g() ]` starts to evaluate.
1. The `y` on this assignment's left-hand evaluates
into a reference to the variable named `y`.
2. The inner array literal `[ f(), x = g() ]` starts to evaluate.
1. The function call `f()` prints "F!" to the console and
then evaluates to the number `2`.
2. The assignment expression `x = g()` starts to evaluate.
1. The `x` on this assignment's left-hand side evaluates
into a reference to the variable named `x`.
2. The function call `g()` prints "G!" to the console and
then evaluates to the number `3`.
3. That `3` result from `g()` is assigned to `x`.
3. The assignment expression `x = g()` has now finished evaluating;
its result is the new value of `x`, which is `3`.
That `3` result becomes the next element
in the inner array literal (after the `2` from the `f()`).
3. The inner array literal `[ f(), x = g() ]`
has now finished evaluating;
its result is an array with two values: `[ 2, 3 ]`.
4. That `[ 2, 3 ]` array is now assigned to `y`.
2. The assignment expression `y = [ f(), x = g() ]` has
now finished evaluating;
its result is the new value of `y` β which happens to be `[ 2, 3 ]`.
`x` is now assigned to `3`,
`y` is now assigned to `[ 2, 3 ]`,
and the console has printed "F!" then "G!".
#### Evaluation example 3
`x[f()] = g()` also evaluates from left to right.
(This example assumes that `x` is already assigned to some object.
For more information about objects, read [Working with Objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects).)
1. The assignment expression `x[f()] = g()` starts to evaluate.
1. The `x[f()]` property access on this assignment's left-hand
starts to evaluate.
1. The `x` in this property access evaluates
into a reference to the variable named `x`.
2. Then the function call `f()` prints "F!" to the console and
then evaluates to the number `2`.
2. The `x[f()]` property access on this assignment
has now finished evaluating;
its result is a variable property reference: `x[2]`.
3. Then the function call `g()` prints "G!" to the console and
then evaluates to the number `3`.
4. That `3` is now assigned to `x[2]`.
(This step will succeed only if `x` is assigned to an [object](/en-US/docs/Web/JavaScript/Guide/Working_with_objects).)
2. The assignment expression `x[f()] = g()` has now finished evaluating;
its result is the new value of `x[2]` β which happens to be `3`.
`x[2]` is now assigned to `3`,
and the console has printed "F!" then "G!".
### Avoid assignment chains
Chaining assignments or nesting assignments in other expressions can
result in surprising behavior. For this reason,
[chaining assignments in the same statement is discouraged][discourage assign chain].
In particular, putting a variable chain in a [`const`][], [`let`][], or [`var`][] statement often does _not_ work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are _not_ declared by the `const`/`let`/`var` statement.
For example:
```js-nolint
const z = y = x = f();
```
This statement seemingly declares the variables `x`, `y`, and `z`.
However, it only actually declares the variable `z`.
`y` and `x` are either invalid references to nonexistent variables (in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)) or, worse, would implicitly create [global variables](/en-US/docs/Glossary/Global_variable) for `x` and `y` in [sloppy mode](/en-US/docs/Glossary/Sloppy_mode).
## Comparison operators
A comparison operator compares its operands and returns a logical value based on whether the comparison is true.
The operands can be numerical, string, logical, or [object](/en-US/docs/Web/JavaScript/Guide/Working_with_objects) values.
Strings are compared based on standard lexicographical ordering, using Unicode values.
In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison.
This behavior generally results in comparing the operands numerically.
The sole exceptions to type conversion within comparisons involve the `===` and `!==` operators, which perform strict equality and inequality comparisons.
These operators do not attempt to convert the operands to compatible types before checking equality.
The following table describes the comparison operators in terms of this sample code:
```js
const var1 = 3;
const var2 = 4;
```
<table class="standard-table">
<caption>
Comparison operators
</caption>
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Description</th>
<th scope="col">Examples returning true</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Equality">Equal</a> (<code>==</code>)
</td>
<td>Returns <code>true</code> if the operands are equal.</td>
<td>
<code>3 == var1</code>
<p><code>"3" == var1</code></p>
<code>3 == '3'</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Inequality">Not equal</a> (<code>!=</code>)
</td>
<td>Returns <code>true</code> if the operands are not equal.</td>
<td>
<code>var1 != 4<br />var2 != "3"</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality">Strict equal</a> (<code>===</code>)
</td>
<td>
Returns <code>true</code> if the operands are equal and of the same
type. See also {{jsxref("Object.is")}} and
<a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">sameness in JS</a>.
</td>
<td><code>3 === var1</code></td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality">Strict not equal</a> (<code>!==</code>)
</td>
<td>
Returns <code>true</code> if the operands are of the same type but not equal, or are of different type.
</td>
<td>
<code>var1 !== "3"<br />3 !== '3'</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than">Greater than</a> (<code>></code>)
</td>
<td>
Returns <code>true</code> if the left operand is greater than the right operand.
</td>
<td>
<code>var2 > var1<br />"12" > 2</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal">Greater than or equal</a>
(<code>>=</code>)
</td>
<td>
Returns <code>true</code> if the left operand is greater than or equal to the right operand.
</td>
<td>
<code>var2 >= var1<br />var1 >= 3</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than">Less than</a>
(<code><</code>)
</td>
<td>
Returns <code>true</code> if the left operand is less than the right operand.
</td>
<td>
<code>var1 < var2<br />"2" < 12</code>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal">Less than or equal</a>
(<code><=</code>)
</td>
<td>
Returns <code>true</code> if the left operand is less than or equal to the right operand.
</td>
<td>
<code>var1 <= var2<br />var2 <= 5</code>
</td>
</tr>
</tbody>
</table>
> **Note:** `=>` is not a comparison operator but rather is the notation
> for [Arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
## Arithmetic operators
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value.
The standard arithmetic operators are addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`).
These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces {{jsxref("Infinity")}}). For example:
```js
1 / 2; // 0.5
1 / 2 === 1.0 / 2.0; // this is true
```
In addition to the standard arithmetic operations (`+`, `-`, `*`, `/`), JavaScript provides the arithmetic operators listed in the following table:
<table class="fullwidth-table">
<caption>
Arithmetic operators
</caption>
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Description</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Remainder">Remainder</a> (<code>%</code>)
</td>
<td>
Binary operator. Returns the integer remainder of dividing the two operands.
</td>
<td>12 % 5 returns 2.</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Increment">Increment</a> (<code>++</code>)
</td>
<td>
Unary operator. Adds one to its operand. If used as a prefix operator
(<code>++x</code>), returns the value of its operand after adding one;
if used as a postfix operator (<code>x++</code>), returns the value of
its operand before adding one.
</td>
<td>
If <code>x</code> is 3, then <code>++x</code> sets <code>x</code> to 4
and returns 4, whereas <code>x++</code> returns 3 and, only then, sets <code>x</code> to 4.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Decrement">Decrement</a> (<code>--</code>)
</td>
<td>
Unary operator. Subtracts one from its operand.
The return value is analogous to that for the increment operator.
</td>
<td>
If <code>x</code> is 3, then <code>--x</code> sets <code>x</code> to 2
and returns 2, whereas <code>x--</code> returns 3 and, only then, sets <code>x</code> to 2.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation">Unary negation</a> (<code>-</code>)
</td>
<td>Unary operator. Returns the negation of its operand.</td>
<td>If <code>x</code> is 3, then <code>-x</code> returns -3.</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus">Unary plus</a> (<code>+</code>)
</td>
<td>
Unary operator. Attempts to <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion">convert the operand to a number</a>, if it is not already.
</td>
<td>
<p><code>+"3"</code> returns <code>3</code>.</p>
<p><code>+true</code> returns <code>1</code>.</p>
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation">Exponentiation operator</a> (<code>**</code>)
</td>
<td>
Calculates the <code>base</code> to the <code>exponent</code> power,
that is, <code>base^exponent</code>
</td>
<td>
<code>2 ** 3</code> returns <code>8</code>.<br /><code>10 ** -1</code>
returns <code>0.1</code>.
</td>
</tr>
</tbody>
</table>
## Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather
than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has
a binary representation of 1001. Bitwise operators perform their operations on such
binary representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.
| Operator | Usage | Description |
| -------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Bitwise AND](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND) | `a & b` | Returns a one in each bit position for which the corresponding bits of both operands are ones. |
| [Bitwise OR](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) | `a \| b` | Returns a zero in each bit position for which the corresponding bits of both operands are zeros. |
| [Bitwise XOR](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR) | `a ^ b` | Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.] |
| [Bitwise NOT](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT) | `~ a` | Inverts the bits of its operand. |
| [Left shift](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift) | `a << b` | Shifts `a` in binary representation `b` bits to the left, shifting in zeros from the right. |
| [Sign-propagating right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift) | `a >> b` | Shifts `a` in binary representation `b` bits to the right, discarding bits shifted off. |
| [Zero-fill right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) | `a >>> b` | Shifts `a` in binary representation `b` bits to the right, discarding bits shifted off, and shifting in zeros from the left. |
### Bitwise logical operators
Conceptually, the bitwise logical operators work as follows:
- The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
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:
```plain
Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001
After: 1010 0000 0000 0000 0110 0000 0000 0001
```
- 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.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111.
So, when the bitwise operators are applied to these values, the results are as follows:
| Expression | Result | Binary Description |
| ---------- | ------ | ------------------------------------------------- |
| `15 & 9` | `9` | `1111 & 1001 = 1001` |
| `15 \| 9` | `15` | `1111 \| 1001 = 1111` |
| `15 ^ 9` | `6` | `1111 ^ 1001 = 0110` |
| `~15` | `-16` | `~ 0000 0000 β¦ 0000 1111 = 1111 1111 β¦ 1111 0000` |
| `~9` | `-10` | `~ 0000 0000 β¦ 0000 1001 = 1111 1111 β¦ 1111 0110` |
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with
the most significant (left-most) bit set to 1 represent negative numbers
(two's-complement representation). `~x` evaluates to the same value that
`-x - 1` evaluates to.
### Bitwise shift operators
The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be
shifted.
The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result of either type {{jsxref("Number")}} or {{jsxref("BigInt")}}: specifically, if the type
of the left operand is {{jsxref("BigInt")}}, they return {{jsxref("BigInt")}};
otherwise, they return {{jsxref("Number")}}.
The shift operators are listed in the following table.
<table class="fullwidth-table">
<caption>
Bitwise shift operators
</caption>
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Description</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift">Left shift</a><br />(<code><<</code>)
</td>
<td>
This operator shifts the first operand the specified number of bits to
the left. Excess bits shifted off to the left are discarded. Zero bits
are shifted in from the right.
</td>
<td>
<code>9<<2</code> yields 36, because 1001 shifted 2 bits to
the left becomes 100100, which is 36.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift">Sign-propagating right shift</a> (<code>>></code>)
</td>
<td>
This operator shifts the first operand the specified number of bits to
the right. Excess bits shifted off to the right are discarded. Copies of
the leftmost bit are shifted in from the left.
</td>
<td>
<code>9>>2</code> yields 2, because 1001 shifted 2 bits to the right
becomes 10, which is 2. Likewise, <code>-9>>2</code> yields -3, because the sign is preserved.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift">Zero-fill right shift</a> (<code>>>></code>)
</td>
<td>
This operator shifts the first operand the specified number of bits to
the right. Excess bits shifted off to the right are discarded. Zero bits
are shifted in from the left.
</td>
<td>
<code>19>>>2</code> yields 4, because 10011 shifted 2 bits to the right
becomes 100, which is 4. For non-negative numbers, zero-fill right shift
and sign-propagating right shift yield the same result.
</td>
</tr>
</tbody>
</table>
## Logical operators
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value.
However, the `&&` and `||` operators actually return the value of one of the specified operands, so if these
operators are used with non-Boolean values, they may return a non-Boolean value.
The logical operators are described in the following table.
<table class="fullwidth-table">
<caption>
Logical operators
</caption>
<thead>
<tr>
<th scope="col">Operator</th>
<th scope="col">Usage</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND">Logical AND</a> (<code>&&</code>)
</td>
<td><code>expr1 && expr2</code></td>
<td>
Returns <code>expr1</code> if it can be converted to <code>false</code>;
otherwise, returns <code>expr2</code>. Thus, when used with Boolean
values, <code>&&</code> returns <code>true</code> if both
operands are true; otherwise, returns <code>false</code>.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR">Logical OR </a>(<code>||</code>)
</td>
<td><code>expr1 || expr2</code></td>
<td>
Returns <code>expr1</code> if it can be converted to <code>true</code>;
otherwise, returns <code>expr2</code>. Thus, when used with Boolean
values, <code>||</code> returns <code>true</code> if either operand is
true; if both are false, returns <code>false</code>.
</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT">Logical NOT</a> (<code>!</code>)
</td>
<td><code>!expr</code></td>
<td>
Returns <code>false</code> if its single operand that can be converted
to <code>true</code>; otherwise, returns <code>true</code>.
</td>
</tr>
</tbody>
</table>
Examples of expressions that can be converted to `false` are those that
evaluate to null, 0, NaN, the empty string (""), or undefined.
The following code shows examples of the `&&` (logical AND)
operator.
```js
const a1 = true && true; // t && t returns true
const a2 = true && false; // t && f returns false
const a3 = false && true; // f && t returns false
const a4 = false && 3 === 4; // f && f returns false
const a5 = "Cat" && "Dog"; // t && t returns Dog
const a6 = false && "Cat"; // f && t returns false
const a7 = "Cat" && false; // t && f returns false
```
The following code shows examples of the || (logical OR) operator.
```js
const o1 = true || true; // t || t returns true
const o2 = false || true; // f || t returns true
const o3 = true || false; // t || f returns true
const o4 = false || 3 === 4; // f || f returns false
const o5 = "Cat" || "Dog"; // t || t returns Cat
const o6 = false || "Cat"; // f || t returns Cat
const o7 = "Cat" || false; // t || f returns Cat
```
The following code shows examples of the ! (logical NOT) operator.
```js
const n1 = !true; // !t returns false
const n2 = !false; // !f returns true
const n3 = !"Cat"; // !t returns false
```
### Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible
"short-circuit" evaluation using the following rules:
- `false && anything` is short-circuit evaluated to false.
- `true || anything` is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the
_anything_ part of the above expressions is not evaluated, so any side effects of
doing so do not take effect.
Note that for the second case, in modern code you can use the [Nullish coalescing operator](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) (`??`) that works like `||`, but it only returns the second expression, when the first one is "[nullish](/en-US/docs/Glossary/Nullish)", i.e. [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
or [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).
It is thus the better alternative to provide defaults, when values like `''` or `0` are valid values for the first expression, too.
## BigInt operators
Most operators that can be used between numbers can be used between [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) values as well.
```js
// BigInt addition
const a = 1n + 2n; // 3n
// Division with BigInts round towards zero
const b = 1n / 2n; // 0n
// Bitwise operations with BigInts do not truncate either side
const c = 40000000000000000n >> 2n; // 10000000000000000n
```
One exception is [unsigned right shift (`>>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift), which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".
```js
const d = 8n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >> instead
```
BigInts and numbers are not mutually replaceable β you cannot mix them in calculations.
```js example-bad
const a = 1n + 2; // TypeError: Cannot mix BigInt and other types
```
This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.
```js example-good
const a = Number(1n) + 2; // 3
const b = 1n + BigInt(2); // 3n
```
You can compare BigInts with numbers.
```js
const a = 1n > 2; // false
const b = 3 > 2n; // true
```
## String operators
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
For example,
```js
console.log("my " + "string"); // console logs the string "my string".
```
The shorthand assignment operator `+=` can also be used to concatenate strings.
For example,
```js
let mystring = "alpha";
mystring += "bet"; // evaluates to "alphabet" and assigns this value to mystring.
```
## Conditional (ternary) operator
The [conditional operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator)
is the only JavaScript operator that takes three operands.
The operator can have one of two values based on a condition.
The syntax is:
```js-nolint
condition ? val1 : val2
```
If `condition` is true, the operator has the value of `val1`.
Otherwise it has the value of `val2`. You can use the conditional operator anywhere you would use a standard operator.
For example,
```js
const status = age >= 18 ? "adult" : "minor";
```
This statement assigns the value "adult" to the variable `status` if
`age` is eighteen or more. Otherwise, it assigns the value "minor" to
`status`.
## Comma operator
The [comma operator](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) (`,`)
evaluates both of its operands and returns the value of the last operand.
This operator is primarily used inside a `for` loop, to allow multiple variables to be updated each time through the loop.
It is regarded bad style to use it elsewhere, when it is not necessary.
Often two separate statements can and should be used instead.
For example, if `a` is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once.
The code prints the values of the diagonal elements in the array:
```js
const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const a = [x, x, x, x, x];
for (let i = 0, j = 9; i <= j; i++, j--) {
// ^
console.log(`a[${i}][${j}]= ${a[i][j]}`);
}
```
## Unary operators
A unary operation is an operation with only one operand.
### delete
The [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator deletes an object's property.
The syntax is:
```js
delete object.property;
delete object[propertyKey];
delete objectName[index];
```
where `object` is the name of an object, `property` is an existing property, and `propertyKey` is a string or symbol referring to an existing property.
If the `delete` operator succeeds, it removes the property from the object.
Trying to access it afterwards will yield `undefined`.
The `delete` operator returns `true` if the operation is possible; it returns `false` if the operation is not possible.
```js
delete Math.PI; // returns false (cannot delete non-configurable properties)
const myObj = { h: 4 };
delete myObj.h; // returns true (can delete user-defined properties)
```
#### Deleting array elements
Since arrays are just objects, it's technically possible to `delete` elements from them.
This is, however, regarded as a bad practice β try to avoid it.
When you delete an array property, the array length is not affected and other elements are not re-indexed.
To achieve that behavior, it is much better to just overwrite the element with the value `undefined`.
To actually manipulate the array, use the various array methods such as [`splice`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).
### typeof
The [`typeof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) returns a string indicating the type of the unevaluated operand.
`operand` is the string, variable, keyword, or object for which the type is to be returned.
The parentheses are optional.
Suppose you define the following variables:
```js
const myFun = new Function("5 + 2");
const shape = "round";
const size = 1;
const foo = ["Apple", "Mango", "Orange"];
const today = new Date();
```
The `typeof` operator returns the following results for these variables:
```js
typeof myFun; // returns "function"
typeof shape; // returns "string"
typeof size; // returns "number"
typeof foo; // returns "object"
typeof today; // returns "object"
typeof doesntExist; // returns "undefined"
```
For the keywords `true` and `null`, the `typeof`
operator returns the following results:
```js
typeof true; // returns "boolean"
typeof null; // returns "object"
```
For a number or string, the `typeof` operator returns the following results:
```js
typeof 62; // returns "number"
typeof "Hello world"; // returns "string"
```
For property values, the `typeof` operator returns the type of value the
property contains:
```js
typeof document.lastModified; // returns "string"
typeof window.length; // returns "number"
typeof Math.LN2; // returns "number"
```
For methods and functions, the `typeof` operator returns results as follows:
```js
typeof blur; // returns "function"
typeof eval; // returns "function"
typeof parseInt; // returns "function"
typeof shape.split; // returns "function"
```
For predefined objects, the `typeof` operator returns results as follows:
```js
typeof Date; // returns "function"
typeof Function; // returns "function"
typeof Math; // returns "object"
typeof Option; // returns "function"
typeof String; // returns "function"
```
### void
The [`void` operator](/en-US/docs/Web/JavaScript/Reference/Operators/void) specifies an expression to be evaluated without returning a value. `expression` is a JavaScript expression to evaluate.
The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.
## Relational operators
A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.
### in
The [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in) returns `true` if the specified property is in the specified object.
The syntax is:
```js-nolint
propNameOrNumber in objectName
```
where `propNameOrNumber` is a string, numeric, or symbol expression representing a property name or array index, and `objectName` is the name of an object.
The following examples show some uses of the `in` operator.
```js
// Arrays
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
"bay" in trees; // returns false
// (you must specify the index number, not the value at that index)
"length" in trees; // returns true (length is an Array property)
// built-in objects
"PI" in Math; // returns true
const myString = new String("coral");
"length" in myString; // returns true
// Custom objects
const mycar = { make: "Honda", model: "Accord", year: 1998 };
"make" in mycar; // returns true
"model" in mycar; // returns true
```
### instanceof
The [`instanceof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) returns `true`
if the specified object is of the specified object type. The syntax is:
```js-nolint
objectName instanceof objectType
```
where `objectName` is the name of the object to compare to `objectType`, and `objectType` is an object type, such as {{jsxref("Date")}} or {{jsxref("Array")}}.
Use `instanceof` when you need to confirm the type of an object at runtime.
For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses `instanceof` to determine whether `theDay` is a `Date` object. Because `theDay` is a `Date` object, the statements in the `if` statement execute.
```js
const theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
// statements to execute
}
```
## Basic expressions
All operators eventually operate on one or more basic expressions. These basic expressions include [identifiers](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations) and [literals](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#literals), but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.
### this
Use the [`this` keyword](/en-US/docs/Web/JavaScript/Reference/Operators/this) to refer to the current object.
In general, `this` refers to the calling object in a method.
Use `this` either with the dot or the bracket notation:
```js
this["propertyName"];
this.propertyName;
```
Suppose a function called `validate` validates an object's `value` property, given the object and the high and low values:
```js
function validate(obj, lowval, hival) {
if (obj.value < lowval || obj.value > hival) {
console.log("Invalid Value!");
}
}
```
You could call `validate` in each form element's `onChange` event handler, using `this` to pass it to the form element, as in the following example:
```html
<p>Enter a number between 18 and 99:</p>
<input type="text" name="age" size="3" onChange="validate(this, 18, 99);" />
```
### Grouping operator
The grouping operator `( )` controls the precedence of evaluation in
expressions. For example, you can override multiplication and division first, then
addition and subtraction to evaluate addition first.
```js-nolint
const a = 1;
const b = 2;
const c = 3;
// default precedence
a + b * c // 7
// evaluated by default like this
a + (b * c) // 7
// now overriding precedence
// addition before multiplication
(a + b) * c // 9
// which is equivalent to
a * c + b * c // 9
```
### new
You can use the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) to create an instance of a user-defined object type or of one of the built-in object types. Use `new` as follows:
```js
const objectName = new ObjectType(param1, param2, /* β¦, */ paramN);
```
### super
The [`super` keyword](/en-US/docs/Web/JavaScript/Reference/Operators/super) is used to call functions on an object's parent.
It is useful with [classes](/en-US/docs/Web/JavaScript/Reference/Classes) to call the parent constructor, for example.
```js-nolint
super(args); // calls the parent constructor.
super.functionOnParent(args);
```
{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/iterators_and_generators/index.md | ---
title: Iterators and generators
slug: Web/JavaScript/Guide/Iterators_and_generators
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Meta_programming")}}
Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of {{jsxref("Statements/for...of", "for...of")}} loops.
For details, see also:
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Statements/for...of", "for...of")}}
- {{jsxref("Statements/function*", "function*")}} and {{jsxref("Generator")}}
- {{jsxref("Operators/yield", "yield")}} and {{jsxref("Operators/yield*", "yield*")}}
## Iterators
In JavaScript an **iterator** is an object which defines a sequence and potentially a return value upon its termination.
Specifically, an iterator is any object which implements the [Iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) by having a `next()` method that returns an object with two properties:
- `value`
- : The next value in the iteration sequence.
- `done`
- : This is `true` if the last value in the sequence has already been consumed. If `value` is present alongside `done`, it is the iterator's return value.
Once created, an iterator object can be iterated explicitly by repeatedly calling `next()`. Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to `next()` should continue to return `{done: true}`.
The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence.
While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary. Because of this, iterators can express sequences of unlimited size, such as the range of integers between `0` and {{jsxref("Infinity")}}.
Here is an example which can do just that. It allows creation of a simple range iterator which defines a sequence of integers from `start` (inclusive) to `end` (exclusive) spaced `step` apart. Its final return value is the size of the sequence it created, tracked by the variable `iterationCount`.
```js
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false };
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true };
},
};
return rangeIterator;
}
```
Using the iterator then looks like this:
```js
const iter = makeRangeIterator(1, 10, 2);
let result = iter.next();
while (!result.done) {
console.log(result.value); // 1 3 5 7 9
result = iter.next();
}
console.log("Iterated over sequence of size:", result.value); // [5 numbers returned, that took interval in between: 0 to 10]
```
> **Note:** It is not possible to know reflectively whether a particular object is an iterator. If you need to do this, use [Iterables](#iterables).
## Generator functions
While custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. **Generator functions** provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the {{jsxref("Statements/function*", "function*")}} syntax.
When called, generator functions do not initially execute their code. Instead, they return a special type of iterator, called a **Generator**. When a value is consumed by calling the generator's `next` method, the Generator function executes until it encounters the `yield` keyword.
The function can be called as many times as desired, and returns a new Generator each time. Each Generator may only be iterated once.
We can now adapt the example from above. The behavior of this code is identical, but the implementation is much easier to write and read.
```js
function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
```
## Iterables
An object is **iterable** if it defines its iteration behavior, such as what values are looped over in a {{jsxref("Statements/for...of", "for...of")}} construct. Some built-in types, such as {{jsxref("Array")}} or {{jsxref("Map")}}, have a default iteration behavior, while other types (such as {{jsxref("Object")}}) do not.
In order to be **iterable**, an object must implement the **@@iterator** method. This means that the object (or one of the objects up its [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)) must have a property with a {{jsxref("Symbol.iterator")}} key.
It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case.
Iterables which can iterate only once (such as Generators) customarily return `this` from their **@@iterator** method, whereas iterables which can be iterated many times must return a new iterator on each invocation of **@@iterator**.
```js
function* makeIterator() {
yield 1;
yield 2;
}
const iter = makeIterator();
for (const itItem of iter) {
console.log(itItem);
}
console.log(iter[Symbol.iterator]() === iter); // true
// This example show us generator(iterator) is iterable object,
// which has the @@iterator method return the `iter` (itself),
// and consequently, the it object can iterate only _once_.
// If we change the @@iterator method of `iter` to a function/generator
// which returns a new iterator/generator object, `iter`
// can iterate many times
iter[Symbol.iterator] = function* () {
yield 2;
yield 1;
};
```
### User-defined iterables
You can make your own iterables like this:
```js
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
```
User-defined iterables can be used in `for...of` loops or the spread syntax as usual.
```js
for (const value of myIterable) {
console.log(value);
}
// 1
// 2
// 3
[...myIterable]; // [1, 2, 3]
```
### Built-in iterables
{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} and {{jsxref("Set")}} are all built-in iterables, because their prototype objects all have a {{jsxref("Symbol.iterator")}} method.
### Syntaxes expecting iterables
Some statements and expressions expect iterables. For example: the {{jsxref("Statements/for...of", "for...of")}} loops, {{jsxref("Operators/Spread_syntax", "spread syntax", "", 1)}}, {{jsxref("Operators/yield*", "yield*")}}, and {{jsxref("Operators/Destructuring_assignment", "destructuring", "", 1)}} syntax.
```js
for (const value of ["a", "b", "c"]) {
console.log(value);
}
// "a"
// "b"
// "c"
[..."abc"];
// ["a", "b", "c"]
function* gen() {
yield* ["a", "b", "c"];
}
gen().next();
// { value: "a", done: false }
[a, b, c] = new Set(["a", "b", "c"]);
a;
// "a"
```
## Advanced generators
Generators compute their `yield`ed values _on demand_, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above).
The {{jsxref("Generator/next", "next()")}} method also accepts a value, which can be used to modify the internal state of the generator. A value passed to `next()` will be received by `yield` .
> **Note:** A value passed to the _first_ invocation of `next()` is always ignored.
Here is the fibonacci generator using `next(x)` to restart the sequence:
```js
function* fibonacci() {
let current = 0;
let next = 1;
while (true) {
const reset = yield current;
[current, next] = [next, next + current];
if (reset) {
current = 0;
next = 1;
}
}
}
const sequence = fibonacci();
console.log(sequence.next().value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
console.log(sequence.next().value); // 5
console.log(sequence.next().value); // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
```
You can force a generator to throw an exception by calling its {{jsxref("Generator/throw", "throw()")}} method and passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the `yield` that is currently suspended were instead a `throw value` statement.
If the exception is not caught from within the generator, it will propagate up through the call to `throw()`, and subsequent calls to `next()` will result in the `done` property being `true`.
Generators have a {{jsxref("Generator/return", "return()")}} method that returns the given value and finishes the generator itself.
{{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Meta_programming")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/using_promises/index.md | ---
title: Using promises
slug: Web/JavaScript/Guide/Using_promises
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Using_classes", "Web/JavaScript/Guide/Typed_arrays")}}
A {{jsxref("Promise")}} is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.
Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Imagine a function, `createAudioFileAsync()`, which asynchronously generates a sound file given a configuration record and two callback functions: one called if the audio file is successfully created, and the other called if an error occurs.
Here's some code that uses `createAudioFileAsync()`:
```js
function successCallback(result) {
console.log(`Audio file ready at URL: ${result}`);
}
function failureCallback(error) {
console.error(`Error generating audio file: ${error}`);
}
createAudioFileAsync(audioSettings, successCallback, failureCallback);
```
If `createAudioFileAsync()` were rewritten to return a promise, you would attach your callbacks to it instead:
```js
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
```
This convention has several advantages. We will explore each one.
## Chaining
A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. In the old days, doing several asynchronous operations in a row would lead to the classic callback pyramid of doom:
```js-nolint
doSomething(function (result) {
doSomethingElse(result, function (newResult) {
doThirdThing(newResult, function (finalResult) {
console.log(`Got the final result: ${finalResult}`);
}, failureCallback);
}, failureCallback);
}, failureCallback);
```
With promises, we accomplish this by creating a promise chain. The API design of promises makes this great, because callbacks are attached to the returned promise object, instead of being passed into a function.
Here's the magic: the `then()` function returns a **new promise**, different from the original:
```js
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
```
This second promise (`promise2`) represents the completion not just of `doSomething()`, but also of the `successCallback` or `failureCallback` you passed in β which can be other asynchronous functions returning a promise. When that's the case, any callbacks added to `promise2` get queued behind the promise returned by either `successCallback` or `failureCallback`.
> **Note:** If you want a working example to play with, you can use the following template to create any function returning a promise:
>
> ```js
> function doSomething() {
> return new Promise((resolve) => {
> setTimeout(() => {
> // Other things to do before completion of the promise
> console.log("Did something");
> // The fulfillment value of the promise
> resolve("https://example.com/");
> }, 200);
> });
> }
> ```
>
> The implementation is discussed in the [Creating a Promise around an old callback API](#creating_a_promise_around_an_old_callback_api) section below.
With this pattern, you can create longer chains of processing, where each promise represents the completion of one asynchronous step in the chain. In addition, the arguments to `then` are optional, and `catch(failureCallback)` is short for `then(null, failureCallback)` β so if your error handling code is the same for all steps, you can attach it to the end of the chain:
```js
doSomething()
.then(function (result) {
return doSomethingElse(result);
})
.then(function (newResult) {
return doThirdThing(newResult);
})
.then(function (finalResult) {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
```
You might see this expressed with [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) instead:
```js
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
```
> **Note:** Arrow function expressions can have an [implicit return](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body); so, `() => x` is short for `() => { return x; }`.
`doSomethingElse` and `doThirdThing` can return any value β if they return promises, that promise is first waited until it settles, and the next callback receives the fulfillment value, not the promise itself. It is important to always return promises from `then` callbacks, even if the promise always resolves to `undefined`. If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".
```js example-bad
doSomething()
.then((url) => {
// Missing `return` keyword in front of fetch(url).
fetch(url);
})
.then((result) => {
// result is undefined, because nothing is returned from the previous
// handler. There's no way to know the return value of the fetch()
// call anymore, or whether it succeeded at all.
});
```
By returning the result of the `fetch` call (which is a promise), we can both track its completion and receive its value when it completes.
```js example-good
doSomething()
.then((url) => {
// `return` keyword added
return fetch(url);
})
.then((result) => {
// result is a Response object
});
```
Floating promises could be worse if you have race conditions β if the promise from the last handler is not returned, the next `then` handler will be called early, and any value it reads may be incomplete.
```js example-bad
const listOfIngredients = [];
doSomething()
.then((url) => {
// Missing `return` keyword in front of fetch(url).
fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
});
})
.then(() => {
console.log(listOfIngredients);
// listOfIngredients will always be [], because the fetch request hasn't completed yet.
});
```
Therefore, as a rule of thumb, whenever your operation encounters a promise, return it and defer its handling to the next `then` handler.
```js example-good
const listOfIngredients = [];
doSomething()
.then((url) => {
// `return` keyword now included in front of fetch call.
return fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
});
})
.then(() => {
console.log(listOfIngredients);
// listOfIngredients will now contain data from fetch call.
});
```
Even better, you can flatten the nested chain into a single chain, which is simpler and makes error handling easier. The details are discussed in the [Nesting](#nesting) section below.
```js
doSomething()
.then((url) => fetch(url))
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
})
.then(() => {
console.log(listOfIngredients);
});
```
Using [`async`/`await`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) can help you write code that's more intuitive and resembles synchronous code. Below is the same example using `async`/`await`:
```js
async function logIngredients() {
const url = await doSomething();
const res = await fetch(url);
const data = await res.json();
listOfIngredients.push(data);
console.log(listOfIngredients);
}
```
Note how the code looks exactly like synchronous code, except for the `await` keywords in front of promises. One of the only tradeoffs is that it may be easy to forget the [`await`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) keyword, which can only be fixed when there's a type mismatch (e.g. trying to use a promise as a value).
`async`/`await` builds on promises β for example, `doSomething()` is the same function as before, so there's minimal refactoring needed to change from promises to `async`/`await`. You can read more about the `async`/`await` syntax in the [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) references.
> **Note:** async/await has the same concurrency semantics as normal promise chains. `await` within one async function does not stop the entire program, only the parts that depend on its value, so other async jobs can still run while the `await` is pending.
## Error handling
You might recall seeing `failureCallback` three times in the pyramid of doom earlier, compared to only once at the end of the promise chain:
```js
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);
```
If there's an exception, the browser will look down the chain for `.catch()` handlers or `onRejected`. This is very much modeled after how synchronous code works:
```js
try {
const result = syncDoSomething();
const newResult = syncDoSomethingElse(result);
const finalResult = syncDoThirdThing(newResult);
console.log(`Got the final result: ${finalResult}`);
} catch (error) {
failureCallback(error);
}
```
This symmetry with asynchronous code culminates in the `async`/`await` syntax:
```js
async function foo() {
try {
const result = await doSomething();
const newResult = await doSomethingElse(result);
const finalResult = await doThirdThing(newResult);
console.log(`Got the final result: ${finalResult}`);
} catch (error) {
failureCallback(error);
}
}
```
Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations. All errors are now handled by the [`catch()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) method at the end of the chain, and you should almost never need to use `try`/`catch` without using `async`/`await`.
### Nesting
In the examples above involving `listOfIngredients`, the first one has one promise chain nested in the return value of another `then()` handler, while the second one uses an entirely flat chain. Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition.
Nesting is a control structure to limit the scope of `catch` statements. Specifically, a nested `catch` only catches failures in its scope and below, not errors higher up in the chain outside the nested scope. When used correctly, this gives greater precision in error recovery:
```js
doSomethingCritical()
.then((result) =>
doSomethingOptional(result)
.then((optionalResult) => doSomethingExtraNice(optionalResult))
.catch((e) => {}),
) // Ignore if optional stuff fails; proceed.
.then(() => moreCriticalStuff())
.catch((e) => console.error(`Critical failure: ${e.message}`));
```
Note that the optional steps here are nested β with the nesting caused not by the indentation, but by the placement of the outer `(` and `)` parentheses around the steps.
The inner error-silencing `catch` handler only catches failures from `doSomethingOptional()` and `doSomethingExtraNice()`, after which the code resumes with `moreCriticalStuff()`. Importantly, if `doSomethingCritical()` fails, its error is caught by the final (outer) `catch` only, and does not get swallowed by the inner `catch` handler.
In `async`/`await`, this code looks like:
```js
async function main() {
try {
const result = await doSomethingCritical();
try {
const optionalResult = await doSomethingOptional(result);
await doSomethingExtraNice(optionalResult);
} catch (e) {
// Ignore failures in optional steps and proceed.
}
await moreCriticalStuff();
} catch (e) {
console.error(`Critical failure: ${e.message}`);
}
}
```
> **Note:** If you don't have sophisticated error handling, you very likely don't need nested `then` handlers. Instead, use a flat chain and put the error handling logic at the end.
### Chaining after a catch
It's possible to chain _after_ a failure, i.e. a `catch`, which is useful to accomplish new actions even after an action failed in the chain. Read the following example:
```js
doSomething()
.then(() => {
throw new Error("Something failed");
console.log("Do this");
})
.catch(() => {
console.error("Do that");
})
.then(() => {
console.log("Do this, no matter what happened before");
});
```
This will output the following text:
```plain
Initial
Do that
Do this, no matter what happened before
```
> **Note:** The text "Do this" is not displayed because the "Something failed" error caused a rejection.
In `async`/`await`, this code looks like:
```js
async function main() {
try {
await doSomething();
throw new Error("Something failed");
console.log("Do this");
} catch (e) {
console.error("Do that");
}
console.log("Do this, no matter what happened before");
}
```
### Promise rejection events
If a promise rejection event is not handled by any handler, it bubbles to the top of the call stack, and the host needs to surface it. On the web, whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the [`window`](/en-US/docs/Web/API/Window) or, if being used in a web worker, it's the [`Worker`](/en-US/docs/Web/API/Worker) or other worker-based interface). The two events are:
- [`unhandledrejection`](/en-US/docs/Web/API/Window/unhandledrejection_event)
- : Sent when a promise is rejected but there is no rejection handler available.
- [`rejectionhandled`](/en-US/docs/Web/API/Window/rejectionhandled_event)
- : Sent when a handler is attached to a rejected promise that has already caused an `unhandledrejection` event.
In both cases, the event (of type [`PromiseRejectionEvent`](/en-US/docs/Web/API/PromiseRejectionEvent)) has as members a [`promise`](/en-US/docs/Web/API/PromiseRejectionEvent/promise) property indicating the promise that was rejected, and a [`reason`](/en-US/docs/Web/API/PromiseRejectionEvent/reason) property that provides the reason given for the promise to be rejected.
These make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. These handlers are global per context, so all errors will go to the same event handlers, regardless of source.
In [Node.js](/en-US/docs/Glossary/Node.js), handling promise rejection is slightly different. You capture unhandled rejections by adding a handler for the Node.js `unhandledRejection` event (notice the difference in capitalization of the name), like this:
```js
process.on("unhandledRejection", (reason, promise) => {
// Add code here to examine the "promise" and "reason" values
});
```
For Node.js, to prevent the error from being logged to the console (the default action that would otherwise occur), adding that `process.on()` listener is all that's necessary; there's no need for an equivalent of the browser runtime's [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault) method.
However, if you add that `process.on` listener but don't also have code within it to handle rejected promises, they will just be dropped on the floor and silently ignored. So ideally, you should add code within that listener to examine each rejected promise and make sure it was not caused by an actual code bug.
## Composition
There are four [composition tools](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) for running asynchronous operations concurrently: {{jsxref("Promise.all()")}}, {{jsxref("Promise.allSettled()")}}, {{jsxref("Promise.any()")}}, and {{jsxref("Promise.race()")}}.
We can start operations at the same time and wait for them all to finish like this:
```js
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
// use result1, result2 and result3
});
```
If one of the promises in the array rejects, `Promise.all()` immediately rejects the returned promise and aborts the other operations. This may cause unexpected state or behavior. {{jsxref("Promise.allSettled()")}} is another composition tool that ensures all operations are complete before resolving.
These methods all run promises concurrently β a sequence of promises are started simultaneously and do not wait for each other. Sequential composition is possible using some clever JavaScript:
```js
[func1, func2, func3]
.reduce((p, f) => p.then(f), Promise.resolve())
.then((result3) => {
/* use result3 */
});
```
In this example, we [reduce](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) an array of asynchronous functions down to a promise chain. The code above is equivalent to:
```js
Promise.resolve()
.then(func1)
.then(func2)
.then(func3)
.then((result3) => {
/* use result3 */
});
```
This can be made into a reusable compose function, which is common in functional programming:
```js
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
(...funcs) =>
(x) =>
funcs.reduce(applyAsync, Promise.resolve(x));
```
The `composeAsync()` function accepts any number of functions as arguments and returns a new function that accepts an initial value to be passed through the composition pipeline:
```js
const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);
```
Sequential composition can also be done more succinctly with async/await:
```js
let result;
for (const f of [func1, func2, func3]) {
result = await f(result);
}
/* use last result (i.e. result3) */
```
However, before you compose promises sequentially, consider if it's really necessary β it's always better to run promises concurrently so that they don't unnecessarily block each other unless one promise's execution depends on another's result.
## Creating a Promise around an old callback API
A {{jsxref("Promise")}} can be created from scratch using its [constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise). This should be needed only to wrap old APIs.
In an ideal world, all asynchronous functions would already return promises. Unfortunately, some APIs still expect success and/or failure callbacks to be passed in the old way. The most obvious example is the [`setTimeout()`](/en-US/docs/Web/API/setTimeout) function:
```js
setTimeout(() => saySomething("10 seconds passed"), 10 * 1000);
```
Mixing old-style callbacks and promises is problematic. If `saySomething()` fails or contains a programming error, nothing catches it. This is intrinsic to the design of `setTimeout`.
Luckily we can wrap `setTimeout` in a promise. The best practice is to wrap the callback-accepting functions at the lowest possible level, and then never call them directly again:
```js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(10 * 1000)
.then(() => saySomething("10 seconds"))
.catch(failureCallback);
```
The promise constructor takes an executor function that lets us resolve or reject a promise manually. Since `setTimeout()` doesn't really fail, we left out reject in this case. For more information on how the executor function works, see the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) reference.
## Timing
Lastly, we will look into the more technical details, about when the registered callbacks get called.
### Guarantees
In the callback-based API, when and how the callback gets called depends on the API implementor. For example, the callback may be called synchronously or asynchronously:
```js example-bad
function doSomething(callback) {
if (Math.random() > 0.5) {
callback();
} else {
setTimeout(() => callback(), 1000);
}
}
```
The above design is strongly discouraged because it leads to the so-called "state of Zalgo". In the context of designing asynchronous APIs, this means a callback is called synchronously in some cases but asynchronously in other cases, creating ambiguity for the caller. For further background, see the article [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony/), where the term was first formally presented. This API design makes side effects hard to analyze:
```js
let value = 1;
doSomething(() => {
value = 2;
});
console.log(value); // 1 or 2?
```
On the other hand, promises are a form of [inversion of control](https://en.wikipedia.org/wiki/Inversion_of_control) β the API implementor does not control when the callback gets called. Instead, the job of maintaining the callback queue and deciding when to call the callbacks is delegated to the promise implementation, and both the API user and API developer automatically gets strong semantic guarantees, including:
- Callbacks added with [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) will never be invoked before the [completion of the current run](/en-US/docs/Web/JavaScript/Event_loop#run-to-completion) of the JavaScript event loop.
- These callbacks will be invoked even if they were added _after_ the success or failure of the asynchronous operation that the promise represents.
- Multiple callbacks may be added by calling [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) several times. They will be invoked one after another, in the order in which they were inserted.
To avoid surprises, functions passed to [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) will never be called synchronously, even with an already-resolved promise:
```js
Promise.resolve().then(() => console.log(2));
console.log(1);
// Logs: 1, 2
```
Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later (only after the function which created it exits, and when the JavaScript execution stack is empty), just before control is returned to the event loop; i.e. pretty soon:
```js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(0).then(() => console.log(4));
Promise.resolve()
.then(() => console.log(2))
.then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
```
### Task queues vs. microtasks
Promise callbacks are handled as a [microtask](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) whereas [`setTimeout()`](/en-US/docs/Web/API/setTimeout) callbacks are handled as task queues.
```js
const promise = new Promise((resolve, reject) => {
console.log("Promise callback");
resolve();
}).then((result) => {
console.log("Promise callback (.then)");
});
setTimeout(() => {
console.log("event-loop cycle: Promise (fulfilled)", promise);
}, 0);
console.log("Promise (pending)", promise);
```
The code above will output:
```plain
Promise callback
Promise (pending) Promise {<pending>}
Promise callback (.then)
event-loop cycle: Promise (fulfilled) Promise {<fulfilled>}
```
For more details, refer to [Tasks vs. microtasks](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#tasks_vs_microtasks).
### When promises and tasks collide
If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally.
If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use [`queueMicrotask()`](/en-US/docs/Web/API/queueMicrotask) to enqueue a function as a microtask.
## See also
- {{jsxref("Promise")}}
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("Operators/await", "await")}}
- [Promises/A+ specification](https://promisesaplus.com/)
- [We have a problem with promises](https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html) on pouchdb.com (2015)
{{PreviousNext("Web/JavaScript/Guide/Using_classes", "Web/JavaScript/Guide/Typed_arrays")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/text_formatting/index.md | ---
title: Text formatting
slug: Web/JavaScript/Guide/Text_formatting
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_expressions")}}
This chapter introduces how to work with strings and text in JavaScript.
## Strings
JavaScript's [String](/en-US/docs/Glossary/String) type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.
### String literals
You can create simple strings using either single or double quotes:
```js-nolint
'foo'
"bar"
```
More advanced strings can be created using escape sequences:
#### Hexadecimal escape sequences
The number after \x is interpreted as a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) number.
```js-nolint
"\xA9" // "Β©"
```
#### Unicode escape sequences
The Unicode escape sequences require at least four hexadecimal digits following `\u`.
```js-nolint
"\u00A9" // "Β©"
```
#### Unicode code point escapes
With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to `0x10FFFF`. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.
See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.
```js-nolint
"\u{2F804}"
// the same with simple Unicode escapes
"\uD87E\uDC04"
```
### String objects
The {{jsxref("String")}} object is a wrapper around the string primitive data type.
```js
const foo = new String("foo"); // Creates a String object
console.log(foo); // [String: 'foo']
typeof foo; // 'object'
```
You can call any of the methods of the `String` object on a string literal valueβJavaScript automatically converts the string literal to a temporary `String` object, calls the method, then discards the temporary `String` object. You can also use the `length` property with a string literal.
You should use string literals unless you specifically need to use a `String` object, because `String` objects can have counterintuitive behavior. For example:
```js
const firstString = "2 + 2"; // Creates a string literal value
const secondString = new String("2 + 2"); // Creates a String object
eval(firstString); // Returns the number 4
eval(secondString); // Returns a String object containing "2 + 2"
```
A `String` object has one property, `length`, that indicates the number of UTF-16 code units in the string. For example, the following code assigns `helloLength` the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects:
```js
const hello = "Hello, World!";
const helloLength = hello.length;
hello[0] = "L"; // This has no effect, because strings are immutable
hello[0]; // This returns "H"
```
Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using square brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.
A `String` object has a variety of methods: for example those that return a variation on the string itself, such as `substring` and `toUpperCase`.
The following table summarizes the methods of {{jsxref("String")}} objects.
<table class="standard-table">
<caption>
<h4 id="Methods_of_String">Methods of <code>String</code></h4>
</caption>
<thead>
<tr>
<th scope="col">Method</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{{jsxref("String/charAt", "charAt()")}}, {{jsxref("String/charCodeAt", "charCodeAt()")}},
{{jsxref("String/codePointAt", "codePointAt()")}}
</td>
<td>
Return the character or character code at the specified position in
string.
</td>
</tr>
<tr>
<td>
{{jsxref("String/indexOf", "indexOf()")}},
{{jsxref("String/lastIndexOf", "lastIndexOf()")}}
</td>
<td>
Return the position of specified substring in the string or last
position of specified substring, respectively.
</td>
</tr>
<tr>
<td>
{{jsxref("String/startsWith", "startsWith()")}},
{{jsxref("String/endsWith", "endsWith()")}},
{{jsxref("String/includes", "includes()")}}
</td>
<td>
Returns whether or not the string starts, ends or contains a specified
string.
</td>
</tr>
<tr>
<td>{{jsxref("String/concat", "concat()")}}</td>
<td>Combines the text of two strings and returns a new string.</td>
</tr>
<tr>
<td>{{jsxref("String/split", "split()")}}</td>
<td>
Splits a <code>String</code> object into an array of strings by
separating the string into substrings.
</td>
</tr>
<tr>
<td>{{jsxref("String/slice", "slice()")}}</td>
<td>Extracts a section of a string and returns a new string.</td>
</tr>
<tr>
<td>
{{jsxref("String/substring", "substring()")}},
{{jsxref("String/substr", "substr()")}}
</td>
<td>
Return the specified subset of the string, either by specifying the
start and end indexes or the start index and a length.
</td>
</tr>
<tr>
<td>
{{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}},
{{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}},
{{jsxref("String/search", "search()")}}
</td>
<td>Work with regular expressions.</td>
</tr>
<tr>
<td>
{{jsxref("String/toLowerCase", "toLowerCase()")}},
{{jsxref("String/toUpperCase", "toUpperCase()")}}
</td>
<td>
<p>
Return the string in all lowercase or all uppercase, respectively.
</p>
</td>
</tr>
<tr>
<td>{{jsxref("String/normalize", "normalize()")}}</td>
<td>
Returns the Unicode Normalization Form of the calling string value.
</td>
</tr>
<tr>
<td>{{jsxref("String/repeat", "repeat()")}}</td>
<td>
Returns a string consisting of the elements of the object repeated the
given times.
</td>
</tr>
<tr>
<td>{{jsxref("String/trim", "trim()")}}</td>
<td>Trims whitespace from the beginning and end of the string.</td>
</tr>
</tbody>
</table>
### Multi-line template literals
[Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Template literals are enclosed by backtick ([grave accent](https://en.wikipedia.org/wiki/Grave_accent)) characters (`` ` ``) instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (`${expression}`).
#### Multi-lines
Any new line 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:
```js
console.log(
"string text line 1\n\
string text line 2",
);
// "string text line 1
// string text line 2"
```
To get the same effect with multi-line strings, you can now write:
```js
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
```
#### Embedded expressions
In order to embed expressions within normal strings, you would use the following syntax:
```js
const five = 5;
const ten = 10;
console.log(
"Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".",
);
// "Fifteen is 15 and not 20."
```
Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:
```js
const five = 5;
const ten = 10;
console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`);
// "Fifteen is 15 and not 20."
```
For more information, read about [Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) in the [JavaScript reference](/en-US/docs/Web/JavaScript/Reference).
## Internationalization
The {{jsxref("Intl")}} object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for {{jsxref("Intl.Collator")}}, {{jsxref("Intl.NumberFormat")}}, and {{jsxref("Intl.DateTimeFormat")}} objects are properties of the `Intl` object.
### Date and time formatting
The {{jsxref("Intl.DateTimeFormat")}} object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)
```js
// July 17, 2014 00:00:00 UTC:
const july172014 = new Date("2014-07-17");
const options = {
year: "2-digit",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
};
const americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
// Local timezone vary depending on your settings
// In CEST, logs: 07/17/14, 02:00 AM GMT+2
// In PDT, logs: 07/16/14, 05:00 PM GMT-7
console.log(americanDateTime(july172014));
```
### Number formatting
The {{jsxref("Intl.NumberFormat")}} object is useful for formatting numbers, for example currencies.
```js
const gasPrice = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 3,
});
console.log(gasPrice.format(5.259)); // $5.259
const hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec", {
style: "currency",
currency: "CNY",
});
console.log(hanDecimalRMBInChina.format(1314.25)); // οΏ₯ δΈ,δΈδΈε.δΊδΊ
```
### Collation
The {{jsxref("Intl.Collator")}} object is useful for comparing and sorting strings.
For example, there are actually two different sort orders in German, _phonebook_ and _dictionary_. Phonebook sort emphasizes sound, and it's as if "Γ€", "ΓΆ", and so on were expanded to "ae", "oe", and so on prior to sorting.
```js
const names = ["Hochberg", "HΓΆnigswald", "Holzman"];
const germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// "Hochberg, HΓΆnigswald, Holzman"
```
Some German words conjugate with extra umlauts, so in dictionaries it's sensible to order ignoring umlauts (except when ordering words differing _only_ by umlauts: _schon_ before _schΓΆn_).
```js
const germanDictionary = new Intl.Collator("de-DE-u-co-dict");
// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
console.log(names.sort(germanDictionary.compare).join(", "));
// "Hochberg, Holzman, HΓΆnigswald"
```
For more information about the {{jsxref("Intl")}} API, see also [Introducing the JavaScript Internationalization API](https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/).
{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_expressions")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/modules/index.md | ---
title: JavaScript modules
slug: Web/JavaScript/Guide/Modules
page-type: guide
browser-compat:
- javascript.statements.import
- javascript.statements.export
---
{{jsSidebar("JavaScript Guide")}}{{Previous("Web/JavaScript/Guide/Meta_programming")}}
This guide gives you all you need to get started with JavaScript module syntax.
## A background on modules
JavaScript programs started off pretty small β most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have complete applications being run in browsers with a lot of JavaScript, as well as JavaScript being used in other contexts ([Node.js](/en-US/docs/Glossary/Node.js), for example).
It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScript libraries and frameworks that enable module usage (for example, other [CommonJS](https://en.wikipedia.org/wiki/CommonJS) and [AMD](https://github.com/amdjs/amdjs-api/blob/master/AMD.md)-based module systems like [RequireJS](https://requirejs.org/), and more recently [Webpack](https://webpack.js.org/) and [Babel](https://babeljs.io/)).
The good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. This can only be a good thing β browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips.
Use of native JavaScript modules is dependent on the {{jsxref("Statements/import", "import")}} and {{jsxref("Statements/export", "export")}} statements; these are supported in browsers as shown in the compatibility table below.
## Browser compatibility
{{Compat}}
## Introducing an example
To demonstrate usage of modules, we've created a [simple set of examples](https://github.com/mdn/js-examples/tree/main/module-examples) that you can find on GitHub. These examples demonstrate a simple set of modules that create a [`<canvas>`](/en-US/docs/Web/HTML/Element/canvas) element on a webpage, and then draw (and report information about) different shapes on the canvas.
These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly.
> **Note:** If you want to download the examples and run them locally, you'll need to run them through a local web server.
## Basic example structure
In our first example (see [basic-modules](https://github.com/mdn/js-examples/tree/main/module-examples/basic-modules)) we have a file structure as follows:
```plain
index.html
main.js
modules/
canvas.js
square.js
```
> **Note:** All of the examples in this guide have basically the same structure; the above should start getting pretty familiar.
The modules directory's two modules are described below:
- `canvas.js` β contains functions related to setting up the canvas:
- `create()` β creates a canvas with a specified `width` and `height` inside a wrapper [`<div>`](/en-US/docs/Web/HTML/Element/div) with a specified ID, which is itself appended inside a specified parent element. Returns an object containing the canvas's 2D context and the wrapper's ID.
- `createReportList()` β creates an unordered list appended inside a specified wrapper element, which can be used to output report data into. Returns the list's ID.
- `square.js` β contains:
- `name` β a constant containing the string 'square'.
- `draw()` β draws a square on a specified canvas, with a specified size, position, and color. Returns an object containing the square's size, position, and color.
- `reportArea()` β writes a square's area to a specific report list, given its length.
- `reportPerimeter()` β writes a square's perimeter to a specific report list, given its length.
### Aside β .mjs versus .js
Throughout this article, we've used `.js` extensions for our module files, but in other resources you may see the `.mjs` extension used instead. [V8's documentation recommends this](https://v8.dev/features/modules#mjs), for example. The reasons given are:
- It is good for clarity, i.e. it makes it clear which files are modules, and which are regular JavaScript.
- It ensures that your module files are parsed as a module by runtimes such as [Node.js](https://nodejs.org/api/esm.html#esm_enabling), and build tools such as [Babel](https://babeljs.io/docs/en/options#sourcetype).
However, we decided to keep using `.js`, at least for the moment. To get modules to work correctly in a browser, you need to make sure that your server is serving them with a `Content-Type` header that contains a JavaScript MIME type such as `text/javascript`. If you don't, you'll get a strict MIME type checking error along the lines of "The server responded with a non-JavaScript MIME type" and the browser won't run your JavaScript. Most servers already set the correct type for `.js` files, but not yet for `.mjs` files. Servers that already serve `.mjs` files correctly include [GitHub Pages](https://pages.github.com/) and [`http-server`](https://github.com/http-party/http-server#readme) for Node.js.
This is OK if you are using such an environment already, or if you aren't but you know what you are doing and have access (i.e. you can configure your server to set the correct [`Content-Type`](/en-US/docs/Web/HTTP/Headers/Content-Type) for `.mjs` files). It could however cause confusion if you don't control the server you are serving files from, or are publishing files for public use, as we are here.
For learning and portability purposes, we decided to keep to `.js`.
If you really value the clarity of using `.mjs` for modules versus using `.js` for "normal" JavaScript files, but don't want to run into the problem described above, you could always use `.mjs` during development and convert them to `.js` during your build step.
It is also worth noting that:
- Some tools may never support `.mjs`.
- The `<script type="module">` attribute is used to denote when a module is being pointed to, as you'll see below.
## Exporting module features
The first thing you do to get access to module features is export them. This is done using the {{jsxref("Statements/export", "export")}} statement.
The easiest way to use it is to place it in front of any items you want exported out of the module, for example:
```js
export const name = "square";
export function draw(ctx, length, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, length, length);
return { length, x, y, color };
}
```
You can export functions, `var`, `let`, `const`, and β as we'll see later β classes. They need to be top-level items; you can't use `export` inside a function, for example.
A more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file, followed by a comma-separated list of the features you want to export wrapped in curly braces. For example:
```js
export { name, draw, reportArea, reportPerimeter };
```
## Importing features into your script
Once you've exported some features out of your module, you need to import them into your script to be able to use them. The simplest way to do this is as follows:
```js
import { name, draw, reportArea, reportPerimeter } from "./modules/square.js";
```
You use the {{jsxref("Statements/import", "import")}} statement, followed by a comma-separated list of the features you want to import wrapped in curly braces, followed by the keyword `from`, followed by the _module specifier_.
The _module specifier_ provides a string that the JavaScript environment can resolve to a path to the module file.
In a browser, this could be a path relative to the site root, which for our `basic-modules` example would be `/js-examples/module-examples/basic-modules`.
However, here we are instead using the dot (`.`) syntax to mean "the current location", followed by the relative path to the file we are trying to find. This is much better than writing out the entire absolute path each time, as relative paths are shorter and make the URL portable β the example will still work if you move it to a different location in the site hierarchy.
So for example:
```bash
/js-examples/module-examples/basic-modules/modules/square.js
```
becomes
```bash
./modules/square.js
```
You can see such lines in action in [`main.js`](https://github.com/mdn/js-examples/blob/main/module-examples/basic-modules/main.js).
> **Note:** In some module systems, you can use a module specifier like `modules/square` that isn't a relative or absolute path, and that doesn't have a file extension.
> This kind of specifier can be used in a browser environment if you first define an [import map](#importing_modules_using_import_maps).
Once you've imported the features into your script, you can use them just like they were defined inside the same file. The following is found in `main.js`, below the import lines:
```js
const myCanvas = create("myCanvas", document.body, 480, 320);
const reportList = createReportList(myCanvas.id);
const square1 = draw(myCanvas.ctx, 50, 50, 100, "blue");
reportArea(square1.length, reportList);
reportPerimeter(square1.length, reportList);
```
> **Note:** The imported values are read-only views of the features that were exported. Similar to `const` variables, you cannot re-assign the variable that was imported, but you can still modify properties of object values. The value can only be re-assigned by the module exporting it. See the [`import` reference](/en-US/docs/Web/JavaScript/Reference/Statements/import#imported_values_can_only_be_modified_by_the_exporter) for an example.
## Importing modules using import maps
Above we saw how a browser can import a module using a module specifier that is either an absolute URL, or a relative URL that is resolved using the base URL of the document:
```js
import { name as squareName, draw } from "./shapes/square.js";
import { name as circleName } from "https://example.com/shapes/circle.js";
```
[Import maps](/en-US/docs/Web/HTML/Element/script/type/importmap) allow developers to instead specify almost any text they want in the module specifier when importing a module; the map provides a corresponding value that will replace the text when the module URL is resolved.
For example, the `imports` key in the import map below defines a "module specifier map" JSON object where the property names can be used as module specifiers, and the corresponding values will be substituted when the browser resolves the module URL.
The values must be absolute or relative URLs.
Relative URLs are resolved to absolute URL addresses using the [base URL](/en-US/docs/Web/HTML/Element/base) of the document containing the import map.
```html
<script type="importmap">
{
"imports": {
"shapes": "./shapes/square.js",
"shapes/square": "./modules/shapes/square.js",
"https://example.com/shapes/square.js": "./shapes/square.js",
"https://example.com/shapes/": "/shapes/square/",
"../shapes/square": "./shapes/square.js"
}
}
</script>
```
The import map is defined using a [JSON object](/en-US/docs/Web/HTML/Element/script/type/importmap#import_map_json_representation) inside a `<script>` element with the `type` attribute set to [`importmap`](/en-US/docs/Web/HTML/Element/script/type/importmap).
There can only be one import map in the document, and because it is used to resolve which modules are loaded in both static and dynamic imports, it must be declared before any `<script>` elements that import modules.
Note that the import map only applies to the document β the specification does not cover how to apply an import map in a worker or worklet context. <!-- https://github.com/WICG/import-maps/issues/2 -->
With this map you can now use the property names above as module specifiers.
If there is no trailing forward slash on the module specifier key then the whole module specifier key is matched and substituted.
For example, below we match bare module names, and remap a URL to another path.
```js
// Bare module names as module specifiers
import { name as squareNameOne } from "shapes";
import { name as squareNameTwo } from "shapes/square";
// Remap a URL to another URL
import { name as squareNameThree } from "https://example.com/shapes/square.js";
```
If the module specifier has a trailing forward slash then the value must have one as well, and the key is matched as a "path prefix".
This allows remapping of whole classes of URLs.
```js
// Remap a URL as a prefix ( https://example.com/shapes/)
import { name as squareNameFour } from "https://example.com/shapes/moduleshapes/square.js";
```
It is possible for multiple keys in an import map to be valid matches for a module specifier.
For example, a module specifier of `shapes/circle/` could match the module specifier keys `shapes/` and `shapes/circle/`.
In this case the browser will select the most specific (longest) matching module specifier key.
Import maps allow modules to be imported using bare module names (as in Node.js), and can also simulate importing modules from packages, both with and without file extensions.
While not shown above, they also allow particular versions of a library to be imported, based on the path of the script that is importing the module.
Generally they let developers write more ergonomic import code, and make it easier to manage the different versions and dependencies of modules used by a site.
This can reduce the effort required to use the same JavaScript libraries in both browser and server.
The following sections expand on the various features outlined above.
### Feature detection
You can check support for import maps using the [`HTMLScriptElement.supports()`](/en-US/docs/Web/API/HTMLScriptElement/supports_static) static method (which is itself broadly supported):
```js
if (HTMLScriptElement.supports?.("importmap")) {
console.log("Browser supports import maps.");
}
```
### Importing modules as bare names
In some JavaScript environments, such as Node.js, you can use bare names for the module specifier.
This works because the environment can resolve module names to a standard location in the file system.
For example, you might use the following syntax to import the "square" module.
```js
import { name, draw, reportArea, reportPerimeter } from "square";
```
To use bare names on a browser you need an import map, which provides the information needed by the browser to resolve module specifiers to URLs (JavaScript will throw a `TypeError` if it attempts to import a module specifier that can't be resolved to a module location).
Below you can see a map that defines a `square` module specifier key, which in this case maps to a relative address value.
```html
<script type="importmap">
{
"imports": {
"square": "./shapes/square.js"
}
}
</script>
```
With this map we can now use a bare name when we import the module:
```js
import { name as squareName, draw } from "square";
```
### Remapping module paths
Module specifier map entries, where both the specifier key and its associated value have a trailing forward slash (`/`), can be used as a path-prefix.
This allows the remapping of a whole set of import URLs from one location to another.
It can also be used to emulate working with "packages and modules", such as you might see in the Node ecosystem.
> **Note:** The trailing `/` indicates that the module specifier key can be substituted as _part_ of a module specifier.
> If this is not present, the browser will only match (and substitute) the whole module specifier key.
#### Packages of modules
The following JSON import map definition maps `lodash` as a bare name, and the module specifier prefix `lodash/` to the path `/node_modules/lodash-es/` (resolved to the document base URL):
```json
{
"imports": {
"lodash": "/node_modules/lodash-es/lodash.js",
"lodash/": "/node_modules/lodash-es/"
}
}
```
With this mapping you can import both the whole "package", using the bare name, and modules within it (using the path mapping):
```js
import _ from "lodash";
import fp from "lodash/fp.js";
```
It is possible to import `fp` above without the `.js` file extension, but you would need to create a bare module specifier key for that file, such as `lodash/fp`, rather than using the path.
This may be reasonable for just one module, but scales poorly if you wish to import many modules.
#### General URL remapping
A module specifier key doesn't have to be path β it can also be an absolute URL (or a URL-like relative path like `./`, `../`, `/`).
This may be useful if you want to remap a module that has absolute paths to a resource with your own local resources.
```json
{
"imports": {
"https://www.unpkg.com/moment/": "/node_modules/moment/"
}
}
```
### Scoped modules for version management
Ecosystems like Node use package managers such as npm to manage modules and their dependencies.
The package manager ensures that each module is separated from other modules and their dependencies.
As a result, while a complex application might include the same module multiple times with several different versions in different parts of the module graph, users do not need to think about this complexity.
> **Note:** You can also achieve version management using relative paths, but this is subpar because, among other things, this forces a particular structure on your project, and prevents you from using bare module names.
Import maps similarly allow you to have multiple versions of dependencies in your application and refer to them using the same module specifier.
You implement this with the `scopes` key, which allows you to provide module specifier maps that will be used depending on the path of the script performing the import.
The example below demonstrates this.
```json
{
"imports": {
"coolmodule": "/node_modules/coolmodule/index.js"
},
"scopes": {
"/node_modules/dependency/": {
"coolmodule": "/node_modules/some/other/location/coolmodule/index.js"
}
}
}
```
With this mapping, if a script with an URL that contains `/node_modules/dependency/` imports `coolmodule`, the version in `/node_modules/some/other/location/coolmodule/index.js` will be used.
The map in `imports` is used as a fallback if there is no matching scope in the scoped map, or the matching scopes don't contain a matching specifier. For example, if `coolmodule` is imported from a script with a non-matching scope path, then the module specifier map in `imports` will be used instead, mapping to the version in `/node_modules/coolmodule/index.js`.
Note that the path used to select a scope does not affect how the address is resolved.
The value in the mapped path does not have to match the scopes path, and relative paths are still resolved to the base URL of the script that contains the import map.
Just as for module specifier maps, you can have many scope keys, and these may contain overlapping paths.
If multiple scopes match the referrer URL, then the most specific scope path is checked first (the longest scope key) for a matching specifier.
The browsers will fall back to the next most specific matching scoped path if there is no matching specifier, and so on.
If there is no matching specifier in any of the matching scopes, the browser checks for a match in the module specifier map in the `imports` key.
### Improve caching by mapping away hashed filenames
Script files used by websites often have hashed filenames to simplify caching.
The downside of this approach is that if a module changes, any modules that import it using its hashed filename will also need to be updated/regenerated.
This potentially results in a cascade of updates, which is wasteful of network resources.
Import maps provide a convenient solution to this problem.
Rather than depending on specific hashed filenames, applications and scripts instead depend on an un-hashed version of the module name (address).
An import map like the one below then provides a mapping to the actual script file.
```json
{
"imports": {
"main_script": "/node/srcs/application-fg7744e1b.js",
"dependency_script": "/node/srcs/dependency-3qn7e4b1q.js"
}
}
```
If `dependency_script` changes, then its hash contained in the file name changes as well. In this case, we only need to update the import map to reflect the changed name of the module.
We don't have to update the source of any JavaScript code that depends on it, because the specifier in the import statement does not change.
## Applying the module to your HTML
Now we just need to apply the `main.js` module to our HTML page. This is very similar to how we apply a regular script to a page, with a few notable differences.
First of all, you need to include `type="module"` in the [`<script>`](/en-US/docs/Web/HTML/Element/script) element, to declare this script as a module. To import the `main.js` script, we use this:
```html
<script type="module" src="main.js"></script>
```
You can also embed the module's script directly into the HTML file by placing the JavaScript code within the body of the `<script>` element:
```html
<script type="module">
/* JavaScript module code here */
</script>
```
The script into which you import the module features basically acts as the top-level module. If you omit it, Firefox for example gives you an error of "SyntaxError: import declarations may only appear at top level of a module".
You can only use `import` and `export` statements inside modules, not regular scripts.
> **Note:** Modules and their dependencies can be preloaded by specifying them in [`<link>`](/en-US/docs/Web/HTML/Element/link) elements with [`rel="modulepreloaded"`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload).
> This can significantly reduce load time when the modules are used.
## Other differences between modules and standard scripts
- You need to pay attention to local testing β if you try to load the HTML file locally (i.e. with a `file://` URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server.
- Also, note that you might get different behavior from sections of script defined inside modules as opposed to in standard scripts. This is because modules use {{jsxref("Strict_mode", "strict mode", "", 1)}} automatically.
- There is no need to use the `defer` attribute (see [`<script>` attributes](/en-US/docs/Web/HTML/Element/script#attributes)) when loading a module script; modules are deferred automatically.
- Modules are only executed once, even if they have been referenced in multiple `<script>` tags.
- Last but not least, let's make this clear β module features are imported into the scope of a single script β they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example. You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.
Module-defined variables are scoped to the module unless explicitly attached to the global object. On the other hand, globally-defined variables are available within the module. For example, given the following code:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<link rel="stylesheet" href="" />
</head>
<body>
<div id="main"></div>
<script>
// A var statement creates a global variable.
var text = "Hello";
</script>
<script type="module" src="./render.js"></script>
</body>
</html>
```
```js
/* render.js */
document.getElementById("main").innerText = text;
```
The page would still render `Hello`, because the global variables `text` and `document` are available in the module. (Also note from this example that a module doesn't necessarily need an import/export statement β the only thing needed is for the entry point to have `type="module"`.)
## Default exports versus named exports
The functionality we've exported so far has been comprised of **named exports** β each item (be it a function, `const`, etc.) has been referred to by its name upon export, and that name has been used to refer to it on import as well.
There is also a type of export called the **default export** β this is designed to make it easy to have a default function provided by a module, and also helps JavaScript modules to interoperate with existing CommonJS and AMD module systems (as explained nicely in [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) by Jason Orendorff; search for "Default exports").
Let's look at an example as we explain how it works. In our basic-modules `square.js` you can find a function called `randomSquare()` that creates a square with a random color, size, and position. We want to export this as our default, so at the bottom of the file we write this:
```js
export default randomSquare;
```
Note the lack of curly braces.
We could instead prepend `export default` onto the function and define it as an anonymous function, like this:
```js
export default function (ctx) {
// β¦
}
```
Over in our `main.js` file, we import the default function using this line:
```js
import randomSquare from "./modules/square.js";
```
Again, note the lack of curly braces. This is because there is only one default export allowed per module, and we know that `randomSquare` is it. The above line is basically shorthand for:
```js
import { default as randomSquare } from "./modules/square.js";
```
> **Note:** The as syntax for renaming exported items is explained below in the [Renaming imports and exports](#renaming_imports_and_exports) section.
## Avoiding naming conflicts
So far, our canvas shape drawing modules seem to be working OK. But what happens if we try to add a module that deals with drawing another shape, like a circle or triangle? These shapes would probably have associated functions like `draw()`, `reportArea()`, etc. too; if we tried to import different functions of the same name into the same top-level module file, we'd end up with conflicts and errors.
Fortunately there are a number of ways to get around this. We'll look at these in the following sections.
## Renaming imports and exports
Inside your `import` and `export` statement's curly braces, you can use the keyword `as` along with a new feature name, to change the identifying name you will use for a feature inside the top-level module.
So for example, both of the following would do the same job, albeit in a slightly different way:
```js
// inside module.js
export { function1 as newFunctionName, function2 as anotherNewFunctionName };
// inside main.js
import { newFunctionName, anotherNewFunctionName } from "./modules/module.js";
```
```js
// inside module.js
export { function1, function2 };
// inside main.js
import {
function1 as newFunctionName,
function2 as anotherNewFunctionName,
} from "./modules/module.js";
```
Let's look at a real example. In our [renaming](https://github.com/mdn/js-examples/tree/main/module-examples/renaming) directory you'll see the same module system as in the previous example, except that we've added `circle.js` and `triangle.js` modules to draw and report on circles and triangles.
Inside each of these modules, we've got features with the same names being exported, and therefore each has the same `export` statement at the bottom:
```js
export { name, draw, reportArea, reportPerimeter };
```
When importing these into `main.js`, if we tried to use
```js
import { name, draw, reportArea, reportPerimeter } from "./modules/square.js";
import { name, draw, reportArea, reportPerimeter } from "./modules/circle.js";
import { name, draw, reportArea, reportPerimeter } from "./modules/triangle.js";
```
The browser would throw an error such as "SyntaxError: redeclaration of import name" (Firefox).
Instead we need to rename the imports so that they are unique:
```js
import {
name as squareName,
draw as drawSquare,
reportArea as reportSquareArea,
reportPerimeter as reportSquarePerimeter,
} from "./modules/square.js";
import {
name as circleName,
draw as drawCircle,
reportArea as reportCircleArea,
reportPerimeter as reportCirclePerimeter,
} from "./modules/circle.js";
import {
name as triangleName,
draw as drawTriangle,
reportArea as reportTriangleArea,
reportPerimeter as reportTrianglePerimeter,
} from "./modules/triangle.js";
```
Note that you could solve the problem in the module files instead, e.g.
```js
// in square.js
export {
name as squareName,
draw as drawSquare,
reportArea as reportSquareArea,
reportPerimeter as reportSquarePerimeter,
};
```
```js
// in main.js
import {
squareName,
drawSquare,
reportSquareArea,
reportSquarePerimeter,
} from "./modules/square.js";
```
And it would work just the same. What style you use is up to you, however it arguably makes more sense to leave your module code alone, and make the changes in the imports. This especially makes sense when you are importing from third party modules that you don't have any control over.
## Creating a module object
The above method works OK, but it's a little messy and long-winded. An even better solution is to import each module's features inside a module object. The following syntax form does that:
```js
import * as Module from "./modules/module.js";
```
This grabs all the exports available inside `module.js`, and makes them available as members of an object `Module`, effectively giving it its own namespace. So for example:
```js
Module.function1();
Module.function2();
```
Again, let's look at a real example. If you go to our [module-objects](https://github.com/mdn/js-examples/tree/main/module-examples/module-objects) directory, you'll see the same example again, but rewritten to take advantage of this new syntax. In the modules, the exports are all in the following simple form:
```js
export { name, draw, reportArea, reportPerimeter };
```
The imports on the other hand look like this:
```js
import * as Canvas from "./modules/canvas.js";
import * as Square from "./modules/square.js";
import * as Circle from "./modules/circle.js";
import * as Triangle from "./modules/triangle.js";
```
In each case, you can now access the module's imports underneath the specified object name, for example:
```js
const square1 = Square.draw(myCanvas.ctx, 50, 50, 100, "blue");
Square.reportArea(square1.length, reportList);
Square.reportPerimeter(square1.length, reportList);
```
So you can now write the code just the same as before (as long as you include the object names where needed), and the imports are much neater.
## Modules and classes
As we hinted at earlier, you can also export and import classes; this is another option for avoiding conflicts in your code, and is especially useful if you've already got your module code written in an object-oriented style.
You can see an example of our shape drawing module rewritten with ES classes in our [classes](https://github.com/mdn/js-examples/tree/main/module-examples/classes) directory. As an example, the [`square.js`](https://github.com/mdn/js-examples/blob/main/module-examples/classes/modules/square.js) file now contains all its functionality in a single class:
```js
class Square {
constructor(ctx, listId, length, x, y, color) {
// β¦
}
draw() {
// β¦
}
// β¦
}
```
which we then export:
```js
export { Square };
```
Over in [`main.js`](https://github.com/mdn/js-examples/blob/main/module-examples/classes/main.js), we import it like this:
```js
import { Square } from "./modules/square.js";
```
And then use the class to draw our square:
```js
const square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, "blue");
square1.draw();
square1.reportArea();
square1.reportPerimeter();
```
## Aggregating modules
There will be times where you'll want to aggregate modules together. You might have multiple levels of dependencies, where you want to simplify things, combining several submodules into one parent module. This is possible using export syntax of the following forms in the parent module:
```js
export * from "x.js";
export { name } from "x.js";
```
For an example, see our [module-aggregation](https://github.com/mdn/js-examples/tree/main/module-examples/module-aggregation) directory. In this example (based on our earlier classes example) we've got an extra module called `shapes.js`, which aggregates all the functionality from `circle.js`, `square.js`, and `triangle.js` together. We've also moved our submodules inside a subdirectory inside the `modules` directory called `shapes`. So the module structure in this example is:
```plain
modules/
canvas.js
shapes.js
shapes/
circle.js
square.js
triangle.js
```
In each of the submodules, the export is of the same form, e.g.
```js
export { Square };
```
Next up comes the aggregation part. Inside [`shapes.js`](https://github.com/mdn/js-examples/blob/main/module-examples/module-aggregation/modules/shapes.js), we include the following lines:
```js
export { Square } from "./shapes/square.js";
export { Triangle } from "./shapes/triangle.js";
export { Circle } from "./shapes/circle.js";
```
These grab the exports from the individual submodules and effectively make them available from the `shapes.js` module.
> **Note:** The exports referenced in `shapes.js` basically get redirected through the file and don't really exist there, so you won't be able to write any useful related code inside the same file.
So now in the `main.js` file, we can get access to all three module classes by replacing
```js
import { Square } from "./modules/square.js";
import { Circle } from "./modules/circle.js";
import { Triangle } from "./modules/triangle.js";
```
with the following single line:
```js
import { Square, Circle, Triangle } from "./modules/shapes.js";
```
## Dynamic module loading
A recent addition to JavaScript modules functionality is dynamic module loading. This allows you to dynamically load modules only when they are needed, rather than having to load everything up front. This has some obvious performance advantages; let's read on and see how it works.
This new functionality allows you to call [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import) as a function, passing it the path to the module as a parameter. It returns a {{jsxref("Promise")}}, which fulfills with a module object (see [Creating a module object](#creating_a_module_object)) giving you access to that object's exports. For example:
```js
import("./modules/myModule.js").then((module) => {
// Do something with the module.
});
```
> **Note:** Dynamic import is permitted in the browser main thread, and in shared and dedicated workers.
> However `import()` will throw if called in a service worker or worklet.
<!-- https://whatpr.org/html/6395/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability) -->
Let's look at an example. In the [dynamic-module-imports](https://github.com/mdn/js-examples/tree/main/module-examples/dynamic-module-imports) directory we've got another example based on our classes example. This time however we are not drawing anything on the canvas when the example loads. Instead, we include three buttons β "Circle", "Square", and "Triangle" β that, when pressed, dynamically load the required module and then use it to draw the associated shape.
In this example we've only made changes to our [`index.html`](https://github.com/mdn/js-examples/blob/main/module-examples/dynamic-module-imports/index.html) and [`main.js`](https://github.com/mdn/js-examples/blob/main/module-examples/dynamic-module-imports/main.js) files β the module exports remain the same as before.
Over in `main.js` we've grabbed a reference to each button using a [`document.querySelector()`](/en-US/docs/Web/API/Document/querySelector) call, for example:
```js
const squareBtn = document.querySelector(".square");
```
We then attach an event listener to each button so that when pressed, the relevant module is dynamically loaded and used to draw the shape:
```js
squareBtn.addEventListener("click", () => {
import("./modules/square.js").then((Module) => {
const square1 = new Module.Square(
myCanvas.ctx,
myCanvas.listId,
50,
50,
100,
"blue",
);
square1.draw();
square1.reportArea();
square1.reportPerimeter();
});
});
```
Note that, because the promise fulfillment returns a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with `Module.` prepended to it, e.g. `Module.Square( /* β¦ */ )`.
Another advantage of dynamic imports is that they are always available, even in script environments. Therefore, if you have an existing `<script>` tag in your HTML that doesn't have `type="module"`, you can still reuse code distributed as modules by dynamically importing it.
```html
<script>
import("./modules/square.js").then((module) => {
// Do something with the module.
});
// Other code that operates on the global scope and is not
// ready to be refactored into modules yet.
var btn = document.querySelector(".square");
</script>
```
## Top level await
Top level await is a feature available within modules. This means the `await` keyword can be used. It allows modules to act as big [asynchronous functions](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing) meaning code can be evaluated before use in parent modules, but without blocking sibling modules from loading.
Let's take a look at an example. You can find all the files and code described in this section within the [`top-level-await`](https://github.com/mdn/js-examples/tree/main/module-examples/top-level-await) directory, which extends from the previous examples.
Firstly we'll declare our color palette in a separate [`colors.json`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/data/colors.json) file:
```json
{
"yellow": "#F4D03F",
"green": "#52BE80",
"blue": "#5499C7",
"red": "#CD6155",
"orange": "#F39C12"
}
```
Then we'll create a module called [`getColors.js`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/modules/getColors.js) which uses a fetch request to load the [`colors.json`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/data/colors.json) file and return the data as an object.
```js
// fetch request
const colors = fetch("../data/colors.json").then((response) => response.json());
export default await colors;
```
Notice the last export line here.
We're using the keyword `await` before specifying the constant `colors` to export. This means any other modules which include this one will wait until `colors` has been downloaded and parsed before using it.
Let's include this module in our [`main.js`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/main.js) file:
```js
import colors from "./modules/getColors.js";
import { Canvas } from "./modules/canvas.js";
const circleBtn = document.querySelector(".circle");
// β¦
```
We'll use `colors` instead of the previously used strings when calling our shape functions:
```js
const square1 = new Module.Square(
myCanvas.ctx,
myCanvas.listId,
50,
50,
100,
colors.blue,
);
const circle1 = new Module.Circle(
myCanvas.ctx,
myCanvas.listId,
75,
200,
100,
colors.green,
);
const triangle1 = new Module.Triangle(
myCanvas.ctx,
myCanvas.listId,
100,
75,
190,
colors.yellow,
);
```
This is useful because the code within [`main.js`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/main.js) won't execute until the code in [`getColors.js`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/modules/getColors.js) has run. However it won't block other modules being loaded. For instance our [`canvas.js`](https://github.com/mdn/js-examples/blob/main/module-examples/top-level-await/modules/canvas.js) module will continue to load while `colors` is being fetched.
## Import declarations are hoisted
Import declarations are [hoisted](/en-US/docs/Glossary/Hoisting). In this case, it means that the imported values are available in the module's code even before the place that declares them, and that the imported module's side effects are produced before the rest of the module's code starts running.
So for example, in `main.js`, importing `Canvas` in the middle of the code would still work:
```js
// β¦
const myCanvas = new Canvas("myCanvas", document.body, 480, 320);
myCanvas.create();
import { Canvas } from "./modules/canvas.js";
myCanvas.createReportList();
// β¦
```
Still, it is considered good practice to put all your imports at the top of the code, which makes it easier to analyze dependencies.
## Cyclic imports
Modules can import other modules, and those modules can import other modules, and so on. This forms a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) called the "dependency graph". In an ideal world, this graph is [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph). In this case, the graph can be evaluated using a depth-first traversal.
However, cycles are often inevitable. Cyclic import arises if module `a` imports module `b`, but `b` directly or indirectly depends on `a`. For example:
```js
// -- a.js --
import { b } from "./b.js";
// -- b.js --
import { a } from "./a.js";
// Cycle:
// a.js βββ> b.js
// ^ β
// βββββββββββ
```
Cyclic imports don't always fail. The imported variable's value is only retrieved when the variable is actually used (hence allowing [live bindings](/en-US/docs/Web/JavaScript/Reference/Statements/import#imported_values_can_only_be_modified_by_the_exporter)), and only if the variable remains uninitialized at that time will a [`ReferenceError`](/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init) be thrown.
```js
// -- a.js --
import { b } from "./b.js";
setTimeout(() => {
console.log(b); // 1
}, 10);
export const a = 2;
// -- b.js --
import { a } from "./a.js";
setTimeout(() => {
console.log(a); // 2
}, 10);
export const b = 1;
```
In this example, both `a` and `b` are used asynchronously. Therefore, at the time the module is evaluated, neither `b` nor `a` is actually read, so the rest of the code is executed as normal, and the two `export` declarations produce the values of `a` and `b`. Then, after the timeout, both `a` and `b` are available, so the two `console.log` statements also execute as normal.
If you change the code to use `a` synchronously, the module evaluation fails:
```js
// -- a.js (entry module) --
import { b } from "./b.js";
export const a = 2;
// -- b.js --
import { a } from "./a.js";
console.log(a); // ReferenceError: Cannot access 'a' before initialization
export const b = 1;
```
This is because when JavaScript evaluates `a.js`, it needs to first evaluate `b.js`, the dependency of `a.js`. However, `b.js` uses `a`, which is not yet available.
On the other hand, if you change the code to use `b` synchronously but `a` asynchronously, the module evaluation succeeds:
```js
// -- a.js (entry module) --
import { b } from "./b.js";
console.log(b); // 1
export const a = 2;
// -- b.js --
import { a } from "./a.js";
setTimeout(() => {
console.log(a); // 2
}, 10);
export const b = 1;
```
This is because the evaluation of `b.js` completes normally, so the value of `b` is available when `a.js` is evaluated.
You should usually avoid cyclic imports in your project, because they make your code more error-prone. Some common cycle-elimination techniques are:
- Merge the two modules into one.
- Move the shared code into a third module.
- Move some code from one module to the other.
However, cyclic imports can also occur if the libraries depend on each other, which is harder to fix.
## Authoring "isomorphic" modules
The introduction of modules encourages the JavaScript ecosystem to distribute and reuse code in a modular fashion. However, that doesn't necessarily mean a piece of JavaScript code can run in every environment. Suppose you discovered a module that generates SHA hashes of your user's password. Can you use it in the browser front end? Can you use it on your Node.js server? The answer is: it depends.
Modules still have access to global variables, as demonstrated previously. If the module references globals like `window`, it can run in the browser, but will throw an error in your Node.js server, because `window` is not available there. Similarly, if the code requires access to `process` to be functional, it can only be used in Node.js.
In order to maximize the reusability of a module, it is often advised to make the code "isomorphic" β that is, exhibits the same behavior in every runtime. This is commonly achieved in three ways:
- Separate your modules into "core" and "binding". For the "core", focus on pure JavaScript logic like computing the hash, without any DOM, network, filesystem access, and expose utility functions. For the "binding" part, you can read from and write to the global context. For example, the "browser binding" may choose to read the value from an input box, while the "Node binding" may read it from `process.env`, but values read from either place will be piped to the same core function and handled in the same way. The core can be imported in every environment and used in the same way, while only the binding, which is usually lightweight, needs to be platform-specific.
- Detect whether a particular global exists before using it. For example, if you test that `typeof window === "undefined"`, you know that you are probably in a Node.js environment, and should not read DOM.
```js
// myModule.js
let password;
if (typeof process !== "undefined") {
// We are running in Node.js; read it from `process.env`
password = process.env.PASSWORD;
} else if (typeof window !== "undefined") {
// We are running in the browser; read it from the input box
password = document.getElementById("password").value;
}
```
This is preferable if the two branches actually end up with the same behavior ("isomorphic"). If it's impossible to provide the same functionality, or if doing so involves loading significant amounts of code while a large part remains unused, better use different "bindings" instead.
- Use a polyfill to provide a fallback for missing features. For example, if you want to use the [`fetch`](/en-US/docs/Web/API/Fetch_API) function, which is only supported in Node.js since v18, you can use a similar API, like the one provided by [`node-fetch`](https://www.npmjs.com/package/node-fetch). You can do so conditionally through dynamic imports:
```js
// myModule.js
if (typeof fetch === "undefined") {
// We are running in Node.js; use node-fetch
globalThis.fetch = (await import("node-fetch")).default;
}
// β¦
```
The [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) variable is a global object that is available in every environment and is useful if you want to read or create global variables within modules.
These practices are not unique to modules. Still, with the trend of code reusability and modularization, you are encouraged to make your code cross-platform so that it can be enjoyed by as many people as possible. Runtimes like Node.js are also actively implementing web APIs where possible to improve interoperability with the web.
## Troubleshooting
Here are a few tips that may help you if you are having trouble getting your modules to work. Feel free to add to the list if you discover more!
- We mentioned this before, but to reiterate: `.mjs` files need to be loaded with a MIME-type of `text/javascript` (or another JavaScript-compatible MIME-type, but `text/javascript` is recommended), otherwise you'll get a strict MIME type checking error like "The server responded with a non-JavaScript MIME type".
- If you try to load the HTML file locally (i.e. with a `file://` URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server. GitHub pages is ideal as it also serves `.mjs` files with the correct MIME type.
- Because `.mjs` is a non-standard file extension, some operating systems might not recognize it, or try to replace it with something else. For example, we found that macOS was silently adding on `.js` to the end of `.mjs` files and then automatically hiding the file extension. So all of our files were actually coming out as `x.mjs.js`. Once we turned off automatically hiding file extensions, and trained it to accept `.mjs`, it was OK.
## See also
- [JavaScript modules](https://v8.dev/features/modules) on v8.dev (2018)
- [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) on hacks.mozilla.org (2018)
- [ES6 in Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) on hacks.mozilla.org (2015)
- [Exploring JS, Ch.16: Modules](https://exploringjs.com/es6/ch_modules.html) by Dr. Axel Rauschmayer
{{Previous("Web/JavaScript/Guide/Meta_programming")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/control_flow_and_error_handling/index.md | ---
title: Control flow and error handling
slug: Web/JavaScript/Guide/Control_flow_and_error_handling
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
JavaScript supports a compact set of statements, specifically
control flow statements, that you can use to incorporate a great deal of interactivity
in your application. This chapter provides an overview of these statements.
The [JavaScript reference](/en-US/docs/Web/JavaScript/Reference/Statements)
contains exhaustive details about the statements in this chapter. The semicolon
(`;`) character is used to separate statements in JavaScript code.
Any JavaScript expression is also a statement.
See [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators)
for complete information about expressions.
## Block statement
The most basic statement is a _block statement_, which is used to group
statements. The block is delimited by a pair of curly braces:
```js
{
statement1;
statement2;
// β¦
statementN;
}
```
### Example
Block statements are commonly used with control flow statements (`if`,
`for`, `while`).
```js
while (x < 10) {
x++;
}
```
Here, `{ x++; }` is the block statement.
> **Note:** [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var)-declared variables are not block-scoped, but are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:
>
> ```js
> var x = 1;
> {
> var x = 2;
> }
> console.log(x); // 2
> ```
>
> This outputs `2` because the `var x` statement within the block is in the same scope as the `var x` statement before the block. (In C or Java, the equivalent code would have output `1`.)
>
> This scoping effect can be mitigated by using {{jsxref("Statements/let", "let")}} or {{jsxref("Statements/const", "const")}}.
## Conditional statements
A conditional statement is a set of commands that executes if a specified condition is
true. JavaScript supports two conditional statements: `if...else` and
`switch`.
### if...else statement
Use the `if` statement to execute a statement if a logical condition is
`true`. Use the optional `else` clause to execute a statement if
the condition is `false`.
An `if` statement looks like this:
```js
if (condition) {
statement1;
} else {
statement2;
}
```
Here, the `condition` can be any expression that evaluates to
`true` or `false`. (See [Boolean](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#description)
for an explanation of what evaluates to `true` and `false`.)
If `condition` evaluates to `true`,
`statement_1` is executed. Otherwise,
`statement_2` is executed. `statement_1` and
`statement_2` can be any statement, including further nested
`if` statements.
You can also compound the statements using `else if` to have multiple
conditions tested in sequence, as follows:
```js
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}
```
In the case of multiple conditions, only the first logical condition which evaluates to
`true` will be executed. To execute multiple statements, group them within a
block statement (`{ /* β¦ */ }`).
#### Best practice
In general, it's good practice to always use block statementsβ_especially_ when
nesting `if` statements:
```js
if (condition) {
// Statements for when condition is true
// β¦
} else {
// Statements for when condition is false
// β¦
}
```
In general it's good practice to not have an `if...else` with an assignment like `x = y` as a condition:
```js-nolint example-bad
if (x = y) {
// statements here
}
```
However, in the rare case you find yourself wanting to do something like that, the [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while) documentation has a [Using an assignment as a condition](/en-US/docs/Web/JavaScript/Reference/Statements/while#using_an_assignment_as_a_condition) section with guidance on a general best-practice syntax you should know about and follow.
#### Falsy values
The following values evaluate to `false` (also known as [Falsy](/en-US/docs/Glossary/Falsy) values):
- `false`
- `undefined`
- `null`
- `0`
- `NaN`
- the empty string (`""`)
All other valuesβincluding all objectsβevaluate to `true` when passed to a
conditional statement.
> **Note:** Do not confuse the primitive boolean values
> `true` and `false` with the true and false values of the
> {{jsxref("Boolean")}} object!
>
> For example:
>
> ```js
> const b = new Boolean(false);
> if (b) {
> // this condition evaluates to true
> }
> if (b == true) {
> // this condition evaluates to false
> }
> ```
#### Example
In the following example, the function `checkData` returns `true`
if the number of characters in a `Text` object is three. Otherwise, it
displays an alert and returns `false`.
```js
function checkData() {
if (document.form1.threeChar.value.length === 3) {
return true;
} else {
alert(
`Enter exactly three characters. ${document.form1.threeChar.value} is not valid.`,
);
return false;
}
}
```
### switch statement
A `switch` statement allows a program to evaluate an expression and attempt
to match the expression's value to a `case` label. If a match is found, the
program executes the associated statement.
A `switch` statement looks like this:
```js
switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
// β¦
default:
statementsDefault;
}
```
JavaScript evaluates the above switch statement as follows:
- The program first looks for a `case` clause with a label matching the
value of expression and then transfers control to that clause, executing the
associated statements.
- If no matching label is found, the program looks for the optional
`default` clause:
- If a `default` clause is found, the program transfers control to that
clause, executing the associated statements.
- If no `default` clause is found, the program resumes execution at the
statement following the end of `switch`.
- (By convention, the `default` clause is written as the last clause,
but it does not need to be so.)
#### break statements
The optional `break` statement associated with each `case` clause
ensures that the program breaks out of `switch` once the matched statement is
executed, and then continues execution at the statement following `switch`.
If `break` is omitted, the program continues execution inside the
`switch` statement (and will execute statements under the next `case`, and so on).
##### Example
In the following example, if `fruitType` evaluates to
`'Bananas'`, the program matches the value with case `'Bananas'`
and executes the associated statement. When `break` is encountered, the
program exits the `switch` and continues execution from the statement
following `switch`. If `break` were omitted, the statement for
`case 'Cherries'` would also be executed.
```js
switch (fruitType) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Apples":
console.log("Apples are $0.32 a pound.");
break;
case "Bananas":
console.log("Bananas are $0.48 a pound.");
break;
case "Cherries":
console.log("Cherries are $3.00 a pound.");
break;
case "Mangoes":
console.log("Mangoes are $0.56 a pound.");
break;
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
break;
default:
console.log(`Sorry, we are out of ${fruitType}.`);
}
console.log("Is there anything else you'd like?");
```
## Exception handling statements
You can throw exceptions using the `throw` statement and handle them using
the `try...catch` statements.
- [`throw` statement](#throw_statement)
- [`try...catch` statement](#try...catch_statement)
### Exception types
Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects
are created equal. While it is common to throw numbers or strings as errors, it is
frequently more effective to use one of the exception types specifically created for
this purpose:
- [ECMAScript exceptions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#error_types)
- [`DOMException`](/en-US/docs/Web/API/DOMException)
### throw statement
Use the `throw` statement to throw an exception. A `throw`
statement specifies the value to be thrown:
```js
throw expression;
```
You may throw any expression, not just expressions of a specific type. The following
code throws several exceptions of varying types:
```js
throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
toString() {
return "I'm an object!";
},
};
```
### `try...catch` statement
The `try...catch` statement marks a block of statements to try, and
specifies one or more responses should an exception be thrown. If an exception is
thrown, the `try...catch` statement catches it.
The `try...catch` statement consists of a `try` block, which
contains one or more statements, and a `catch` block, containing statements
that specify what to do if an exception is thrown in the `try` block.
In other words, you want the `try` block to succeedβbut if it does not, you
want control to pass to the `catch` block. If any statement within the
`try` block (or in a function called from within the `try` block)
throws an exception, control _immediately_ shifts to the `catch`
block. If no exception is thrown in the `try` block, the `catch`
block is skipped. The `finally` block executes after the `try` and
`catch` blocks execute but before the statements following the
`try...catch` statement.
The following example uses a `try...catch` statement. The example calls a
function that retrieves a month name from an array based on the value passed to the
function. If the value does not correspond to a month number
(`1` β `12`), an exception is thrown with the value
`'InvalidMonthNo'` and the statements in the `catch` block set the
`monthName` variable to `'unknown'`.
```js-nolint
function getMonthName(mo) {
mo--; // Adjust month number for array index (so that 0 = Jan, 11 = Dec)
const months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
if (months[mo]) {
return months[mo];
} else {
throw new Error("InvalidMonthNo"); // throw keyword is used here
}
}
try {
// statements to try
monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
monthName = "unknown";
logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}
```
#### The catch block
You can use a `catch` block to handle all exceptions that may be generated
in the `try` block.
```js-nolint
catch (exception) {
statements
}
```
The `catch` block specifies an identifier (`exception`
in the preceding syntax) that holds the value specified by the `throw`
statement. You can use this identifier to get information about the exception that was
thrown.
JavaScript creates this identifier when the `catch` block is entered. The
identifier lasts only for the duration of the `catch` block. Once the
`catch` block finishes executing, the identifier no longer exists.
For example, the following code throws an exception. When the exception occurs, control
transfers to the `catch` block.
```js
try {
throw "myException"; // generates an exception
} catch (err) {
// statements to handle any exceptions
logMyErrors(err); // pass exception object to error handler
}
```
> **Note:** When logging errors to the console inside
> a `catch` block, using `console.error()` rather than
> `console.log()` is advised for debugging. It formats the message as an
> error, and adds it to the list of error messages generated by the page.
#### The finally block
The `finally` block contains statements to be executed _after_ the
`try` and `catch` blocks execute. Additionally, the
`finally` block executes _before_ the code that follows the
`tryβ¦catchβ¦finally` statement.
It is also important to note that the `finally` block will execute
_whether or not_ an exception is thrown. If an exception is thrown, however, the
statements in the `finally` block execute even if no `catch` block
handles the exception that was thrown.
You can use the `finally` block to make your script fail gracefully when an
exception occurs. For example, you may need to release a resource that your script has
tied up.
The following example opens a file and then executes statements that use the file.
(Server-side JavaScript allows you to access files.) If an exception is thrown while the
file is open, the `finally` block closes the file before the script fails.
Using `finally` here _ensures_ that the file is never left open, even
if an error occurs.
```js
openMyFile();
try {
writeMyFile(theData); // This may throw an error
} catch (e) {
handleError(e); // If an error occurred, handle it
} finally {
closeMyFile(); // Always close the resource
}
```
If the `finally` block returns a value, this value becomes the return value
of the entire `tryβ¦catchβ¦finally` production, regardless of any
`return` statements in the `try` and `catch` blocks:
```js
function f() {
try {
console.log(0);
throw "bogus";
} catch (e) {
console.log(1);
// This return statement is suspended
// until finally block has completed
return true;
console.log(2); // not reachable
} finally {
console.log(3);
return false; // overwrites the previous "return"
console.log(4); // not reachable
}
// "return false" is executed now
console.log(5); // not reachable
}
console.log(f()); // 0, 1, 3, false
```
Overwriting of return values by the `finally` block also applies to
exceptions thrown or re-thrown inside of the `catch` block:
```js
function f() {
try {
throw "bogus";
} catch (e) {
console.log('caught inner "bogus"');
// This throw statement is suspended until
// finally block has completed
throw e;
} finally {
return false; // overwrites the previous "throw"
}
// "return false" is executed now
}
try {
console.log(f());
} catch (e) {
// this is never reached!
// while f() executes, the `finally` block returns false,
// which overwrites the `throw` inside the above `catch`
console.log('caught outer "bogus"');
}
// Logs:
// caught inner "bogus"
// false
```
#### Nesting try...catch statements
You can nest one or more `try...catch` statements.
If an inner `try` block does _not_ have a corresponding
`catch` block:
1. it _must_ contain a `finally` block, and
2. the enclosing `try...catch` statement's `catch` block is
checked for a match.
For more information, see [nested try-blocks](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#nested_try_blocks)
on the [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)
reference page.
### Utilizing Error objects
Depending on the type of error, you may be able to use the `name` and
`message` properties to get a more refined message.
The `name` property provides the general class of `Error` (such
as `DOMException` or `Error`), while `message`
generally provides a more succinct message than one would get by converting the error
object to a string.
If you are throwing your own exceptions, in order to take advantage of these properties
(such as if your `catch` block doesn't discriminate between your own
exceptions and system ones), you can use the `Error` constructor.
For example:
```js
function doSomethingErrorProne() {
if (ourCodeMakesAMistake()) {
throw new Error("The message");
} else {
doSomethingToGetAJavaScriptError();
}
}
try {
doSomethingErrorProne();
} catch (e) {
// Now, we actually use `console.error()`
console.error(e.name); // 'Error'
console.error(e.message); // 'The message', or a JavaScript error message
}
```
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/indexed_collections/index.md | ---
title: Indexed collections
slug: Web/JavaScript/Guide/Indexed_collections
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_expressions", "Web/JavaScript/Guide/Keyed_collections")}}
This chapter introduces collections of data which are ordered by an index value. This includes arrays and array-like constructs such as {{jsxref("Array")}} objects and {{jsxref("TypedArray")}} objects.
An _array_ is an ordered list of values that you refer to with a name and an index.
For example, consider an array called `emp`, which contains employees' names indexed by their numerical employee number. So `emp[0]` would be employee number zero, `emp[1]` employee number one, and so on.
JavaScript does not have an explicit array data type. However, you can use the predefined `Array` object and its methods to work with arrays in your applications. The `Array` object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions.
We will be focusing on arrays in this article, but many of the same concepts apply to typed arrays as well, since arrays and typed arrays share many similar methods. For more information on typed arrays, see the [typed array guide](/en-US/docs/Web/JavaScript/Guide/Typed_arrays).
## Creating an array
The following statements create equivalent arrays:
```js
const arr1 = new Array(element0, element1, /* β¦, */ elementN);
const arr2 = Array(element0, element1, /* β¦, */ elementN);
const arr3 = [element0, element1, /* β¦, */ elementN];
```
`element0, element1, β¦, elementN` is a list of values for the array's elements. When these values are specified, the array is initialized with them as the array's elements. The array's `length` property is set to the number of arguments.
The bracket syntax is called an "array literal" or "array initializer." It's shorter than other forms of array creation, and so is generally preferred. See [Array literals](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) for details.
To create an array with non-zero length, but without any items, either of the following can be used:
```js
// This...
const arr1 = new Array(arrayLength);
// ...results in the same array as this
const arr2 = Array(arrayLength);
// This has exactly the same effect
const arr3 = [];
arr3.length = arrayLength;
```
> **Note:** In the above code, `arrayLength` must be a `Number`. Otherwise, an array with a single element (the provided value) will be created. Calling `arr.length` will return `arrayLength`, but the array doesn't contain any elements. A {{jsxref("Statements/for...in", "for...in")}} loop will not find any property on the array.
In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object:
```js
const obj = {};
// β¦
obj.prop = [element0, element1, /* β¦, */ elementN];
// OR
const obj = { prop: [element0, element1, /* β¦, */ elementN] };
```
If you wish to initialize an array with a single element, and the element happens to be a `Number`, you must use the bracket syntax. When a single `Number` value is passed to the `Array()` constructor or function, it is interpreted as an `arrayLength`, not as a single element.
This creates an array with only one element: the number 42.
```js
const arr = [42];
```
This creates an array with no elements and `arr.length` set to 42.
```js
const arr = Array(42);
```
This is equivalent to:
```js
const arr = [];
arr.length = 42;
```
Calling `Array(N)` results in a `RangeError`, if `N` is a non-whole number whose fractional portion is non-zero. The following example illustrates this behavior.
```js
const arr = Array(9.3); // RangeError: Invalid array length
```
If your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. Alternatively, create an empty array first before adding the single element to it.
You can also use the {{jsxref("Array.of")}} static method to create arrays with single element.
```js
const wisenArray = Array.of(9.3); // wisenArray contains only one element 9.3
```
## Referring to array elements
Because elements are also properties, you can access them using [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). Suppose you define the following array:
```js
const myArray = ["Wind", "Rain", "Fire"];
```
You can refer to the first element of the array as `myArray[0]`, the second element of the array as `myArray[1]`, etc⦠The index of the elements begins with zero.
> **Note:** You can also use [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) to access other properties of the array, like with an object.
>
> ```js
> const arr = ["one", "two", "three"];
> arr[2]; // three
> arr["length"]; // 3
> ```
## Populating an array
You can populate an array by assigning values to its elements. For example:
```js
const emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";
```
> **Note:** If you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.
>
> ```js
> const arr = [];
> arr[3.4] = "Oranges";
> console.log(arr.length); // 0
> console.log(Object.hasOwn(arr, 3.4)); // true
> ```
You can also populate an array when you create it:
```js
const myArray = new Array("Hello", myVar, 3.14159);
// OR
const myArray = ["Mango", "Apple", "Orange"];
```
### Understanding length
At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name.
The `length` property is special. Its value is always a positive integer greater than the index of the last element if one exists. (In the example below, `'Dusty'` is indexed at `30`, so `cats.length` returns `30 + 1`).
Remember, JavaScript Array indexes are 0-based: they start at `0`, not `1`. This means that the `length` property will be one more than the highest index stored in the array:
```js
const cats = [];
cats[30] = ["Dusty"];
console.log(cats.length); // 31
```
You can also assign to the `length` property.
Writing a value that is shorter than the number of stored items truncates the array. Writing `0` empties it entirely:
```js
const cats = ["Dusty", "Misty", "Twiggy"];
console.log(cats.length); // 3
cats.length = 2;
console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy has been removed
cats.length = 0;
console.log(cats); // []; the cats array is empty
cats.length = 3;
console.log(cats); // [ <3 empty items> ]
```
### Iterating over arrays
A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:
```js
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
```
If you know that none of the elements in your array evaluate to `false` in a boolean contextβif your array consists only of [DOM](/en-US/docs/Web/API/Document_Object_Model) nodes, for exampleβyou can use a more efficient idiom:
```js
const divs = document.getElementsByTagName("div");
for (let i = 0, div; (div = divs[i]); i++) {
/* Process div in some way */
}
```
This avoids the overhead of checking the length of the array, and ensures that the `div` variable is reassigned to the current item each time around the loop for added convenience.
The [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method provides another way of iterating over an array:
```js
const colors = ["red", "green", "blue"];
colors.forEach((color) => console.log(color));
// red
// green
// blue
```
The function passed to `forEach` is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a `forEach` loop.
Note that the elements of an array that are omitted when the array is defined are not listed when iterating by `forEach`, but _are_ listed when `undefined` has been manually assigned to the element:
```js
const sparseArray = ["first", "second", , "fourth"];
sparseArray.forEach((element) => {
console.log(element);
});
// Logs:
// first
// second
// fourth
if (sparseArray[2] === undefined) {
console.log("sparseArray[2] is undefined"); // true
}
const nonsparseArray = ["first", "second", undefined, "fourth"];
nonsparseArray.forEach((element) => {
console.log(element);
});
// Logs:
// first
// second
// undefined
// fourth
```
Since JavaScript array elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using {{jsxref("Statements/for...in", "for...in")}} loops, because normal elements and all enumerable properties will be listed.
### Array methods
The {{jsxref("Array")}} object has the following methods:
The [`concat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) method joins two or more arrays and returns a new array.
```js
let myArray = ["1", "2", "3"];
myArray = myArray.concat("a", "b", "c");
// myArray is now ["1", "2", "3", "a", "b", "c"]
```
The [`join()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method joins all elements of an array into a string.
```js
const myArray = ["Wind", "Rain", "Fire"];
const list = myArray.join(" - "); // list is "Wind - Rain - Fire"
```
The [`push()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) method adds one or more elements to the end of an array and returns the resulting `length` of the array.
```js
const myArray = ["1", "2"];
myArray.push("3"); // myArray is now ["1", "2", "3"]
```
The [`pop()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) method removes the last element from an array and returns that element.
```js
const myArray = ["1", "2", "3"];
const last = myArray.pop();
// myArray is now ["1", "2"], last = "3"
```
The [`shift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) method removes the first element from an array and returns that element.
```js
const myArray = ["1", "2", "3"];
const first = myArray.shift();
// myArray is now ["2", "3"], first is "1"
```
The [`unshift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) method adds one or more elements to the front of an array and returns the new length of the array.
```js
const myArray = ["1", "2", "3"];
myArray.unshift("4", "5");
// myArray becomes ["4", "5", "1", "2", "3"]
```
The [`slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method extracts a section of an array and returns a new array.
```js
let myArray = ["a", "b", "c", "d", "e"];
myArray = myArray.slice(1, 4); // [ "b", "c", "d"]
// starts at index 1 and extracts all elements
// until index 3
```
The [`at()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) method returns the element at the specified index in the array, or `undefined` if the index is out of range. It's notably used for negative indices that access elements from the end of the array.
```js
const myArray = ["a", "b", "c", "d", "e"];
myArray.at(-2); // "d", the second-last element of myArray
```
The [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
```js
const myArray = ["1", "2", "3", "4", "5"];
myArray.splice(1, 3, "a", "b", "c", "d");
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.
```
The [`reverse()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) method transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.
```js
const myArray = ["1", "2", "3"];
myArray.reverse();
// transposes the array so that myArray = ["3", "2", "1"]
```
The [`flat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
```js
let myArray = [1, 2, [3, 4]];
myArray = myArray.flat();
// myArray is now [1, 2, 3, 4], since the [3, 4] subarray is flattened
```
The [`sort()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) method sorts the elements of an array in place, and returns a reference to the array.
```js
const myArray = ["Wind", "Rain", "Fire"];
myArray.sort();
// sorts the array so that myArray = ["Fire", "Rain", "Wind"]
```
`sort()` can also take a callback function to determine how array elements are compared. The callback function is called with two arguments, which are two values from the array. The function compares these two values and returns a positive number, negative number, or zero, indicating the order of the two values. For instance, the following will sort the array by the last letter of a string:
```js
const sortFn = (a, b) => {
if (a[a.length - 1] < b[b.length - 1]) {
return -1; // Negative number => a < b, a comes before b
} else if (a[a.length - 1] > b[b.length - 1]) {
return 1; // Positive number => a > b, a comes after b
}
return 0; // Zero => a = b, a and b keep their original order
};
myArray.sort(sortFn);
// sorts the array so that myArray = ["Wind","Fire","Rain"]
```
- if `a` is less than `b` by the sorting system, return `-1` (or any negative number)
- if `a` is greater than `b` by the sorting system, return `1` (or any positive number)
- if `a` and `b` are considered equivalent, return `0`.
The [`indexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) method searches the array for `searchElement` and returns the index of the first match.
```js
const a = ["a", "b", "a", "b", "a"];
console.log(a.indexOf("b")); // 1
// Now try again, starting from after the last match
console.log(a.indexOf("b", 2)); // 3
console.log(a.indexOf("z")); // -1, because 'z' was not found
```
The [`lastIndexOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) method works like `indexOf`, but starts at the end and searches backwards.
```js
const a = ["a", "b", "c", "d", "a", "b"];
console.log(a.lastIndexOf("b")); // 5
// Now try again, starting from before the last match
console.log(a.lastIndexOf("b", 4)); // 1
console.log(a.lastIndexOf("z")); // -1
```
The [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method executes `callback` on every array item and returns `undefined`.
```js
const a = ["a", "b", "c"];
a.forEach((element) => {
console.log(element);
});
// Logs:
// a
// b
// c
```
The `forEach` method (and others below) that take a callback are known as _iterative methods_, because they iterate over the entire array in some fashion. Each one takes an optional second argument called `thisArg`. If provided, `thisArg` becomes the value of the `this` keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, `this` will refer to the global object ([`window`](/en-US/docs/Web/API/Window), [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), etc.) when the function is [not strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode), or `undefined` when the function is strict.
> **Note:** The `sort()` method introduced above is not an iterative method, because its callback function is only used for comparison and may not be called in any particular order based on element order. `sort()` does not accept the `thisArg` parameter either.
The [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method returns a new array of the return value from executing `callback` on every array item.
```js
const a1 = ["a", "b", "c"];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']
```
The [`flatMap()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) method runs `map()` followed by a `flat()` of depth 1.
```js
const a1 = ["a", "b", "c"];
const a2 = a1.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]);
console.log(a2); // ['A', 'a', 'B', 'b', 'C', 'c']
```
The [`filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method returns a new array containing the items for which `callback` returned `true`.
```js
const a1 = ["a", 10, "b", 20, "c", 30];
const a2 = a1.filter((item) => typeof item === "number");
console.log(a2); // [10, 20, 30]
```
The [`find()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method returns the first item for which `callback` returned `true`.
```js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.find((item) => typeof item === "number");
console.log(i); // 10
```
The [`findLast()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast) method returns the last item for which `callback` returned `true`.
```js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLast((item) => typeof item === "number");
console.log(i); // 30
```
The [`findIndex()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) method returns the index of the first item for which `callback` returned `true`.
```js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findIndex((item) => typeof item === "number");
console.log(i); // 1
```
The [`findLastIndex()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex) method returns the index of the last item for which `callback` returned `true`.
```js
const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLastIndex((item) => typeof item === "number");
console.log(i); // 5
```
The [`every()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) method returns `true` if `callback` returns `true` for every item in the array.
```js
function isNumber(value) {
return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.every(isNumber)); // false
```
The [`some()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) method returns `true` if `callback` returns `true` for at least one item in the array.
```js
function isNumber(value) {
return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.some(isNumber)); // true
const a3 = ["1", "2", "3"];
console.log(a3.some(isNumber)); // false
```
The [`reduce()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method applies `callback(accumulator, currentValue, currentIndex, array)` for each value in the array for the purpose of reducing the list of items down to a single value. The `reduce` function returns the final value returned by `callback` function.
If `initialValue` is specified, then `callback` is called with `initialValue` as the first parameter value and the value of the first item in the array as the second parameter value.
If `initialValue` is _not_ specified, then `callback`'s first two parameter values will be the first and second elements of the array. On _every_ subsequent call, the first parameter's value will be whatever `callback` returned on the previous call, and the second parameter's value will be the next value in the array.
If `callback` needs access to the index of the item being processed, or access to the entire array, they are available as optional parameters.
```js
const a = [10, 20, 30];
const total = a.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0,
);
console.log(total); // 60
```
The [`reduceRight()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) method works like `reduce()`, but starts with the last element.
`reduce` and `reduceRight` are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.
## Array transformations
You can transform back and forth between arrays and other data structures.
### Grouping the elements of an array
The {{jsxref("Object.groupBy()")}} method can be used to group the elements of an array, using a test function that returns a string indicating the group of the current element.
Here we have a simple inventory array that contains "food" objects that have a `name` and a `type`.
```js
const inventory = [
{ name: "asparagus", type: "vegetables" },
{ name: "bananas", type: "fruit" },
{ name: "goat", type: "meat" },
{ name: "cherries", type: "fruit" },
{ name: "fish", type: "meat" },
];
```
To use `Object.groupBy()`, you supply a callback function that is called with the current element, and optionally the current index and array, and returns a string indicating the group of the element.
The code below uses an arrow function to return the `type` of each array element (this uses [object destructuring syntax for function arguments](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#unpacking_properties_from_objects_passed_as_a_function_parameter) to unpack the `type` element from the passed object). The result is an object that has properties named after the unique strings returned by the callback. Each property is assigned an array containing the elements in the group.
```js
const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result.vegetables);
// [{ name: "asparagus", type: "vegetables" }]
```
Note that the returned object references the _same_ elements as the original array (not {{Glossary("deep copy", "deep copies")}}). Changing the internal structure of these elements will be reflected in both the original array and the returned object.
If you can't use a string as the key, for example, if the information to group is associated with an object that might change, then you can instead use {{jsxref("Map.groupBy()")}}. This is very similar to `Object.groupBy()` except that it groups the elements of the array into a {{jsxref("Map")}} that can use an arbitrary value ({{Glossary("object")}} or {{Glossary("primitive")}}) as a key.
## Sparse arrays
Arrays can contain "empty slots", which are not the same as slots filled with the value `undefined`. Empty slots can be created in one of the following ways:
```js
// Array constructor:
const a = Array(5); // [ <5 empty items> ]
// Consecutive commas in array literal:
const b = [1, 2, , , 5]; // [ 1, 2, <2 empty items>, 5 ]
// Directly setting a slot with index greater than array.length:
const c = [1, 2];
c[4] = 5; // [ 1, 2, <2 empty items>, 5 ]
// Elongating an array by directly setting .length:
const d = [1, 2];
d.length = 5; // [ 1, 2, <3 empty items> ]
// Deleting an element:
const e = [1, 2, 3, 4, 5];
delete e[2]; // [ 1, 2, <1 empty item>, 4, 5 ]
```
In some operations, empty slots behave as if they are filled with `undefined`.
```js
const arr = [1, 2, , , 5]; // Create a sparse array
// Indexed access
console.log(arr[2]); // undefined
// For...of
for (const i of arr) {
console.log(i);
}
// Logs: 1 2 undefined undefined 5
// Spreading
const another = [...arr]; // "another" is [ 1, 2, undefined, undefined, 5 ]
```
But in others (most notably array iteration methods), empty slots are skipped.
```js
const mapped = arr.map((i) => i + 1); // [ 2, 3, <2 empty items>, 6 ]
arr.forEach((i) => console.log(i)); // 1 2 5
const filtered = arr.filter(() => true); // [ 1, 2, 5 ]
const hasFalsy = arr.some((k) => !k); // false
// Property enumeration
const keys = Object.keys(arr); // [ '0', '1', '4' ]
for (const key in arr) {
console.log(key);
}
// Logs: '0' '1' '4'
// Spreading into an object uses property enumeration, not the array's iterator
const objectSpread = { ...arr }; // { '0': 1, '1': 2, '4': 5 }
```
For a complete list of how array methods behave with sparse arrays, see [the `Array` reference page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_methods_and_empty_slots).
## Multi-dimensional arrays
Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.
The following code creates a two-dimensional array.
```js
const a = new Array(4);
for (let i = 0; i < 4; i++) {
a[i] = new Array(4);
for (let j = 0; j < 4; j++) {
a[i][j] = `[${i}, ${j}]`;
}
}
```
This example creates an array with the following rows:
```plain
Row 0: [0, 0] [0, 1] [0, 2] [0, 3]
Row 1: [1, 0] [1, 1] [1, 2] [1, 3]
Row 2: [2, 0] [2, 1] [2, 2] [2, 3]
Row 3: [3, 0] [3, 1] [3, 2] [3, 3]
```
## Using arrays to store other properties
Arrays can also be used like objects, to store related information.
```js
const arr = [1, 2, 3];
arr.property = "value";
console.log(arr.property); // "value"
```
For example, when an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of [`RegExp.prototype.exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec), [`String.prototype.match()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match), and [`String.prototype.split()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split). For information on using arrays with regular expressions, see [Regular Expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions).
## Working with array-like objects
Some JavaScript objects, such as the [`NodeList`](/en-US/docs/Web/API/NodeList) returned by [`document.getElementsByTagName()`](/en-US/docs/Web/API/Document/getElementsByTagName) or the {{jsxref("Functions/arguments", "arguments")}} object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The `arguments` object provides a {{jsxref("Function/length", "length")}} attribute but does not implement array methods like [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).
Array methods cannot be called directly on array-like objects.
```js example-bad
function printArguments() {
arguments.forEach((item) => {
console.log(item);
}); // TypeError: arguments.forEach is not a function
}
```
But you can call them indirectly using {{jsxref("Function.prototype.call()")}}.
```js example-good
function printArguments() {
Array.prototype.forEach.call(arguments, (item) => {
console.log(item);
});
}
```
Array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:
```js
Array.prototype.forEach.call("a string", (chr) => {
console.log(chr);
});
```
{{PreviousNext("Web/JavaScript/Guide/Regular_expressions", "Web/JavaScript/Guide/Keyed_collections")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/using_classes/index.md | ---
title: Using classes
slug: Web/JavaScript/Guide/Using_classes
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_objects", "Web/JavaScript/Guide/Using_promises")}}
JavaScript is a prototype-based language β an object's behaviors are specified by its own properties and its prototype's properties. However, with the addition of [classes](/en-US/docs/Web/JavaScript/Reference/Classes), the creation of hierarchies of objects and the inheritance of properties and their values are much more in line with other object-oriented languages such as Java. In this section, we will demonstrate how objects can be created from classes.
In many other languages, _classes_, or constructors, are clearly distinguished from _objects_, or instances. In JavaScript, classes are mainly an abstraction over the existing prototypical inheritance mechanism β all patterns are convertible to prototype-based inheritance. Classes themselves are normal JavaScript values as well, and have their own prototype chains. In fact, most plain JavaScript functions can be used as constructors β you use the `new` operator with a constructor function to create a new object.
We will be playing with the well-abstracted class model in this tutorial, and discuss what semantics classes offer. If you want to dive deep into the underlying prototype system, you can read the [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) guide.
This chapter assumes that you are already somewhat familiar with JavaScript and that you have used ordinary objects.
## Overview of classes
If you have some hands-on experience with JavaScript, or have followed along with the guide, you probably have already used classes, even if you haven't created one. For example, this [may seem familiar to you](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates):
```js
const bigDay = new Date(2019, 6, 19);
console.log(bigDay.toLocaleDateString());
if (bigDay.getTime() < Date.now()) {
console.log("Once upon a time...");
}
```
On the first line, we created an instance of the class [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), and called it `bigDay`. On the second line, we called a [method](/en-US/docs/Glossary/Method) [`toLocaleDateString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) on the `bigDay` instance, which returns a string. Then, we compared two numbers: one returned from the [`getTime()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method, the other directly called from the `Date` class _itself_, as [`Date.now()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now).
`Date` is a built-in class of JavaScript. From this example, we can get some basic ideas of what classes do:
- Classes create objects through the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator.
- Each object has some properties (data or method) added by the class.
- The class stores some properties (data or method) itself, which are usually used to interact with instances.
These correspond to the three key features of classes:
- Constructor;
- Instance methods and instance fields;
- Static methods and static fields.
## Declaring a class
Classes are usually created with _class declarations_.
```js
class MyClass {
// class body...
}
```
Within a class body, there are a range of features available.
```js
class MyClass {
// Constructor
constructor() {
// Constructor body
}
// Instance field
myField = "foo";
// Instance method
myMethod() {
// myMethod body
}
// Static field
static myStaticField = "bar";
// Static method
static myStaticMethod() {
// myStaticMethod body
}
// Static block
static {
// Static initialization code
}
// Fields, methods, static fields, and static methods all have
// "private" forms
#myPrivateField = "bar";
}
```
If you came from a pre-ES6 world, you may be more familiar with using functions as constructors. The pattern above would roughly translate to the following with function constructors:
```js
function MyClass() {
this.myField = "foo";
// Constructor body
}
MyClass.myStaticField = "bar";
MyClass.myStaticMethod = function () {
// myStaticMethod body
};
MyClass.prototype.myMethod = function () {
// myMethod body
};
(function () {
// Static initialization code
})();
```
> **Note:** Private fields and methods are new features in classes with no trivial equivalent in function constructors.
### Constructing a class
After a class has been declared, you can create instances of it using the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator.
```js
const myInstance = new MyClass();
console.log(myInstance.myField); // 'foo'
myInstance.myMethod();
```
Typical function constructors can both be constructed with `new` and called without `new`. However, attempting to "call" a class without `new` will result in an error.
```js
const myInstance = MyClass(); // TypeError: Class constructor MyClass cannot be invoked without 'new'
```
### Class declaration hoisting
Unlike function declarations, class declarations are not [hoisted](/en-US/docs/Glossary/Hoisting) (or, in some interpretations, hoisted but with the temporal dead zone restriction), which means you cannot use a class before it is declared.
```js
new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization
class MyClass {}
```
This behavior is similar to variables declared with [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const).
### Class expressions
Similar to functions, class declarations also have their expression counterparts.
```js
const MyClass = class {
// Class body...
};
```
Class expressions can have names as well. The expression's name is only visible to the class's body.
```js
const MyClass = class MyClassLongerName {
// Class body. Here MyClass and MyClassLongerName point to the same class.
};
new MyClassLongerName(); // ReferenceError: MyClassLongerName is not defined
```
## Constructor
Perhaps the most important job of a class is to act as a "factory" for objects. For example, when we use the `Date` constructor, we expect it to give a new object which represents the date data we passed in β which we can then manipulate with other methods the instance exposes. In classes, the instance creation is done by the [constructor](/en-US/docs/Web/JavaScript/Reference/Classes/constructor).
As an example, we would create a class called `Color`, which represents a specific color. Users create colors through passing in an [RGB](/en-US/docs/Glossary/RGB) triplet.
```js
class Color {
constructor(r, g, b) {
// Assign the RGB values as a property of `this`.
this.values = [r, g, b];
}
}
```
Open your browser's devtools, paste the above code into the console, and then create an instance:
```js
const red = new Color(255, 0, 0);
console.log(red);
```
You should see some output like this:
```plain
Object { values: (3) [β¦] }
values: Array(3) [ 255, 0, 0 ]
```
You have successfully created a `Color` instance, and the instance has a `values` property, which is an array of the RGB values you passed in. That is pretty much equivalent to the following:
```js
function createColor(r, g, b) {
return {
values: [r, g, b],
};
}
```
The constructor's syntax is exactly the same as a normal function β which means you can use other syntaxes, like [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters):
```js
class Color {
constructor(...values) {
this.values = values;
}
}
const red = new Color(255, 0, 0);
// Creates an instance with the same shape as above.
```
Each time you call `new`, a different instance is created.
```js
const red = new Color(255, 0, 0);
const anotherRed = new Color(255, 0, 0);
console.log(red === anotherRed); // false
```
Within a class constructor, the value of `this` points to the newly created instance. You can assign properties to it, or read existing properties (especially methods β which we will cover next).
The `this` value will be automatically returned as the result of `new`. You are advised to not return any value from the constructor β because if you return a non-primitive value, it will become the value of the `new` expression, and the value of `this` is dropped. (You can read more about what `new` does in [its description](/en-US/docs/Web/JavaScript/Reference/Operators/new#description).)
```js
class MyClass {
constructor() {
this.myField = "foo";
return {};
}
}
console.log(new MyClass().myField); // undefined
```
## Instance methods
If a class only has a constructor, it is not much different from a `createX` factory function which just creates plain objects. However, the power of classes is that they can be used as "templates" which automatically assign methods to instances.
For example, for `Date` instances, you can use a range of methods to get different information from a single date value, such as the [year](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear), [month](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth), [day of the week](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay), etc. You can also set those values through the `setX` counterparts like [`setFullYear`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear).
For our own `Color` class, we can add a method called `getRed` which returns the red value of the color.
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
}
getRed() {
return this.values[0];
}
}
const red = new Color(255, 0, 0);
console.log(red.getRed()); // 255
```
Without methods, you may be tempted to define the function within the constructor:
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
this.getRed = function () {
return this.values[0];
};
}
}
```
This also works. However, a problem is that this creates a new function every time a `Color` instance is created, even when they all do the same thing!
```js
console.log(new Color().getRed === new Color().getRed); // false
```
In contrast, if you use a method, it will be shared between all instances. A function can be shared between all instances, but still have its behavior differ when different instances call it, because the value of `this` is different. If you are curious _where_ this method is stored in β it's defined on the prototype of all instances, or `Color.prototype`, which is explained in more detail in [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
Similarly, we can create a new method called `setRed`, which sets the red value of the color.
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
}
getRed() {
return this.values[0];
}
setRed(value) {
this.values[0] = value;
}
}
const red = new Color(255, 0, 0);
red.setRed(0);
console.log(red.getRed()); // 0; of course, it should be called "black" at this stage!
```
## Private fields
You might be wondering: why do we want to go to the trouble of using `getRed` and `setRed` methods, when we can directly access the `values` array on the instance?
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
}
}
const red = new Color(255, 0, 0);
red.values[0] = 0;
console.log(red.values[0]); // 0
```
There is a philosophy in object-oriented programming called "encapsulation". This means you should not access the underlying implementation of an object, but instead use well-abstracted methods to interact with it. For example, if we suddenly decided to represent colors as [HSL](/en-US/docs/Web/CSS/color_value/hsl) instead:
```js
class Color {
constructor(r, g, b) {
// values is now an HSL array!
this.values = rgbToHSL([r, g, b]);
}
getRed() {
return this.values[0];
}
setRed(value) {
this.values[0] = value;
}
}
const red = new Color(255, 0, 0);
console.log(red.values[0]); // 0; It's not 255 anymore, because the H value for pure red is 0
```
The user assumption that `values` means the RGB value suddenly collapses, and it may cause their logic to break. So, if you are an implementor of a class, you would want to hide the internal data structure of your instance from your user, both to keep the API clean and to prevent the user's code from breaking when you do some "harmless refactors". In classes, this is done through [_private fields_](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
A private field is an identifier prefixed with `#` (the hash symbol). The hash is an integral part of the field's name, which means a private property can never have name clash with a public property. In order to refer to a private field anywhere in the class, you must _declare_ it in the class body (you can't create a private property on the fly). Apart from this, a private field is pretty much equivalent to a normal property.
```js
class Color {
// Declare: every Color instance has a private field called #values.
#values;
constructor(r, g, b) {
this.#values = [r, g, b];
}
getRed() {
return this.#values[0];
}
setRed(value) {
this.#values[0] = value;
}
}
const red = new Color(255, 0, 0);
console.log(red.getRed()); // 255
```
Accessing private fields outside the class is an early syntax error. The language can guard against this because `#privateField` is a special syntax, so it can do some static analysis and find all usage of private fields before even evaluating the code.
```js-nolint example-bad
console.log(red.#values); // SyntaxError: Private field '#values' must be declared in an enclosing class
```
> **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.
Private fields in JavaScript are _hard private_: if the class does not implement methods that expose these private fields, there's absolutely no mechanism to retrieve them from outside the class. This means you are safe to do any refactors to your class's private fields, as long as the behavior of exposed methods stay the same.
After we've made the `values` field private, we can add some more logic in the `getRed` and `setRed` methods, instead of making them simple pass-through methods. For example, we can add a check in `setRed` to see if it's a valid R value:
```js
class Color {
#values;
constructor(r, g, b) {
this.#values = [r, g, b];
}
getRed() {
return this.#values[0];
}
setRed(value) {
if (value < 0 || value > 255) {
throw new RangeError("Invalid R value");
}
this.#values[0] = value;
}
}
const red = new Color(255, 0, 0);
red.setRed(1000); // RangeError: Invalid R value
```
If we leave the `values` property exposed, our users can easily circumvent that check by assigning to `values[0]` directly, and create invalid colors. But with a well-encapsulated API, we can make our code more robust and prevent logic errors downstream.
A class method can read the private fields of other instances, as long as they belong to the same class.
```js
class Color {
#values;
constructor(r, g, b) {
this.#values = [r, g, b];
}
redDifference(anotherColor) {
// #values doesn't necessarily need to be accessed from this:
// you can access private fields of other instances belonging
// to the same class.
return this.#values[0] - anotherColor.#values[0];
}
}
const red = new Color(255, 0, 0);
const crimson = new Color(220, 20, 60);
red.redDifference(crimson); // 35
```
However, if `anotherColor` is not a Color instance, `#values` won't exist. (Even if another class has an identically named `#values` private field, it's not referring to the same thing and cannot be accessed here.) Accessing a nonexistent private property throws an error instead of returning `undefined` like normal properties do. If you don't know if a private field exists on an object and you wish to access it without using `try`/`catch` to handle the error, you can use the [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) operator.
```js
class Color {
#values;
constructor(r, g, b) {
this.#values = [r, g, b];
}
redDifference(anotherColor) {
if (!(#values in anotherColor)) {
throw new TypeError("Color instance expected");
}
return this.#values[0] - anotherColor.#values[0];
}
}
```
> **Note:** Keep in mind that the `#` is a special identifier syntax, and you can't use the field name as if it's a string. `"#values" in anotherColor` would look for a property name literally called `"#values"`, instead of a private field.
There are some limitations in using private properties: the same name can't be declared twice in a single class, and they can't be deleted. Both lead to early syntax errors.
```js-nolint example-bad
class BadIdeas {
#firstName;
#firstName; // syntax error occurs here
#lastName;
constructor() {
delete this.#lastName; // also a syntax error
}
}
```
Methods, [getters, and setters](#accessor_fields) can be private as well. They're useful when you have something complex that the class needs to do internally but no other part of the code should be allowed to call.
For example, imagine creating [HTML custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) that should do something somewhat complicated when clicked/tapped/otherwise activated. Furthermore, the somewhat complicated things that happen when the element is clicked should be restricted to this class, because no other part of the JavaScript will (or should) ever access it.
```js
class Counter extends HTMLElement {
#xValue = 0;
constructor() {
super();
this.onclick = this.#clicked.bind(this);
}
get #x() {
return this.#xValue;
}
set #x(value) {
this.#xValue = value;
window.requestAnimationFrame(this.#render.bind(this));
}
#clicked() {
this.#x++;
}
#render() {
this.textContent = this.#x.toString();
}
connectedCallback() {
this.#render();
}
}
customElements.define("num-counter", Counter);
```
In this case, pretty much every field and method is private to the class. Thus, it presents an interface to the rest of the code that's essentially just like a built-in HTML element. No other part of the program has the power to affect any of the internals of `Counter`.
## Accessor fields
`color.getRed()` and `color.setRed()` allow us to read and write to the red value of a color. If you come from languages like Java, you will be very familiar with this pattern. However, using methods to simply access a property is still somewhat unergonomic in JavaScript. _Accessor fields_ allow us to manipulate something as if its an "actual property".
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
}
get red() {
return this.values[0];
}
set red(value) {
this.values[0] = value;
}
}
const red = new Color(255, 0, 0);
red.red = 0;
console.log(red.red); // 0
```
It looks as if the object has a property called `red` β but actually, no such property exists on the instance! There are only two methods, but they are prefixed with `get` and `set`, which allows them to be manipulated as if they were properties.
If a field only has a getter but no setter, it will be effectively read-only.
```js
class Color {
constructor(r, g, b) {
this.values = [r, g, b];
}
get red() {
return this.values[0];
}
}
const red = new Color(255, 0, 0);
red.red = 0;
console.log(red.red); // 255
```
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), the `red.red = 0` line will throw a type error: "Cannot set property red of #\<Color> which has only a getter". In non-strict mode, the assignment is silently ignored.
## Public fields
Private fields also have their public counterparts, which allow every instance to have a property. Fields are usually designed to be independent of the constructor's parameters.
```js
class MyClass {
luckyNumber = Math.random();
}
console.log(new MyClass().luckyNumber); // 0.5
console.log(new MyClass().luckyNumber); // 0.3
```
Public fields are almost equivalent to assigning a property to `this`. For example, the above example can also be converted to:
```js
class MyClass {
constructor() {
this.luckyNumber = Math.random();
}
}
```
## Static properties
With the `Date` example, we have also encountered the [`Date.now()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) method, which returns the current date. This method does not belong to any date instance β it belongs to the class itself. However, it's put on the `Date` class instead of being exposed as a global `DateNow()` function, because it's mostly useful when dealing with date instances.
> **Note:** Prefixing utility methods with what they deal with is called "namespacing" and is considered a good practice. For example, in addition to the older, unprefixed [`parseInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) method, JavaScript also later added the prefixed [`Number.parseInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt) method to indicate that it's for dealing with numbers.
[_Static properties_](/en-US/docs/Web/JavaScript/Reference/Classes/static) are a group of class features that are defined on the class itself, rather than on individual instances of the class. These features include:
- Static methods
- Static fields
- Static getters and setters
Everything also has private counterparts. For example, for our `Color` class, we can create a static method that checks whether a given triplet is a valid RGB value:
```js
class Color {
static isValid(r, g, b) {
return r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255;
}
}
Color.isValid(255, 0, 0); // true
Color.isValid(1000, 0, 0); // false
```
Static properties are very similar to their instance counterparts, except that:
- They are all prefixed with `static`, and
- They are not accessible from instances.
```js
console.log(new Color(0, 0, 0).isValid); // undefined
```
There is also a special construct called a [_static initialization block_](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks), which is a block of code that runs when the class is first loaded.
```js
class MyClass {
static {
MyClass.myStaticProperty = "foo";
}
}
console.log(MyClass.myStaticProperty); // 'foo'
```
Static initialization blocks are almost equivalent to immediately executing some code after a class has been declared. The only difference is that they have access to static private properties.
## Extends and inheritance
A key feature that classes bring about (in addition to ergonomic encapsulation with private fields) is _inheritance_, which means one object can "borrow" a large part of another object's behaviors, while overriding or enhancing certain parts with its own logic.
For example, suppose our `Color` class now needs to support transparency. We may be tempted to add a new field that indicates its transparency:
```js
class Color {
#values;
constructor(r, g, b, a = 1) {
this.#values = [r, g, b, a];
}
get alpha() {
return this.#values[3];
}
set alpha(value) {
if (value < 0 || value > 1) {
throw new RangeError("Alpha value must be between 0 and 1");
}
this.#values[3] = value;
}
}
```
However, this means every instance β even the vast majority which aren't transparent (those with an alpha value of 1) β will have to have the extra alpha value, which is not very elegant. Plus, if the features keep growing, our `Color` class will become very bloated and hard to maintain.
Instead, in object-oriented programming, we would create a _derived class_. The derived class has access to all public properties of the parent class. In JavaScript, derived classes are declared with an [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) clause, which indicates the class it extends from.
```js
class ColorWithAlpha extends Color {
#alpha;
constructor(r, g, b, a) {
super(r, g, b);
this.#alpha = a;
}
get alpha() {
return this.#alpha;
}
set alpha(value) {
if (value < 0 || value > 1) {
throw new RangeError("Alpha value must be between 0 and 1");
}
this.#alpha = value;
}
}
```
There are a few things that have immediately come to attention. First is that in the constructor, we are calling `super(r, g, b)`. It is a language requirement to call [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super) before accessing `this`. The `super()` call calls the parent class's constructor to initialize `this` β here it's roughly equivalent to `this = new Color(r, g, b)`. You can have code before `super()`, but you cannot access `this` before `super()` β the language prevents you from accessing the uninitialized `this`.
After the parent class is done with modifying `this`, the derived class can do its own logic. Here we added a private field called `#alpha`, and also provided a pair of getter/setters to interact with them.
A derived class inherits all methods from its parent. For example, although `ColorWithAlpha` doesn't declare a `get red()` accessor itself, you can still access `red` because this behavior is specified by the parent class:
```js
const color = new ColorWithAlpha(255, 0, 0, 0.5);
console.log(color.red); // 255
```
Derived classes can also override methods from the parent class. For example, all classes implicitly inherit the [`Object`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) class, which defines some basic methods like [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString). However, the base `toString()` method is notoriously useless, because it prints `[object Object]` in most cases:
```js
console.log(red.toString()); // [object Object]
```
Instead, our class can override it to print the color's RGB values:
```js
class Color {
#values;
// β¦
toString() {
return this.#values.join(", ");
}
}
console.log(new Color(255, 0, 0).toString()); // '255, 0, 0'
```
Within derived classes, you can access the parent class's methods by using `super`. This allows you to build enhancement methods and avoid code duplication.
```js
class ColorWithAlpha extends Color {
#alpha;
// β¦
toString() {
// Call the parent class's toString() and build on the return value
return `${super.toString()}, ${this.#alpha}`;
}
}
console.log(new ColorWithAlpha(255, 0, 0, 0.5).toString()); // '255, 0, 0, 0.5'
```
When you use `extends`, the static methods inherit from each other as well, so you can also override or enhance them.
```js
class ColorWithAlpha extends Color {
// ...
static isValid(r, g, b, a) {
// Call the parent class's isValid() and build on the return value
return super.isValid(r, g, b) && a >= 0 && a <= 1;
}
}
console.log(ColorWithAlpha.isValid(255, 0, 0, -1)); // false
```
Derived classes don't have access to the parent class's private fields β this is another key aspect to JavaScript private fields being "hard private". Private fields are scoped to the class body itself and do not grant access to _any_ outside code.
```js-nolint example-bad
class ColorWithAlpha extends Color {
log() {
console.log(this.#values); // SyntaxError: Private field '#values' must be declared in an enclosing class
}
}
```
A class can only extend from one class. This prevents problems in multiple inheritance like the [diamond problem](https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem). However, due to the dynamic nature of JavaScript, it's still possible to achieve the effect of multiple inheritance through class composition and [mixins](/en-US/docs/Web/JavaScript/Reference/Classes/extends#mix-ins).
Instances of derived classes are also [instances of](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) the base class.
```js
const color = new ColorWithAlpha(255, 0, 0, 0.5);
console.log(color instanceof Color); // true
console.log(color instanceof ColorWithAlpha); // true
```
## Why classes?
The guide has been pragmatic so far: we are focusing on _how_ classes can be used, but there's one question unanswered: _why_ would one use a class? The answer is: it depends.
Classes introduce a _paradigm_, or a way to organize your code. Classes are the foundations of object-oriented programming, which is built on concepts like [inheritance](<https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)>) and [polymorphism](<https://en.wikipedia.org/wiki/Polymorphism_(computer_science)>) (especially _subtype polymorphism_). However, many people are philosophically against certain OOP practices and don't use classes as a result.
For example, one thing that makes `Date` objects infamous is that they're _mutable_.
```js
function incrementDay(date) {
return date.setDate(date.getDate() + 1);
}
const date = new Date(); // 2019-06-19
const newDay = incrementDay(date);
console.log(newDay); // 2019-06-20
// The old date is modified as well!?
console.log(date); // 2019-06-20
```
Mutability and internal state are important aspects of object-oriented programming, but often make code hard to reason with β because any seemingly innocent operation may have unexpected side effects and change the behavior in other parts of the program.
In order to reuse code, we usually resort to extending classes, which can create big hierarchies of inheritance patterns.

However, it is often hard to describe inheritance cleanly when one class can only extend one other class. Often, we want the behavior of multiple classes. In Java, this is done through interfaces; in JavaScript, it can be done through mixins. But at the end of the day, it's still not very convenient.
On the brighter side, classes are a very powerful way to organize our code on a higher level. For example, without the `Color` class, we may need to create a dozen of utility functions:
```js
function isRed(color) {
return color.red === 255;
}
function isValidColor(color) {
return (
color.red >= 0 &&
color.red <= 255 &&
color.green >= 0 &&
color.green <= 255 &&
color.blue >= 0 &&
color.blue <= 255
);
}
// ...
```
But with classes, we can congregate them all under the `Color` namespace, which improves readability. In addition, the introduction of private fields allows us to hide certain data from downstream users, creating a clean API.
In general, you should consider using classes when you want to create objects that store their own internal data and expose a lot of behavior. Take built-in JavaScript classes as examples:
- The [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and [`Set`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) classes store a collection of elements and allow you to access them by key using `get()`, `set()`, `has()`, etc.
- The [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) class stores a date as a Unix timestamp (a number) and allows you to format, update, and read individual date components.
- The [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) class stores information about a particular exception, including the error message, stack trace, cause, etc. It's one of the few classes that come with a rich inheritance structure: there are multiple built-in classes like [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) and [`ReferenceError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) that extend `Error`. In the case of errors, this inheritance allows refining the semantics of errors: each error class represents a specific type of error, which can be easily checked with [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof).
JavaScript offers the mechanism to organize your code in a canonical object-oriented way, but whether and how to use it is entirely up to the programmer's discretion.
{{PreviousNext("Web/JavaScript/Guide/Working_with_objects", "Web/JavaScript/Guide/Using_promises")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/index.md | ---
title: Regular expressions
slug: Web/JavaScript/Guide/Regular_expressions
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}
Regular expressions are patterns used to match character combinations in strings.
In JavaScript, regular expressions are also objects. These patterns are used with the {{jsxref("RegExp/exec", "exec()")}} and {{jsxref("RegExp/test", "test()")}} methods of {{jsxref("RegExp")}}, and with the {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, {{jsxref("String/search", "search()")}}, and {{jsxref("String/split", "split()")}} methods of {{jsxref("String")}}.
This chapter describes JavaScript regular expressions.
## Creating a regular expression
You construct a regular expression in one of two ways:
- Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:
```js
const re = /ab+c/;
```
Regular expression literals provide compilation of the regular expression when the script is loaded.
If the regular expression remains constant, using this can improve performance.
- Or calling the constructor function of the {{jsxref("RegExp")}} object, as follows:
```js
const re = new RegExp("ab+c");
```
Using the constructor function provides runtime compilation of the regular expression.
Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
## Writing a regular expression pattern
A regular expression pattern is composed of simple characters, such as `/abc/`, or a combination of simple and special characters, such as `/ab*c/` or `/Chapter (\d+)\.\d*/`.
The last example includes parentheses, which are used as a memory device.
The match made with this part of the pattern is remembered for later use, as described in [Using groups](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences#using_groups).
> **Note:** If you are already familiar with the forms of a regular expression, you may also read [the cheat sheet](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet) for a quick lookup for a specific pattern/construct.
### Using simple patterns
Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern `/abc/` matches character combinations in strings only when the exact sequence `"abc"` occurs (all characters together and in that order).
Such a match would succeed in the strings `"Hi, do you know your abc's?"` and `"The latest airplane designs evolved from slabcraft."`.
In both cases the match is with the substring `"abc"`.
There is no match in the string `"Grab crab"` because while it contains the substring `"ab c"`, it does not contain the exact substring `"abc"`.
### Using special characters
When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern.
For example, to match _a single `"a"` followed by zero or more `"b"`s followed by `"c"`_, you'd use the pattern `/ab*c/`: the `*` after `"b"` means "0 or more occurrences of the preceding item."
In the string `"cbbabbbbcdebc"`, this pattern will match the substring `"abbbbc"`.
The following pages provide lists of the different special characters that fit into each category, along with descriptions and examples.
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- : Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- : Distinguish different types of characters. For example, distinguishing between letters and digits.
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- : Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.
- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide
- : Indicate numbers of characters or expressions to match.
If you want to look at all the special characters that can be used in regular expressions in a single table, see the following:
<table class="standard-table">
<caption>
Special characters in regular expressions.
</caption>
<thead>
<tr>
<th scope="col">Characters / constructs</th>
<th scope="col">Corresponding article</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>[xyz]</code>, <code>[^xyz]</code>, <code>.</code>,
<code>\d</code>, <code>\D</code>, <code>\w</code>, <code>\W</code>,
<code>\s</code>, <code>\S</code>, <code>\t</code>, <code>\r</code>,
<code>\n</code>, <code>\v</code>, <code>\f</code>, <code>[\b]</code>,
<code>\0</code>, <code>\c<em>X</em></code>, <code>\x<em>hh</em></code>,
<code>\u<em>hhhh</em></code>, <code>\u<em>{hhhh}</em></code>,
<code><em>x</em>|<em>y</em></code>
</td>
<td>
<p>
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"
>Character classes</a
>
</p>
</td>
</tr>
<tr>
<td>
<code>^</code>, <code>$</code>, <code>\b</code>, <code>\B</code>,
<code>x(?=y)</code>, <code>x(?!y)</code>, <code>(?<=y)x</code>,
<code>(?<!y)x</code>
</td>
<td>
<p>
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"
>Assertions</a
>
</p>
</td>
</tr>
<tr>
<td>
<code>(<em>x</em>)</code>, <code>(?<Name>x)</code>, <code>(?:<em>x</em>)</code>,
<code>\<em>n</em></code>, <code>\k<Name></code>
</td>
<td>
<p>
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences"
>Groups and backreferences</a
>
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>*</code>, <code><em>x</em>+</code>, <code><em>x</em>?</code>,
<code><em>x</em>{<em>n</em>}</code>, <code><em>x</em>{<em>n</em>,}</code>,
<code><em>x</em>{<em>n</em>,<em>m</em>}</code>
</td>
<td>
<p>
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers"
>Quantifiers</a
>
</p>
</td>
</tr>
</tbody>
</table>
> **Note:** [A larger cheat sheet is also available](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet) (only aggregating parts of those individual articles).
### Escaping
If you need to use any of the special characters literally (actually searching for a `"*"`, for instance), you must escape it by putting a backslash in front of it.
For instance, to search for `"a"` followed by `"*"` followed by `"b"`, you'd use `/a\*b/` β the backslash "escapes" the `"*"`, making it literal instead of special.
Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern).
For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use `/\/example\/[a-z]+/i`βthe backslashes before each slash make them literal.
To match a literal backslash, you need to escape the backslash.
For instance, to match the string "C:\\" where "C" can be any letter, you'd use `/[A-Z]:\\/` β the first backslash escapes the one after it, so the expression searches for a single literal backslash.
If using the `RegExp` constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level.
`/a\*b/` and `new RegExp("a\\*b")` create the same expression, which searches for "a" followed by a literal "\*" followed by "b".
If escape strings are not already part of your pattern you can add them using {{jsxref("String.prototype.replace()")}}:
```js
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
```
The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.
It is explained in detail below in [Advanced Searching With Flags](#advanced_searching_with_flags).
_Why isn't this built into JavaScript?_ There is a [proposal](https://github.com/tc39/proposal-regex-escaping) to add such a function to RegExp.
### Using parentheses
Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered.
Once remembered, the substring can be recalled for other use. See [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences#using_groups) for more details.
## Using regular expressions in JavaScript
Regular expressions are used with the {{jsxref("RegExp")}} methods {{jsxref("RegExp/test", "test()")}} and {{jsxref("RegExp/exec", "exec()")}} and with the {{jsxref("String")}} methods {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, {{jsxref("String/search", "search()")}}, and {{jsxref("String/split", "split()")}}.
| Method | Description |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| {{jsxref("RegExp/exec", "exec()")}} | Executes a search for a match in a string. It returns an array of information or `null` on a mismatch. |
| {{jsxref("RegExp/test", "test()")}} | Tests for a match in a string. It returns `true` or `false`. |
| {{jsxref("String/match", "match()")}} | Returns an array containing all of the matches, including capturing groups, or `null` if no match is found. |
| {{jsxref("String/matchAll", "matchAll()")}} | Returns an iterator containing all of the matches, including capturing groups. |
| {{jsxref("String/search", "search()")}} | Tests for a match in a string. It returns the index of the match, or `-1` if the search fails. |
| {{jsxref("String/replace", "replace()")}} | Executes a search for a match in a string, and replaces the matched substring with a replacement substring. |
| {{jsxref("String/replaceAll", "replaceAll()")}} | Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. |
| {{jsxref("String/split", "split()")}} | Uses a regular expression or a fixed string to break a string into an array of substrings. |
When you want to know whether a pattern is found in a string, use the `test()` or `search()` methods; for more information (but slower execution) use the `exec()` or `match()` methods.
If you use `exec()` or `match()` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`.
If the match fails, the `exec()` method returns `null` (which coerces to `false`).
In the following example, the script uses the `exec()` method to find a match in a string.
```js
const myRe = /d(b+)d/g;
const myArray = myRe.exec("cdbbdbsbz");
```
If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script:
```js
const myArray = /d(b+)d/g.exec("cdbbdbsbz");
// similar to 'cdbbdbsbz'.match(/d(b+)d/g); however,
// 'cdbbdbsbz'.match(/d(b+)d/g) outputs [ "dbbd" ]
// while /d(b+)d/g.exec('cdbbdbsbz') outputs [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]
```
(See [Using the global search flag with `exec()`](#using_the_global_search_flag_with_exec) for further info about the different behaviors.)
If you want to construct the regular expression from a string, yet another alternative is this script:
```js
const myRe = new RegExp("d(b+)d", "g");
const myArray = myRe.exec("cdbbdbsbz");
```
With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.
<table class="standard-table">
<caption>
Results of regular expression execution.
</caption>
<thead>
<tr>
<th scope="col">Object</th>
<th scope="col">Property or index</th>
<th scope="col">Description</th>
<th scope="col">In this example</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="4"><code>myArray</code></td>
<td></td>
<td>The matched string and all remembered substrings.</td>
<td><code>['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']</code></td>
</tr>
<tr>
<td><code>index</code></td>
<td>The 0-based index of the match in the input string.</td>
<td><code>1</code></td>
</tr>
<tr>
<td><code>input</code></td>
<td>The original string.</td>
<td><code>'cdbbdbsbz'</code></td>
</tr>
<tr>
<td><code>[0]</code></td>
<td>The last matched characters.</td>
<td><code>'dbbd'</code></td>
</tr>
<tr>
<td rowspan="2"><code>myRe</code></td>
<td><code>lastIndex</code></td>
<td>The index at which to start the next match.
(This property is set only if the regular expression uses the g option, described in
<a href="#advanced_searching_with_flags">Advanced Searching With Flags</a>.)
</td>
<td><code>5</code></td>
</tr>
<tr>
<td><code>source</code></td>
<td>
The text of the pattern. Updated at the time that the regular expression is created, not executed.
</td>
<td><code>'d(b+)d'</code></td>
</tr>
</tbody>
</table>
As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable.
If you do, however, every occurrence is a new regular expression.
For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression.
For example, assume you have this script:
```js
const myRe = /d(b+)d/g;
const myArray = myRe.exec("cdbbdbsbz");
console.log(`The value of lastIndex is ${myRe.lastIndex}`);
// "The value of lastIndex is 5"
```
However, if you have this script:
```js
const myArray = /d(b+)d/g.exec("cdbbdbsbz");
console.log(`The value of lastIndex is ${/d(b+)d/g.lastIndex}`);
// "The value of lastIndex is 0"
```
The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property.
If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.
### Advanced searching with flags
Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching.
These flags can be used separately or together in any order, and are included as part of the regular expression.
| Flag | Description | Corresponding property |
| ---- | --------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `d` | Generate indices for substring matches. | {{jsxref("RegExp/hasIndices", "hasIndices")}} |
| `g` | Global search. | {{jsxref("RegExp/global", "global")}} |
| `i` | Case-insensitive search. | {{jsxref("RegExp/ignoreCase", "ignoreCase")}} |
| `m` | Allows `^` and `$` to match next to newline characters. | {{jsxref("RegExp/multiline", "multiline")}} |
| `s` | Allows `.` to match newline characters. | {{jsxref("RegExp/dotAll", "dotAll")}} |
| `u` | "Unicode"; treat a pattern as a sequence of Unicode code points. | {{jsxref("RegExp/unicode", "unicode")}} |
| `v` | An upgrade to the `u` mode with more Unicode features. | {{jsxref("RegExp/unicodeSets", "unicodeSets")}} |
| `y` | Perform a "sticky" search that matches starting at the current position in the target string. | {{jsxref("RegExp/sticky", "sticky")}} |
To include a flag with the regular expression, use this syntax:
```js
const re = /pattern/flags;
```
or
```js
const re = new RegExp("pattern", "flags");
```
Note that the flags are an integral part of a regular expression. They cannot be added or removed later.
For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.
```js
const re = /\w+\s/g;
const str = "fee fi fo fum";
const myArray = str.match(re);
console.log(myArray);
// ["fee ", "fi ", "fo "]
```
You could replace the line:
```js
const re = /\w+\s/g;
```
with:
```js
const re = new RegExp("\\w+\\s", "g");
```
and get the same result.
The `m` flag is used to specify that a multiline input string should be treated as multiple lines.
If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string.
#### Using the global search flag with exec()
{{jsxref("RegExp.prototype.exec()")}} method with the `g` flag returns each match and its position iteratively.
```js
const str = "fee fi fo fum";
const re = /\w+\s/g;
console.log(re.exec(str)); // ["fee ", index: 0, input: "fee fi fo fum"]
console.log(re.exec(str)); // ["fi ", index: 4, input: "fee fi fo fum"]
console.log(re.exec(str)); // ["fo ", index: 7, input: "fee fi fo fum"]
console.log(re.exec(str)); // null
```
In contrast, {{jsxref("String.prototype.match()")}} method returns all matches at once, but without their position.
```js
console.log(str.match(re)); // ["fee ", "fi ", "fo "]
```
#### Using unicode regular expressions
The `u` flag is used to create "unicode" regular expressions; that is, regular expressions which support matching against unicode text. An important feature that's enabled in unicode mode is [Unicode property escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape). For example, the following regular expression might be used to match against an arbitrary unicode "word":
```js
/\p{L}*/u;
```
Unicode regular expressions have different execution behavior as well. [`RegExp.prototype.unicode`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) contains more explanation about this.
## Examples
> **Note:** Several examples are also available in:
>
> - The reference pages for {{jsxref("RegExp/exec", "exec()")}}, {{jsxref("RegExp/test", "test()")}}, {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/search", "search()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/split", "split()")}}
> - The guide articles: [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes), [assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions), [groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences), [quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers)
### Using special characters to verify input
In the following example, the user is expected to enter a phone number.
When the user presses the "Check" button, the script checks the validity of the number.
If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number.
If the number is invalid, the script informs the user that the phone number is not valid.
The regular expression looks for:
1. the beginning of the line of data: `^`
2. followed by three numeric characters `\d{3}` OR `|` a left parenthesis `\(`, followed by three digits `\d{3}`, followed by a close parenthesis `\)`, in a non-capturing group `(?:)`
3. followed by one dash, forward slash, or decimal point in a capturing group `()`
4. followed by three digits `\d{3}`
5. followed by the match remembered in the (first) captured group `\1`
6. followed by four digits `\d{4}`
7. followed by the end of the line of data: `$`
#### HTML
```html
<p>
Enter your phone number (with area code) and then click "Check".
<br />
The expected format is like ###-###-####.
</p>
<form id="form">
<input id="phone" />
<button type="submit">Check</button>
</form>
<p id="output"></p>
```
#### JavaScript
```js
const form = document.querySelector("#form");
const input = document.querySelector("#phone");
const output = document.querySelector("#output");
const re = /^(?:\d{3}|\(\d{3}\))([-/.])\d{3}\1\d{4}$/;
function testInfo(phoneInput) {
const ok = re.exec(phoneInput.value);
output.textContent = ok
? `Thanks, your phone number is ${ok[0]}`
: `${phoneInput.value} isn't a phone number with area code!`;
}
form.addEventListener("submit", (event) => {
event.preventDefault();
testInfo(input);
});
```
#### Result
{{EmbedLiveSample("Using_special_characters_to_verify_input")}}
## Tools
- [RegExr](https://regexr.com/)
- : An online tool to learn, build, & test Regular Expressions.
- [Regex tester](https://regex101.com/)
- : An online regex builder/debugger
- [Regex interactive tutorial](https://regexlearn.com/)
- : An online interactive tutorials, Cheat sheet, & Playground.
- [Regex visualizer](https://extendsclass.com/regex-tester.html)
- : An online visual regex tester.
{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide/regular_expressions | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/character_classes/index.md | ---
title: Character classes
slug: Web/JavaScript/Guide/Regular_expressions/Character_classes
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.
{{EmbedInteractiveExample("pages/js/regexp-character-classes.html")}}
## Types
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>[xyz]<br />[a-c]</code>
</td>
<td>
<p>
A character class. Matches any one of the enclosed characters. You can
specify a range of characters by using a hyphen, but if the hyphen
appears as the first or last character enclosed in the square brackets,
it is taken as a literal hyphen to be included in the character class
as a normal character.
</p>
<p>
For example, <code>[abcd]</code> is the same as <code>[a-d]</code>.
They match the "b" in "brisket", and the "c" in "chop".
</p>
<p>
For example, <code>[abcd-]</code> and <code>[-abcd]</code> match the
"b" in "brisket", the "c" in "chop", and the "-" (hyphen) in
"non-profit".
</p>
<p>
For example, <code>[\w-]</code> is the same as
<code>[A-Za-z0-9_-]</code>. They both match the "b" in "brisket", the
"c" in "chop", and the "n" in "non-profit".
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>[^xyz]<br />[^a-c]</code>
</p>
</td>
<td>
<p>
A negated or complemented character class. That is, it matches
anything that is not enclosed in the square brackets. You can specify a range
of characters by using a hyphen, but if the hyphen appears as the
first character after the <code>^</code> or the last character enclosed in the square brackets, it is taken as
a literal hyphen to be included in the character class as a normal
character. For example, <code>[^abc]</code> is the same as
<code>[^a-c]</code>. They initially match "o" in "bacon" and "h" in
"chop".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> The ^ character may also indicate the
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"
>beginning of input</a
>.
</p>
</div>
</td>
</tr>
<tr>
<td><code>.</code></td>
<td>
<p>Has one of the following meanings:</p>
<ul>
<li>
Matches any single character <em>except</em> line terminators:
<code>\n</code>, <code>\r</code>, <code>\u2028</code> or
<code>\u2029</code>. For example, <code>/.y/</code> matches "my" and
"ay", but not "yes", in "yes make my day", as there is no character before "y" in "yes".
</li>
<li>
Inside a character class, the dot loses its special meaning and
matches a literal dot.
</li>
</ul>
<p>
Note that the <code>m</code> multiline flag doesn't change the dot
behavior. So to match a pattern across multiple lines, the character
class <code>[^]</code> can be used β it will match any character
including newlines.
</p>
<p>
The <code>s</code> "dotAll" flag allows the dot to
also match line terminators.
</p>
</td>
</tr>
<tr>
<td><code>\d</code></td>
<td>
<p>
Matches any digit (Arabic numeral). Equivalent to <code>[0-9]</code>.
For example, <code>/\d/</code> or <code>/[0-9]/</code> matches "2" in
"B2 is the suite number".
</p>
</td>
</tr>
<tr>
<td><code>\D</code></td>
<td>
<p>
Matches any character that is not a digit (Arabic numeral). Equivalent
to <code>[^0-9]</code>. For example, <code>/\D/</code> or
<code>/[^0-9]/</code> matches "B" in "B2 is the suite number".
</p>
</td>
</tr>
<tr>
<td><code>\w</code></td>
<td>
<p>
Matches any alphanumeric character from the basic Latin alphabet,
including the underscore. Equivalent to <code>[A-Za-z0-9_]</code>. For
example, <code>/\w/</code> matches "a" in "apple", "5" in "$5.28", "3"
in "3D" and "m" in "Γmanuel".
</p>
</td>
</tr>
<tr>
<td><code>\W</code></td>
<td>
<p>
Matches any character that is not a word character from the basic
Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>. For example,
<code>/\W/</code> or <code>/[^A-Za-z0-9_]/</code> matches "%" in "50%"
and "Γ" in "Γmanuel".
</p>
</td>
</tr>
<tr>
<td><code>\s</code></td>
<td>
<p>
Matches a single white space character, including space, tab, form
feed, line feed, and other Unicode spaces. Equivalent to
<code>[\f\n\r\t\v\u0020\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>. For example, <code>/\s\w*/</code> matches " bar" in "foo bar".
</p>
</td>
</tr>
<tr>
<td><code>\S</code></td>
<td>
<p>
Matches a single character other than white space. Equivalent to
<code>[^\f\n\r\t\v\u0020\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>. For example, <code>/\S\w*/</code> matches "foo" in "foo bar".
</p>
</td>
</tr>
<tr>
<td><code>\t</code></td>
<td>Matches a horizontal tab.</td>
</tr>
<tr>
<td><code>\r</code></td>
<td>Matches a carriage return.</td>
</tr>
<tr>
<td><code>\n</code></td>
<td>Matches a linefeed.</td>
</tr>
<tr>
<td><code>\v</code></td>
<td>Matches a vertical tab.</td>
</tr>
<tr>
<td><code>\f</code></td>
<td>Matches a form-feed.</td>
</tr>
<tr>
<td><code>[\b]</code></td>
<td>
Matches a backspace. If you're looking for the word-boundary character
(<code>\b</code>), see
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"
>Assertions</a
>.
</td>
</tr>
<tr>
<td><code>\0</code></td>
<td>Matches a NUL character. Do not follow this with another digit.</td>
</tr>
<tr>
<td>
<code>\c<em>X</em></code>
</td>
<td>
<p>
Matches a control character using
<a href="https://en.wikipedia.org/wiki/Caret_notation"
>caret notation</a
>, where "X" is a letter from AβZ (corresponding to code points
<code>U+0001</code><em>β</em><code>U+001A</code>). For example,
<code>/\cM\cJ/</code> matches "\r\n".
</p>
</td>
</tr>
<tr>
<td>
<code>\x<em>hh</em></code>
</td>
<td>
Matches the character with the code <code><em>hh</em></code> (two
hexadecimal digits).
</td>
</tr>
<tr>
<td>
<code>\u<em>hhhh</em></code>
</td>
<td>
Matches a UTF-16 code-unit with the value
<code><em>hhhh</em></code> (four hexadecimal digits).
</td>
</tr>
<tr>
<td>
<code>\u<em>{hhhh}</em> or <em>\u{hhhhh}</em></code>
</td>
<td>
(Only when the <code>u</code> flag is set.) Matches the character with
the Unicode value <code>U+<em>hhhh</em></code> or <code
>U+<em>hhhhh</em></code
>
(hexadecimal digits).
</td>
</tr>
<tr>
<td>
<code>\p{<em>UnicodeProperty</em>}</code>,
<code>\P{<em>UnicodeProperty</em>}</code>
</td>
<td>
Matches a character based on its
<a
href="/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape"
>Unicode character properties</a
>
(to match just, for example, emoji characters, or Japanese
<em>katakana</em> characters, or Chinese/Japanese Han/Kanji characters,
etc.).
</td>
</tr>
<tr>
<td><code>\</code></td>
<td>
<p>
Indicates that the following character should be treated specially, or
"escaped". It behaves one of two ways.
</p>
<ul>
<li>
For characters that are usually treated literally, indicates that
the next character is special and not to be interpreted literally.
For example, <code>/b/</code> matches the character "b". By placing
a backslash in front of "b", that is by using <code>/\b/</code>, the
character becomes special to mean match a word boundary.
</li>
<li>
For characters that are usually treated specially, indicates that
the next character is not special and should be interpreted
literally. For example, "*" is a special character that means 0 or
more occurrences of the preceding character should be matched; for
example, <code>/a*/</code> means match 0 or more "a"s. To match
<code>*</code> literally, precede it with a backslash; for example,
<code>/a\*/</code> matches "a*".
</li>
</ul>
<div class="notecard note">
<p>
<strong>Note:</strong> To match this character literally, escape it
with itself. In other words to search for <code>\</code> use
<code>/\\/</code>.
</p>
</div>
</td>
</tr>
<tr>
<td>
<code><em>x</em>|<em>y</em></code>
</td>
<td>
<p>
<strong>Disjunction: </strong>Matches either "x" or "y". Each component, separated by a pipe (<code>|</code>), is called an <em>alternative</em>. For example,
<code>/green|red/</code> matches "green" in "green apple" and "red" in
"red apple".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> A disjunction is another way to specify "a set of choices", but it's not a character class. Disjunctions are not atoms β you need to use a <a href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences">group</a> to make it part of a bigger pattern. <code>[abc]</code> is functionally equivalent to <code>(?:a|b|c)</code>.
</p>
</div>
</td>
</tr>
</tbody>
</table>
## Examples
### Looking for a series of digits
```js
const randomData = "015 354 8787 687351 3512 8735";
const regexpFourDigits = /\b\d{4}\b/g;
// \b indicates a boundary (i.e. do not start matching in the middle of a word)
// \d{4} indicates a digit, four times
// \b indicates another boundary (i.e. do not end matching in the middle of a word)
console.table(randomData.match(regexpFourDigits));
// ['8787', '3512', '8735']
```
### Looking for a word (from the latin alphabet) starting with A
```js
const aliceExcerpt =
"I'm sure I'm not Ada,' she said, 'for her hair goes in such long ringlets, and mine doesn't go in ringlets at all.";
const regexpWordStartingWithA = /\b[aA]\w+/g;
// \b indicates a boundary (i.e. do not start matching in the middle of a word)
// [aA] indicates the letter a or A
// \w+ indicates any character *from the latin alphabet*, multiple times
console.table(aliceExcerpt.match(regexpWordStartingWithA));
// ['Ada', 'and', 'at', 'all']
```
### Looking for a word (from Unicode characters)
Instead of the Latin alphabet, we can use a range of Unicode characters to identify a word (thus being able to deal with text in other languages like Russian or Arabic). The "Basic Multilingual Plane" of Unicode contains most of the characters used around the world and we can use character classes and ranges to match words written with those characters.
```js
const nonEnglishText = "ΠΡΠΈΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ΠΠ»ΠΈΡΡ Π² Π‘ΡΡΠ°Π½Π΅ ΡΡΠ΄Π΅Ρ";
const regexpBMPWord = /([\u0000-\u0019\u0021-\uFFFF])+/gu;
// BMP goes through U+0000 to U+FFFF but space is U+0020
console.table(nonEnglishText.match(regexpBMPWord));
["ΠΡΠΈΠΊΠ»ΡΡΠ΅Π½ΠΈΡ", "ΠΠ»ΠΈΡΡ", "Π²", "Π‘ΡΡΠ°Π½Π΅", "ΡΡΠ΄Π΅Ρ"];
```
### Counting vowels
```js
const aliceExcerpt =
"There was a long silence after this, and Alice could only hear whispers now and then.";
const regexpVowels = /[AEIOUYaeiouy]/g;
console.log("Number of vowels:", aliceExcerpt.match(regexpVowels).length);
// Number of vowels: 26
```
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
| 0 |
data/mdn-content/files/en-us/web/javascript/guide/regular_expressions | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/cheatsheet/index.md | ---
title: Regular expression syntax cheat sheet
slug: Web/JavaScript/Guide/Regular_expressions/Cheatsheet
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
This page provides an overall cheat sheet of all the capabilities of `RegExp` syntax by aggregating the content of the articles in the `RegExp` guide. If you need more information on a specific topic, please follow the link on the corresponding heading to access the full article or head to [the guide](/en-US/docs/Web/JavaScript/Guide/Regular_expressions).
## Character classes
[Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) distinguish kinds of characters such as, for example, distinguishing between letters and digits.
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>[xyz]<br />[a-c]</code>
</td>
<td>
<p>
A character class. Matches any one of the enclosed characters. You can
specify a range of characters by using a hyphen, but if the hyphen
appears as the first or last character enclosed in the square brackets,
it is taken as a literal hyphen to be included in the character class
as a normal character.
</p>
<p>
For example, <code>[abcd]</code> is the same as <code>[a-d]</code>.
They match the "b" in "brisket", and the "a" or the "c" in "arch",
but not the "-" (hyphen) in "non-profit".
</p>
<p>
For example, <code>[abcd-]</code> and <code>[-abcd]</code> match the
"b" in "brisket", the "a" or the "c" in "arch", and the "-" (hyphen)
in "non-profit".
</p>
<p>
For example, <code>[\w-]</code> is the same as
<code>[A-Za-z0-9_-]</code>. They both match any of the characters in
"[email protected]" except for the "@" and the ".".
</p>
</td>
</tr>
<tr>
<td>
<p>
<code>[^xyz]<br />[^a-c]</code>
</p>
</td>
<td>
<p>
A negated or complemented character class. That is, it matches
anything that is not enclosed in the square brackets. You can specify a range
of characters by using a hyphen, but if the hyphen appears as the
first or last character enclosed in the square brackets, it is taken as
a literal hyphen to be included in the character class as a normal
character. For example, <code>[^abc]</code> is the same as
<code>[^a-c]</code>. They initially match "o" in "bacon" and "h" in
"chop".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> The ^ character may also indicate the
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"
>beginning of input</a
>.
</p>
</div>
</td>
</tr>
<tr>
<td><code>.</code></td>
<td>
<p>Has one of the following meanings:</p>
<ul>
<li>
Matches any single character <em>except</em> line terminators:
<code>\n</code>, <code>\r</code>, <code>\u2028</code> or
<code>\u2029</code>. For example, <code>/.y/</code> matches "my" and
"ay", but not "yes", in "yes make my day".
</li>
<li>
Inside a character class, the dot loses its special meaning and
matches a literal dot.
</li>
</ul>
<p>
Note that the <code>m</code> multiline flag doesn't change the dot
behavior. So to match a pattern across multiple lines, the character
class <code>[^]</code> can be used β it will match any character
including newlines.
</p>
<p>
The <code>s</code> "dotAll" flag allows the dot to
also match line terminators.
</p>
</td>
</tr>
<tr>
<td><code>\d</code></td>
<td>
<p>
Matches any digit (Arabic numeral). Equivalent to <code>[0-9]</code>.
For example, <code>/\d/</code> or <code>/[0-9]/</code> matches "2" in
"B2 is the suite number".
</p>
</td>
</tr>
<tr>
<td><code>\D</code></td>
<td>
<p>
Matches any character that is not a digit (Arabic numeral). Equivalent
to <code>[^0-9]</code>. For example, <code>/\D/</code> or
<code>/[^0-9]/</code> matches "B" in "B2 is the suite number".
</p>
</td>
</tr>
<tr>
<td><code>\w</code></td>
<td>
<p>
Matches any alphanumeric character from the basic Latin alphabet,
including the underscore. Equivalent to <code>[A-Za-z0-9_]</code>. For
example, <code>/\w/</code> matches "a" in "apple", "5" in "$5.28", and
"3" in "3D".
</p>
</td>
</tr>
<tr>
<td><code>\W</code></td>
<td>
<p>
Matches any character that is not a word character from the basic
Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>. For example,
<code>/\W/</code> or <code>/[^A-Za-z0-9_]/</code> matches "%" in
"50%".
</p>
</td>
</tr>
<tr>
<td><code>\s</code></td>
<td>
<p>
Matches a single white space character, including space, tab, form
feed, line feed, and other Unicode spaces. Equivalent to
<code
>[
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code
>. For example, <code>/\s\w*/</code> matches " bar" in "foo bar".
</p>
</td>
</tr>
<tr>
<td><code>\S</code></td>
<td>
<p>
Matches a single character other than white space. Equivalent to
<code
>[^
\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code
>. For example, <code>/\S\w*/</code> matches "foo" in "foo bar".
</p>
</td>
</tr>
<tr>
<td><code>\t</code></td>
<td>Matches a horizontal tab.</td>
</tr>
<tr>
<td><code>\r</code></td>
<td>Matches a carriage return.</td>
</tr>
<tr>
<td><code>\n</code></td>
<td>Matches a linefeed.</td>
</tr>
<tr>
<td><code>\v</code></td>
<td>Matches a vertical tab.</td>
</tr>
<tr>
<td><code>\f</code></td>
<td>Matches a form-feed.</td>
</tr>
<tr>
<td><code>[\b]</code></td>
<td>
Matches a backspace. If you're looking for the word-boundary character
(<code>\b</code>), see
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"
>Boundaries</a
>.
</td>
</tr>
<tr>
<td><code>\0</code></td>
<td>Matches a NUL character. Do not follow this with another digit.</td>
</tr>
<tr>
<td>
<code>\c<em>X</em></code>
</td>
<td>
<p>
Matches a control character using
<a href="https://en.wikipedia.org/wiki/Caret_notation"
>caret notation</a
>, where "X" is a letter from AβZ (corresponding to code points
<code>U+0001</code><em>β</em><code>U+001F</code>). For example,
<code>/\cM/</code> matches "\r" in "\r\n".
</p>
</td>
</tr>
<tr>
<td>
<code>\x<em>hh</em></code>
</td>
<td>
Matches the character with the code <code><em>hh</em></code> (two
hexadecimal digits).
</td>
</tr>
<tr>
<td>
<code>\u<em>hhhh</em></code>
</td>
<td>
Matches a UTF-16 code-unit with the value
<code><em>hhhh</em></code> (four hexadecimal digits).
</td>
</tr>
<tr>
<td>
<code>\u<em>{hhhh}</em> or <em>\u{hhhhh}</em></code>
</td>
<td>
(Only when the <code>u</code> flag is set.) Matches the character with
the Unicode value <code>U+<em>hhhh</em></code> or <code
>U+<em>hhhhh</em></code
>
(hexadecimal digits).
</td>
</tr>
<tr>
<td><code>\</code></td>
<td>
<p>
Indicates that the following character should be treated specially, or
"escaped". It behaves one of two ways.
</p>
<ul>
<li>
For characters that are usually treated literally, indicates that
the next character is special and not to be interpreted literally.
For example, <code>/b/</code> matches the character "b". By placing
a backslash in front of "b", that is by using <code>/\b/</code>, the
character becomes special to mean match a word boundary.
</li>
<li>
For characters that are usually treated specially, indicates that
the next character is not special and should be interpreted
literally. For example, "*" is a special character that means 0 or
more occurrences of the preceding character should be matched; for
example, <code>/a*/</code> means match 0 or more "a"s. To match
<code>*</code> literally, precede it with a backslash; for example,
<code>/a\*/</code> matches "a*".
</li>
</ul>
<p>
Note that some characters like <code>:</code>, <code>-</code>,
<code>@</code>, etc. neither have a special meaning when escaped nor
when unescaped. Escape sequences like <code>\:</code>,
<code>\-</code>, <code>\@</code> will be equivalent to their literal,
unescaped character equivalents in regular expressions. However, in
regular expressions with the
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags"
>unicode flag</a
>, these will cause an <em>invalid identity escape</em> error. This is
done to ensure backward compatibility with existing code that uses new
escape sequences like <code>\p</code> or <code>\k</code>.
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> To match this character literally, escape it
with itself. In other words to search for <code>\</code> use
<code>/\\/</code>.
</p>
</div>
</td>
</tr>
<tr>
<td>
<code><em>x</em>|<em>y</em></code>
</td>
<td>
<p>
<strong>Disjunction: </strong>Matches either "x" or "y". Each component, separated by a pipe (<code>|</code>), is called an <em>alternative</em>. For example,
<code>/green|red/</code> matches "green" in "green apple" and "red" in
"red apple".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> A disjunction is another way to specify "a set of choices", but it's not a character class. Disjunctions are not atoms β you need to use a <a href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences">group</a> to make it part of a bigger pattern. <code>[abc]</code> is functionally equivalent to <code>(?:a|b|c)</code>.
</p>
</div>
</td>
</tr>
</tbody>
</table>
## Assertions
[Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).
### Boundary-type assertions
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>^</code></td>
<td>
<p>
Matches the beginning of input. If the multiline flag is set to true,
also matches immediately after a line break character. For example,
<code>/^A/</code> does not match the "A" in "an A", but does match the
first "A" in "An A".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> This character has a different meaning when
it appears at the start of a
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"
>character class</a
>.
</p>
</div>
</td>
</tr>
<tr>
<td><code>$</code></td>
<td>
<p>
Matches the end of input. If the multiline flag is set to true, also
matches immediately before a line break character. For example,
<code>/t$/</code> does not match the "t" in "eater", but does match it
in "eat".
</p>
</td>
</tr>
<tr>
<td><code>\b</code></td>
<td>
<p>
Matches a word boundary. This is the position where a word character
is not followed or preceded by another word-character, such as between
a letter and a space. Note that a matched word boundary is not
included in the match. In other words, the length of a matched word
boundary is zero.
</p>
<p>Examples:</p>
<ul>
<li><code>/\bm/</code> matches the "m" in "moon".</li>
<li>
<code>/oo\b/</code> does not match the "oo" in "moon", because "oo"
is followed by "n" which is a word character.
</li>
<li>
<code>/oon\b/</code> matches the "oon" in "moon", because "oon" is
the end of the string, thus not followed by a word character.
</li>
<li>
<code>/\w\b\w/</code> will never match anything, because a word
character can never be followed by both a non-word and a word
character.
</li>
</ul>
<p>
To match a backspace character (<code>[\b]</code>), see
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"
>Character Classes</a
>.
</p>
</td>
</tr>
<tr>
<td><code>\B</code></td>
<td>
<p>
Matches a non-word boundary. This is a position where the previous and
next character are of the same type: Either both must be words, or
both must be non-words, for example between two letters or between two
spaces. The beginning and end of a string are considered non-words.
Same as the matched word boundary, the matched non-word boundary is
also not included in the match. For example,
<code>/\Bon/</code> matches "on" in "at noon", and
<code>/ye\B/</code> matches "ye" in "possibly yesterday".
</p>
</td>
</tr>
</tbody>
</table>
### Other assertions
> **Note:** The `?` character may also be used as a quantifier.
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>x(?=y)</code></td>
<td>
<p>
<strong>Lookahead assertion: </strong>Matches "x" only if "x" is
followed by "y". For example, /<code>Jack(?=Sprat)/</code> matches
"Jack" only if it is followed by "Sprat".<br /><code
>/Jack(?=Sprat|Frost)/</code
>
matches "Jack" only if it is followed by "Sprat" or "Frost". However,
neither "Sprat" nor "Frost" is part of the match results.
</p>
</td>
</tr>
<tr>
<td><code>x(?!y)</code></td>
<td>
<p>
<strong>Negative lookahead assertion: </strong>Matches "x" only if "x"
is not followed by "y". For example, <code>/\d+(?!\.)/</code> matches
a number only if it is not followed by a decimal point. <code
>/\d+(?!\.)/.exec('3.141')</code
>
matches "141" but not "3".
</p>
</td>
</tr>
<tr>
<td><code>(?<=y)x</code></td>
<td>
<p>
<strong>Lookbehind assertion: </strong>Matches "x" only if "x" is
preceded by "y". For example,
<code>/(?<=Jack)Sprat/</code> matches "Sprat" only if it is
preceded by "Jack". <code>/(?<=Jack|Tom)Sprat/</code> matches
"Sprat" only if it is preceded by "Jack" or "Tom". However, neither
"Jack" nor "Tom" is part of the match results.
</p>
</td>
</tr>
<tr>
<td><code>(?<!y)x</code></td>
<td>
<p>
<strong>Negative lookbehind assertion: </strong>Matches "x" only if
"x" is not preceded by "y". For example,
<code>/(?<!-)\d+/</code> matches a number only if it is not
preceded by a minus sign. <code>/(?<!-)\d+/.exec('3')</code>
matches "3". <code>/(?<!-)\d+/.exec('-3')</code> match is not
found because the number is preceded by the minus sign.
</p>
</td>
</tr>
</tbody>
</table>
## Groups and backreferences
[Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) indicate groups of expression characters.
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>(<em>x</em>)</code></td>
<td>
<p>
<strong>Capturing group: </strong>Matches <code><em>x</em></code> and
remembers the match. For example, <code>/(foo)/</code> matches and
remembers "foo" in "foo bar".
</p>
<p>
A regular expression may have multiple capturing groups. In results,
matches to capturing groups typically in an array whose members are in
the same order as the left parentheses in the capturing group. This is
usually just the order of the capturing groups themselves. This
becomes important when capturing groups are nested. Matches are
accessed using the index of the result's elements (<code
>[1], β¦, [n]</code
>) or from the predefined <code>RegExp</code> object's properties
(<code>$1, β¦, $9</code>).
</p>
<p>
Capturing groups have a performance penalty. If you don't need the
matched substring to be recalled, prefer non-capturing parentheses
(see below).
</p>
<p>
<code
><a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match"
>String.prototype.match()</a
></code
>
won't return groups if the <code>/.../g</code> flag is set. However,
you can still use
<code
><a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll"
>String.prototype.matchAll()</a
></code
>
to get all matches.
</p>
</td>
</tr>
<tr>
<td><code>(?<Name>x)</code></td>
<td>
<p>
<strong>Named capturing group: </strong>Matches "x" and stores it on
the groups property of the returned matches under the name specified
by <code><Name></code>. The angle brackets (<code><</code>
and <code>></code>) are required for group name.
</p>
<p>
For example, to extract the United States area code from a phone
number, we could use <code>/\((?<area>\d\d\d)\)/</code>. The
resulting number would appear under <code>matches.groups.area</code>.
</p>
</td>
</tr>
<tr>
<td><code>(?:<em>x</em>)</code></td>
<td>
<strong>Non-capturing group: </strong>Matches "x" but does not remember
the match. The matched substring cannot be recalled from the resulting
array's elements (<code>[1], β¦, [n]</code>) or from the predefined
<code>RegExp</code> object's properties (<code>$1, β¦, $9</code>).
</td>
</tr>
<tr>
<td>
<code>\<em>n</em></code>
</td>
<td>
<p>
Where "n" is a positive integer. A back reference to the last
substring matching the n parenthetical in the regular expression
(counting left parentheses). For example,
<code>/apple(,)\sorange\1/</code> matches "apple, orange," in "apple,
orange, cherry, peach".
</p>
</td>
</tr>
<tr>
<td>\k<Name></td>
<td>
<p>
A back reference to the last substring matching the <strong
>Named capture group </strong
>specified by <code><Name></code>.
</p>
<p>
For example, <code>/(?<title>\w+), yes \k<title>/</code
> matches "Sir, yes Sir" in "Do you copy? Sir, yes Sir!".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> <code>\k</code> is used literally here to
indicate the beginning of a back reference to a Named capture group.
</p>
</div>
</td>
</tr>
</tbody>
</table>
## Quantifiers
[Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) indicate numbers of characters or expressions to match.
> **Note:** In the following, _item_ refers not only to singular characters, but also includes [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) and [groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences).
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><em>x</em>*</code>
</td>
<td>
<p>
Matches the preceding item "x" 0 or more times. For example,
<code>/bo*/</code> matches "boooo" in "A ghost booooed" and "b" in "A
bird warbled", but nothing in "A goat grunted".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>+</code>
</td>
<td>
<p>
Matches the preceding item "x" 1 or more times. Equivalent to
<code>{1,}</code>. For example, <code>/a+/</code> matches the "a" in
"candy" and all the "a"'s in "caaaaaaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>?</code>
</td>
<td>
<p>
Matches the preceding item "x" 0 or 1 times. For example,
<code>/e?le?/</code> matches the "el" in "angel" and the "le" in
"angle."
</p>
<p>
If used immediately after any of the quantifiers <code>*</code>,
<code>+</code>, <code>?</code>, or <code>{}</code>, makes the
quantifier non-greedy (matching the minimum number of times), as
opposed to the default, which is greedy (matching the maximum number
of times).
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>}</code>
</td>
<td>
<p>
Where "n" is a positive integer, matches exactly "n" occurrences of
the preceding item "x". For example, <code>/a{2}/</code> doesn't match
the "a" in "candy", but it matches all of the "a"'s in "caandy", and
the first two "a"'s in "caaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>,}</code>
</td>
<td>
<p>
Where "n" is a positive integer, matches at least "n" occurrences of
the preceding item "x". For example, <code>/a{2,}/</code> doesn't
match the "a" in "candy", but matches all of the a's in "caandy" and
in "caaaaaaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>,<em>m</em>}</code>
</td>
<td>
<p>
Where "n" is 0 or a positive integer, "m" is a positive integer, and
<code><em>m</em> > <em>n</em></code
>, matches at least "n" and at most "m" occurrences of the preceding
item "x". For example, <code>/a{1,3}/</code> matches nothing in
"cndy", the "a" in "candy", the two "a"'s in "caandy", and the first
three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy",
the match is "aaa", even though the original string had more "a"s in
it.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code><em>x</em>*?</code><br /><code><em>x</em>+?</code><br /><code
><em>x</em>??</code
><br /><code><em>x</em>{n}?</code><br /><code><em>x</em>{n,}?</code
><br /><code><em>x</em>{n,m}?</code>
</p>
</td>
<td>
<p>
By default quantifiers like <code>*</code> and <code>+</code> are
"greedy", meaning that they try to match as much of the string as
possible. The <code>?</code> character after the quantifier makes the
quantifier "non-greedy": meaning that it will stop as soon as it finds
a match. For example, given a string like "some <foo> <bar>
new </bar> </foo> thing":
</p>
<ul>
<li>
<code>/<.*>/</code> will match "<foo> <bar> new
</bar> </foo>"
</li>
<li><code>/<.*?>/</code> will match "<foo>"</li>
</ul>
</td>
</tr>
</tbody>
</table>
| 0 |
data/mdn-content/files/en-us/web/javascript/guide/regular_expressions | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/groups_and_backreferences/index.md | ---
title: Groups and backreferences
slug: Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.
{{EmbedInteractiveExample("pages/js/regexp-groups-backreferences.html")}}
## Types
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>(<em>x</em>)</code></td>
<td>
<p>
<strong>Capturing group: </strong>Matches <code><em>x</em></code> and
remembers the match. For example, <code>/(foo)/</code> matches and
remembers "foo" in "foo bar".
</p>
<p>
A regular expression may have multiple capturing groups. In results,
matches to capturing groups typically in an array whose members are in
the same order as the left parentheses in the capturing group. This is
usually just the order of the capturing groups themselves. This
becomes important when capturing groups are nested. Matches are
accessed using the index of the result's elements (<code
>[1], β¦, [n]</code
>) or from the predefined <code>RegExp</code> object's properties
(<code>$1, β¦, $9</code>).
</p>
<p>
Capturing groups have a performance penalty. If you don't need the
matched substring to be recalled, prefer non-capturing parentheses
(see below).
</p>
<p>
<code
><a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match"
>String.prototype.match()</a
></code
>
won't return groups if the <code>/.../g</code> flag is set. However,
you can still use
<code
><a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll"
>String.prototype.matchAll()</a
></code
>
to get all matches.
</p>
</td>
</tr>
<tr>
<td><code>(?<Name>x)</code></td>
<td>
<p>
<strong>Named capturing group: </strong>Matches "x" and stores it on
the groups property of the returned matches under the name specified
by <code><Name></code>. The angle brackets (<code><</code>
and <code>></code>) are required for group name.
</p>
<p>
For example, to extract the United States area code from a phone
number, we could use <code>/\((?<area>\d\d\d)\)/</code>. The
resulting number would appear under <code>matches.groups.area</code>.
</p>
</td>
</tr>
<tr>
<td><code>(?:<em>x</em>)</code></td>
<td>
<strong>Non-capturing group: </strong>Matches "x" but does not remember
the match. The matched substring cannot be recalled from the resulting
array's elements (<code>[1], β¦, [n]</code>) or from the predefined
<code>RegExp</code> object's properties (<code>$1, β¦, $9</code>).
</td>
</tr>
<tr>
<td>
<code>\<em>n</em></code>
</td>
<td>
<p>
Where "n" is a positive integer. A back reference to the last
substring matching the n parenthetical in the regular expression
(counting left parentheses). For example,
<code>/apple(,)\sorange\1/</code> matches "apple, orange," in "apple,
orange, cherry, peach".
</p>
</td>
</tr>
<tr>
<td><code>\k<Name></code></td>
<td>
<p>
A back reference to the last substring matching the
<strong>Named capture group</strong> specified by
<code><Name></code>.
</p>
<p>
For example,
<code>/(?<title>\w+), yes \k<title>/</code> matches "Sir,
yes Sir" in "Do you copy? Sir, yes Sir!".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> <code>\k</code> is used literally here to
indicate the beginning of a back reference to a Named capture group.
</p>
</div>
</td>
</tr>
</tbody>
</table>
## Examples
### Using groups
```js
const personList = `First_Name: John, Last_Name: Doe
First_Name: Jane, Last_Name: Smith`;
const regexpNames = /First_Name: (\w+), Last_Name: (\w+)/gm;
for (const match of personList.matchAll(regexpNames)) {
console.log(`Hello ${match[1]} ${match[2]}`);
}
```
### Using named groups
```js
const personList = `First_Name: John, Last_Name: Doe
First_Name: Jane, Last_Name: Smith`;
const regexpNames =
/First_Name: (?<firstname>\w+), Last_Name: (?<lastname>\w+)/gm;
for (const match of personList.matchAll(regexpNames)) {
console.log(`Hello ${match.groups.firstname} ${match.groups.lastname}`);
}
```
### Using groups and back references
```js
const quote = `Single quote "'" and double quote '"'`;
const regexpQuotes = /(['"]).*?\1/g;
for (const match of quote.matchAll(regexpQuotes)) {
console.log(match[0]);
}
```
### Using groups and match indices
By providing the `d` flag, the indices of each capturing group is returned. This is especially useful if you are correlating each matched group with the original text β for example, to provide compiler diagnostics.
```js
const code = `function add(x, y) {
return x + y;
}`;
const functionRegexp =
/(function\s+)(?<name>[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/du;
const match = functionRegexp.exec(code);
const lines = code.split("\n");
lines.splice(
1,
0,
" ".repeat(match.indices[1][1] - match.indices[1][0]) +
"^".repeat(match.indices.groups.name[1] - match.indices.groups.name[0]),
);
console.log(lines.join("\n"));
// function add(x, y) {
// ^^^
// return x + y;
// }
```
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide
- [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
| 0 |
data/mdn-content/files/en-us/web/javascript/guide/regular_expressions | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/assertions/index.md | ---
title: Assertions
slug: Web/JavaScript/Guide/Regular_expressions/Assertions
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).
{{EmbedInteractiveExample("pages/js/regexp-assertions.html", "taller")}}
## Types
### Boundary-type assertions
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>^</code></td>
<td>
<p>
Matches the beginning of input. If the multiline flag is set to true,
also matches immediately after a line break character. For example,
<code>/^A/</code> does not match the "A" in "an A", but does match the
first "A" in "An A".
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> This character has a different meaning when
it appears at the start of a
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"
>character class</a
>.
</p>
</div>
</td>
</tr>
<tr>
<td><code>$</code></td>
<td>
<p>
Matches the end of input. If the multiline flag is set to true, also
matches immediately before a line break character. For example,
<code>/t$/</code> does not match the "t" in "eater", but does match it
in "eat".
</p>
</td>
</tr>
<tr>
<td><code>\b</code></td>
<td>
<p>
Matches a word boundary. This is the position where a word character
is not followed or preceded by another word-character, such as between
a letter and a space. Note that a matched word boundary is not
included in the match. In other words, the length of a matched word
boundary is zero.
</p>
<p>Examples:</p>
<ul>
<li><code>/\bm/</code> matches the "m" in "moon".</li>
<li>
<code>/oo\b/</code> does not match the "oo" in "moon", because "oo"
is followed by "n" which is a word character.
</li>
<li>
<code>/oon\b/</code> matches the "oon" in "moon", because "oon" is
the end of the string, thus not followed by a word character.
</li>
<li>
<code>/\w\b\w/</code> will never match anything, because a word
character can never be followed by both a non-word and a word
character.
</li>
</ul>
<p>
To match a backspace character (<code>[\b]</code>), see
<a
href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"
>Character Classes</a
>.
</p>
</td>
</tr>
<tr>
<td><code>\B</code></td>
<td>
<p>
Matches a non-word boundary. This is a position where the previous and
next character are of the same type: Either both must be words, or
both must be non-words, for example between two letters or between two
spaces. The beginning and end of a string are considered non-words.
Same as the matched word boundary, the matched non-word boundary is
also not included in the match. For example,
<code>/\Bon/</code> matches "on" in "at noon", and
<code>/ye\B/</code> matches "ye" in "possibly yesterday".
</p>
</td>
</tr>
</tbody>
</table>
### Other assertions
> **Note:** The `?` character may also be used as a quantifier.
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>x(?=y)</code></td>
<td>
<p>
<strong>Lookahead assertion: </strong>Matches "x" only if "x" is
followed by "y". For example, <code>/Jack(?=Sprat)/</code> matches
"Jack" only if it is followed by "Sprat".<br /><code
>/Jack(?=Sprat|Frost)/</code
>
matches "Jack" only if it is followed by "Sprat" or "Frost". However,
neither "Sprat" nor "Frost" is part of the match results.
</p>
</td>
</tr>
<tr>
<td><code>x(?!y)</code></td>
<td>
<p>
<strong>Negative lookahead assertion: </strong>Matches "x" only if "x"
is not followed by "y". For example, <code>/\d+(?!\.)/</code> matches
a number only if it is not followed by a decimal point. <code
>/\d+(?!\.)/.exec('3.141')</code
>
matches "141" but not "3".
</p>
</td>
</tr>
<tr>
<td><code>(?<=y)x</code></td>
<td>
<p>
<strong>Lookbehind assertion: </strong>Matches "x" only if "x" is
preceded by "y". For example,
<code>/(?<=Jack)Sprat/</code> matches "Sprat" only if it is
preceded by "Jack". <code>/(?<=Jack|Tom)Sprat/</code> matches
"Sprat" only if it is preceded by "Jack" or "Tom". However, neither
"Jack" nor "Tom" is part of the match results.
</p>
</td>
</tr>
<tr>
<td><code>(?<!y)x</code></td>
<td>
<p>
<strong>Negative lookbehind assertion: </strong>Matches "x" only if
"x" is not preceded by "y". For example,
<code>/(?<!-)\d+/</code> matches a number only if it is not
preceded by a minus sign. <code>/(?<!-)\d+/.exec('3')</code>
matches "3". <code>/(?<!-)\d+/.exec('-3')</code> match is not
found because the number is preceded by the minus sign.
</p>
</td>
</tr>
</tbody>
</table>
## Examples
### General boundary-type overview example
```js
// Using Regex boundaries to fix buggy string.
buggyMultiline = `tey, ihe light-greon apple
tangs on ihe greon traa`;
// 1) Use ^ to fix the matching at the beginning of the string, and right after newline.
buggyMultiline = buggyMultiline.replace(/^t/gim, "h");
console.log(1, buggyMultiline); // fix 'tey' => 'hey' and 'tangs' => 'hangs' but do not touch 'traa'.
// 2) Use $ to fix matching at the end of the text.
buggyMultiline = buggyMultiline.replace(/aa$/gim, "ee.");
console.log(2, buggyMultiline); // fix 'traa' => 'tree.'.
// 3) Use \b to match characters right on border between a word and a space.
buggyMultiline = buggyMultiline.replace(/\bi/gim, "t");
console.log(3, buggyMultiline); // fix 'ihe' => 'the' but do not touch 'light'.
// 4) Use \B to match characters inside borders of an entity.
fixedMultiline = buggyMultiline.replace(/\Bo/gim, "e");
console.log(4, fixedMultiline); // fix 'greon' => 'green' but do not touch 'on'.
```
### Matching the beginning of input using a ^ control character
Use `^` for matching at the beginning of input. In this example, we can get the fruits that start with 'A' by a `/^A/` regex. For selecting appropriate fruits we can use the [filter](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method with an [arrow](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) function.
```js
const fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];
// Select fruits started with 'A' by /^A/ Regex.
// Here '^' control symbol used only in one role: Matching beginning of an input.
const fruitsStartsWithA = fruits.filter((fruit) => /^A/.test(fruit));
console.log(fruitsStartsWithA); // [ 'Apple', 'Avocado' ]
```
In the second example `^` is used both for matching at the beginning of input and for creating negated or complemented character class when used within [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes).
```js
const fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];
// Selecting fruits that do not start by 'A' with a /^[^A]/ regex.
// In this example, two meanings of '^' control symbol are represented:
// 1) Matching beginning of the input
// 2) A negated or complemented character class: [^A]
// That is, it matches anything that is not enclosed in the square brackets.
const fruitsStartsWithNotA = fruits.filter((fruit) => /^[^A]/.test(fruit));
console.log(fruitsStartsWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ]
```
### Matching a word boundary
```js
const fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"];
// Select descriptions that contains 'en' or 'ed' words endings:
const enEdSelection = fruitsWithDescription.filter((descr) =>
/(en|ed)\b/.test(descr),
);
console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]
```
### Lookahead assertion
```js
// JS Lookahead assertion x(?=y)
const regex = /First(?= test)/g;
console.log("First test".match(regex)); // [ 'First' ]
console.log("First peach".match(regex)); // null
console.log("This is a First test in a year.".match(regex)); // [ 'First' ]
console.log("This is a First peach in a month.".match(regex)); // null
```
### Basic negative lookahead assertion
For example, `/\d+(?!\.)/` matches a number only if it is not followed by a decimal point. `/\d+(?!\.)/.exec('3.141')` matches "141" but not "3.
```js
console.log(/\d+(?!\.)/g.exec("3.141")); // [ '141', index: 2, input: '3.141' ]
```
### Different meaning of '?!' combination usage in assertions and character classes
The `?!` combination has different meanings in assertions like `/x(?!y)/` and [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) like `[^?!]`.
```js
const orangeNotLemon =
"Do you want to have an orange? Yes, I do not want to have a lemon!";
// Different meaning of '?!' combination usage in Assertions /x(?!y)/ and Ranges /[^?!]/
const selectNotLemonRegex = /[^?!]+have(?! a lemon)[^?!]+[?!]/gi;
console.log(orangeNotLemon.match(selectNotLemonRegex)); // [ 'Do you want to have an orange?' ]
const selectNotOrangeRegex = /[^?!]+have(?! an orange)[^?!]+[?!]/gi;
console.log(orangeNotLemon.match(selectNotOrangeRegex)); // [ ' Yes, I do not want to have a lemon!' ]
```
### Lookbehind assertion
```js
const oranges = ["ripe orange A", "green orange B", "ripe orange C"];
const ripeOranges = oranges.filter((fruit) => /(?<=ripe )orange/.test(fruit));
console.log(ripeOranges); // [ 'ripe orange A', 'ripe orange C' ]
```
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
| 0 |
data/mdn-content/files/en-us/web/javascript/guide/regular_expressions | data/mdn-content/files/en-us/web/javascript/guide/regular_expressions/quantifiers/index.md | ---
title: Quantifiers
slug: Web/JavaScript/Guide/Regular_expressions/Quantifiers
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}
Quantifiers indicate numbers of characters or expressions to match.
{{EmbedInteractiveExample("pages/js/regexp-quantifiers.html", "taller")}}
## Types
> **Note:** In the following, _item_ refers not only to singular characters, but also includes [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) and [groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences).
<table class="standard-table">
<thead>
<tr>
<th scope="col">Characters</th>
<th scope="col">Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><em>x</em>*</code>
</td>
<td>
<p>
Matches the preceding item "x" 0 or more times. For example,
<code>/bo*/</code> matches "boooo" in "A ghost booooed" and "b" in "A
bird warbled", but nothing in "A goat grunted".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>+</code>
</td>
<td>
<p>
Matches the preceding item "x" 1 or more times. Equivalent to
<code>{1,}</code>. For example, <code>/a+/</code> matches the "a" in
"candy" and all the "a"'s in "caaaaaaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>?</code>
</td>
<td>
<p>
Matches the preceding item "x" 0 or 1 times. For example,
<code>/e?le?/</code> matches the "el" in "angel" and the "le" in
"angle."
</p>
<p>
If used immediately after any of the quantifiers <code>*</code>,
<code>+</code>, <code>?</code>, or <code>{}</code>, makes the
quantifier non-greedy (matching the minimum number of times), as
opposed to the default, which is greedy (matching the maximum number
of times).
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>}</code>
</td>
<td>
<p>
Where "n" is a positive integer, matches exactly "n" occurrences of
the preceding item "x". For example, <code>/a{2}/</code> doesn't match
the "a" in "candy", but it matches all of the "a"'s in "caandy", and
the first two "a"'s in "caaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>,}</code>
</td>
<td>
<p>
Where "n" is a positive integer, matches at least "n" occurrences of
the preceding item "x". For example, <code>/a{2,}/</code> doesn't
match the "a" in "candy", but matches all of the a's in "caandy" and
in "caaaaaaandy".
</p>
</td>
</tr>
<tr>
<td>
<code><em>x</em>{<em>n</em>,<em>m</em>}</code>
</td>
<td>
<p>
Where "n" is 0 or a positive integer, "m" is a positive integer, and
<code><em>m</em> > <em>n</em></code
>, matches at least "n" and at most "m" occurrences of the preceding
item "x". For example, <code>/a{1,3}/</code> matches nothing in
"cndy", the "a" in "candy", the two "a"'s in "caandy", and the first
three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy",
the match is "aaa", even though the original string had more "a"s in
it.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code><em>x</em>*?</code><br /><code><em>x</em>+?</code><br /><code
><em>x</em>??</code
><br /><code><em>x</em>{n}?</code><br /><code><em>x</em>{n,}?</code
><br /><code><em>x</em>{n,m}?</code>
</p>
</td>
<td>
<p>
By default quantifiers like <code>*</code> and <code>+</code> are
"greedy", meaning that they try to match as much of the string as
possible. The <code>?</code> character after the quantifier makes the
quantifier "non-greedy": meaning that it will stop as soon as it finds
a match. For example, given a string like "some <foo> <bar>
new </bar> </foo> thing":
</p>
<ul>
<li>
<code>/<.*>/</code> will match "<foo> <bar> new
</bar> </foo>"
</li>
<li><code>/<.*?>/</code> will match "<foo>"</li>
</ul>
</td>
</tr>
</tbody>
</table>
## Examples
### Repeated pattern
```js
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";
console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
```
### Counting characters
```js
const singleLetterWord = /\b\w\b/g;
const notSoLongWord = /\b\w{2,6}\b/g;
const longWord = /\b\w{13,}\b/g;
const sentence = "Why do I have to learn multiplication table?";
console.table(sentence.match(singleLetterWord)); // ["I"]
console.table(sentence.match(notSoLongWord)); // [ "Why", "do", "have", "to", "learn", "table" ]
console.table(sentence.match(longWord)); // ["multiplication"]
```
### Optional character
```js
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";
const regexpEnding = /\w+ou?r/g;
// \w+ One or several letters
// o followed by an "o",
// u? optionally followed by a "u"
// r followed by an "r"
console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]
console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
```
### Greedy versus non-greedy
```js
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\w ]+/;
// [\w ] a letter of the latin alphabet or a whitespace
// + one or several times
console.log(text.match(greedyRegexp)[0]);
// "I must be getting somewhere near the center of the earth"
// almost all of the text matches (leaves out the dot character)
const nonGreedyRegexp = /[\w ]+?/; // Notice the question mark
console.log(text.match(nonGreedyRegexp));
// "I"
// The match is the smallest one possible
```
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/functions/index.md | ---
title: Functions
slug: Web/JavaScript/Guide/Functions
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}
Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedureβa set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.
See also the [exhaustive reference chapter about JavaScript functions](/en-US/docs/Web/JavaScript/Reference/Functions) to get to know the details.
## Defining functions
### Function declarations
A **function definition** (also called a **function declaration**, or **function statement**) consists of the [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function) keyword, followed by:
- The name of the function.
- A list of parameters to the function, enclosed in parentheses and separated by commas.
- The JavaScript statements that define the function, enclosed in curly braces, `{ /* β¦ */ }`.
For example, the following code defines a simple function named `square`:
```js
function square(number) {
return number * number;
}
```
The function `square` takes one parameter, called `number`. The function consists of one statement that says to return the parameter of the function (that is, `number`) multiplied by itself. The [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement specifies the value returned by the function, which is `number * number`.
Parameters are essentially passed to functions **by value** β so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, **the change is not reflected globally or in the code which called that function**.
When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:
```js
function myFunc(theObject) {
theObject.make = "Toyota";
}
const mycar = {
make: "Honda",
model: "Accord",
year: 1998,
};
console.log(mycar.make); // "Honda"
myFunc(mycar);
console.log(mycar.make); // "Toyota"
```
When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:
```js
function myFunc(theArr) {
theArr[0] = 30;
}
const arr = [45];
console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
```
### Function expressions
While the function declaration above is syntactically a statement, functions can also be created by a [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function).
Such a function can be **anonymous**; it does not have to have a name. For example, the function `square` could have been defined as:
```js
const square = function (number) {
return number * number;
};
console.log(square(4)); // 16
```
However, a name _can_ be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:
```js
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3)); // 6
```
Function expressions are convenient when passing a function as an argument to another function. The following example shows a `map` function that should receive a function as first argument and an array as second argument:
```js
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
```
In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:
```js
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
const cube = function (x) {
return x * x * x;
};
const numbers = [0, 1, 2, 5, 10];
console.log(map(cube, numbers)); // [0, 1, 8, 125, 1000]
```
In JavaScript, a function can be defined based on a condition. For example, the following function definition defines `myFunc` only if `num` equals `0`:
```js
let myFunc;
if (num === 0) {
myFunc = function (theObject) {
theObject.make = "Toyota";
};
}
```
In addition to defining functions as described here, you can also use the {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("Global_Objects/eval", "eval()")}}.
A **method** is a function that is a property of an object. Read more about objects and methods in [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects).
## Calling functions
_Defining_ a function does not _execute_ it. Defining it names the function and specifies what to do when the function is called.
**Calling** the function actually performs the specified actions with the indicated parameters. For example, if you define the function `square`, you could call it as follows:
```js
square(5);
```
The preceding statement calls the function with an argument of `5`. The function executes its statements and returns the value `25`.
Functions must be _in scope_ when they are called, but the function declaration can be [hoisted](#function_hoisting) (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The `showProps()` function (defined in [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#objects_and_properties)) is an example of a function that takes an object as an argument.
A function can call itself. For example, here is a function that computes factorials recursively:
```js
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
```
You could then compute the factorials of `1` through `5` as follows:
```js
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120
```
There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.
It turns out that _functions are themselves objects_ β and in turn, these objects have methods. (See the {{jsxref("Function")}} object.) The [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [`apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) methods can be used to achieve this goal.
### Function hoisting
Consider the example below:
```js
console.log(square(5)); // 25
function square(n) {
return n * n;
}
```
This code runs without any error, despite the `square()` function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:
```js
// All function declarations are effectively at the top of the scope
function square(n) {
return n * n;
}
console.log(square(5)); // 25
```
Function hoisting only works with function _declarations_ β not with function _expressions_. The following code will not work:
```js example-bad
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
return n * n;
};
```
## Function scope
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. 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. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access.
```js
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";
// This function is defined in the global scope
function multiply() {
return num1 * num2;
}
console.log(multiply()); // 60
// A nested function example
function getScore() {
const num1 = 2;
const num2 = 3;
function add() {
return `${name} scored ${num1 + num2}`;
}
return add();
}
console.log(getScore()); // "Chamakh scored 5"
```
## Scope and the function stack
### Recursion
A function can refer to and call itself. There are three ways for a function to refer to itself:
1. The function's name
2. [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)
3. An in-scope variable that refers to the function
For example, consider the following function definition:
```js
const foo = function bar() {
// statements go here
};
```
Within the function body, the following are all equivalent:
1. `bar()`
2. `arguments.callee()`
3. `foo()`
A function that calls itself is called a _recursive function_. 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).
For example, consider the following loop:
```js
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
// do stuff
x++;
}
```
It can be converted into a recursive function declaration, followed by a call to that function:
```js
function loop(x) {
// "x >= 10" is the exit condition (equivalent to "!(x < 10)")
if (x >= 10) {
return;
}
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
```
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the [DOM](/en-US/docs/Web/API/Document_Object_Model)) is easier via recursion:
```js
function walkTree(node) {
if (node === null) {
return;
}
// do something with node
for (let i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}
```
Compared to the function `loop`, each recursive call itself makes many recursive calls here.
It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.
In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:
```js
function foo(i) {
if (i < 0) {
return;
}
console.log(`begin: ${i}`);
foo(i - 1);
console.log(`end: ${i}`);
}
foo(3);
// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3
```
### Nested functions and closures
You may nest a function within another function. The nested (inner) function is private to its containing (outer) function.
It also forms a _closure_. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
To summarize:
- The inner function can be accessed only from statements in the outer function.
- The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
The following example shows nested functions:
```js
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
console.log(addSquares(2, 3)); // 13
console.log(addSquares(3, 4)); // 25
console.log(addSquares(4, 5)); // 41
```
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
```js
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
console.log(fnInside(5)); // 8
console.log(outside(3)(5)); // 8
```
### Preservation of variables
Notice how `x` is preserved when `inside` is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to `outside`. The memory can be freed only when the returned `inside` is no longer accessible.
This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.
### Multiply-nested functions
Functions can be multiply-nested. For example:
- A function (`A`) contains a function (`B`), which itself contains a function (`C`).
- Both functions `B` and `C` form closures here. So, `B` can access `A`, and `C` can access `B`.
- In addition, since `C` can access `B` which can access `A`, `C` can also access `A`.
Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called _scope chaining_. (The reason it is called "chaining" is explained later.)
Consider the following example:
```js
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)
```
In this example, `C` accesses `B`'s `y` and `A`'s `x`.
This can be done because:
1. `B` forms a closure including `A` (i.e., `B` can access `A`'s arguments and variables).
2. `C` forms a closure including `B`.
3. Because `C`'s closure includes `B` and `B`'s closure includes `A`, then `C`'s closure also includes `A`. This means `C` can access _both_ `B` _and_ `A`'s arguments and variables. In other words, `C` _chains_ the scopes of `B` and `A`, _in that order_.
The reverse, however, is not true. `A` cannot access `C`, because `A` cannot access any argument or variable of `B`, which `C` is a variable of. Thus, `C` remains private to only `B`.
### Name conflicts
When two arguments or variables in the scopes of a closure have the same name, there is a _name conflict_. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:
```js
function outside() {
const x = 5;
function inside(x) {
return x * 2;
}
return inside;
}
console.log(outside()(10)); // 20 (instead of 10)
```
The name conflict happens at the statement `return x * 2` and is between `inside`'s parameter `x` and `outside`'s variable `x`. The scope chain here is {`inside`, `outside`, global object}. Therefore, `inside`'s `x` takes precedences over `outside`'s `x`, and `20` (`inside`'s `x`) is returned instead of `10` (`outside`'s `x`).
## Closures
Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).
However, the outer function does _not_ have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function.
Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.
```js
// The outer function defines a variable called "name"
const pet = function (name) {
const getName = function () {
// The inner function has access to the "name" variable of the outer function
return name;
};
return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");
console.log(myPet()); // "Vivie"
```
It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.
```js
const createPet = function (name) {
let sex;
const pet = {
// setName(newName) is equivalent to setName: function (newName)
// in this context
setName(newName) {
name = newName;
},
getName() {
return name;
},
getSex() {
return sex;
},
setSex(newSex) {
if (
typeof newSex === "string" &&
(newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
) {
sex = newSex;
}
},
};
return pet;
};
const pet = createPet("Vivie");
console.log(pet.getName()); // Vivie
pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver
```
In the code above, the `name` variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.
```js
const getCode = (function () {
const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modifyβ¦
return function () {
return apiCode;
};
})();
console.log(getCode()); // "0]Eal(eh&2"
```
> **Note:** There are a number of pitfalls to watch out for when using closures!
>
> If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a [name conflict](#name_conflicts).)
>
> ```js example-bad
> const createPet = function (name) {
> // The outer function defines a variable called "name".
> return {
> setName(name) {
> // The enclosed function also defines a variable called "name".
> name = name; // How do we access the "name" defined by the outer function?
> },
> };
> };
> ```
## Using the arguments object
The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:
```js
arguments[i];
```
where `i` is the ordinal number of the argument, starting at `0`. So, the first argument passed to a function would be `arguments[0]`. The total number of arguments is indicated by `arguments.length`.
Using the `arguments` object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use `arguments.length` to determine the number of arguments actually passed to the function, and then access each argument using the `arguments` object.
For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
```js
function myConcat(separator) {
let result = ""; // initialize list
// iterate through arguments
for (let i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
```
You can pass any number of arguments to this function, and it concatenates each argument into a string "list":
```js
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "
console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));
// "elephant; giraffe; lion; cheetah; "
console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
// "sage. basil. oregano. pepper. parsley. "
```
> **Note:** The `arguments` variable is "array-like", but not an array. It is array-like in that it has a numbered index and a `length` property. However, it does _not_ possess all of the array-manipulation methods.
See the {{jsxref("Function")}} object in the JavaScript reference for more information.
## Function parameters
There are two special kinds of parameter syntax: _default parameters_ and _rest parameters_.
### Default parameters
In JavaScript, parameters of functions default to `undefined`. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.
In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are `undefined`.
In the following example, if no value is provided for `b`, its value would be `undefined` when evaluating `a*b`, and a call to `multiply` would normally have returned `NaN`. However, this is prevented by the second line in this example:
```js
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
console.log(multiply(5)); // 5
```
With _default parameters_, a manual check in the function body is no longer necessary. You can put `1` as the default value for `b` in the function head:
```js
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // 5
```
For more details, see [default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) in the reference.
### Rest parameters
The [rest parameter](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) syntax allows us to represent an indefinite number of arguments as an array.
In the following example, the function `multiply` uses _rest parameters_ to collect arguments from the second one to the end. The function then multiplies these by the first argument.
```js
function multiply(multiplier, ...theArgs) {
return theArgs.map((x) => multiplier * x);
}
const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
```
## Arrow functions
An [arrow function expression](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) (also called a _fat arrow_ to distinguish from a hypothetical `->` syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments), [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super), or [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target). Arrow functions are always anonymous.
Two factors influenced the introduction of arrow functions: _shorter functions_ and _non-binding_ of `this`.
### Shorter functions
In some functional patterns, shorter functions are welcome. Compare:
```js
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = a.map(function (s) {
return s.length;
});
console.log(a2); // [8, 6, 7, 9]
const a3 = a.map((s) => s.length);
console.log(a3); // [8, 6, 7, 9]
```
### No separate this
Until arrow functions, every new function defined its own [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value (a new object in the case of a constructor, undefined in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.
```js
function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0;
setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
const p = new Person();
```
In ECMAScript 3/5, this issue was fixed by assigning the value in `this` to a variable that could be closed over.
```js
function Person() {
// Some choose `that` instead of `self`.
// Choose one and be consistent.
const self = this;
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
```
Alternatively, a [bound function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) could be created so that the proper `this` value would be passed to the `growUp()` function.
An arrow function does not have its own `this`; the `this` value of the enclosing execution context is used. Thus, in the following code, the `this` within the function that is passed to `setInterval` has the same value as `this` in the enclosing function:
```js
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // `this` properly refers to the person object
}, 1000);
}
const p = new Person();
```
{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/numbers_and_dates/index.md | ---
title: Numbers and dates
slug: Web/JavaScript/Guide/Numbers_and_dates
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Text_formatting")}}
This chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in JavaScript. This includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global {{jsxref("Math")}} object to perform a wide variety of mathematical operations on numbers.
## Numbers
In JavaScript, numbers are implemented in [double-precision 64-bit binary format IEEE 754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) (i.e., a number between Β±2^β1022 and Β±2^+1023, or about Β±10^β308 to Β±10^+308, with a numeric precision of 53 bits). Integer values up to Β±2^53 β 1 can be represented exactly.
In addition to being able to represent floating-point numbers, the number type has three symbolic values: `+`{{jsxref("Infinity")}}, `-`{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (not-a-number).
See also [JavaScript data types and structures](/en-US/docs/Web/JavaScript/Data_structures) for context with other primitive types in JavaScript.
You can use four types of number literals: decimal, binary, octal, and hexadecimal.
### Decimal numbers
```js-nolint
1234567890
42
```
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](/en-US/docs/Web/JavaScript/Reference/Strict_mode#legacy_octal_literals) β so, use the `0o` prefix instead.
```js-nolint example-bad
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal
```
### Binary numbers
Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (`0b` or `0B`). If the digits after the `0b` are not 0 or 1, the following {{jsxref("SyntaxError")}} is thrown: "Missing binary digits after 0b".
```js-nolint
0b10000000000000000000000000000000 // 2147483648
0b01111111100000000000000000000000 // 2139095040
0B00000000011111111111111111111111 // 8388607
```
### Octal numbers
The standard syntax for octal numbers is to prefix them with `0o`. For example:
```js-nolint
0O755 // 493
0o644 // 420
```
There's also a legacy syntax for octal numbers β by prefixing the octal number with a zero: `0644 === 420` and `"\045" === "%"`. If the digits after the `0` are outside the range 0 through 7, the number will be interpreted as a decimal number.
```js
const n = 0755; // 493
const m = 0644; // 420
```
[Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) forbids this octal syntax.
### Hexadecimal numbers
Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (`0x` or `0X`). If the digits after 0x are outside the range (0123456789ABCDEF), the following {{jsxref("SyntaxError")}} is thrown: "Identifier starts immediately after numeric literal".
```js-nolint
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF // 81985529216486900
0XA // 10
```
### Exponentiation
```js-nolint
0e-5 // 0
0e+5 // 0
5e1 // 50
175e-2 // 1.75
1e3 // 1000
1e-3 // 0.001
1E3 // 1000
```
## Number object
The built-in {{jsxref("Number")}} object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:
```js
const biggestNum = Number.MAX_VALUE;
const smallestNum = Number.MIN_VALUE;
const infiniteNum = Number.POSITIVE_INFINITY;
const negInfiniteNum = Number.NEGATIVE_INFINITY;
const notANum = Number.NaN;
```
You always refer to a property of the predefined `Number` object as shown above, and not as a property of a `Number` object you create yourself.
The following table summarizes the `Number` object's properties.
| Property | Description |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| {{jsxref("Number.MAX_VALUE")}} | The largest positive representable number (`1.7976931348623157e+308`) |
| {{jsxref("Number.MIN_VALUE")}} | The smallest positive representable number (`5e-324`) |
| {{jsxref("Number.NaN")}} | Special "not a number" value |
| {{jsxref("Number.NEGATIVE_INFINITY")}} | Special negative infinite value; returned on overflow |
| {{jsxref("Number.POSITIVE_INFINITY")}} | Special positive infinite value; returned on overflow |
| {{jsxref("Number.EPSILON")}} | Difference between `1` and the smallest value greater than `1` that can be represented as a {{jsxref("Number")}} (`2.220446049250313e-16`) |
| {{jsxref("Number.MIN_SAFE_INTEGER")}} | Minimum safe integer in JavaScript (β2^53 + 1, or `β9007199254740991`) |
| {{jsxref("Number.MAX_SAFE_INTEGER")}} | Maximum safe integer in JavaScript (+2^53 β 1, or `+9007199254740991`) |
| Method | Description |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| {{jsxref("Number.parseFloat()")}} | Parses a string argument and returns a floating point number. Same as the global {{jsxref("parseFloat()")}} function. |
| {{jsxref("Number.parseInt()")}} | Parses a string argument and returns an integer of the specified radix or base. Same as the global {{jsxref("parseInt()")}} function. |
| {{jsxref("Number.isFinite()")}} | Determines whether the passed value is a finite number. |
| {{jsxref("Number.isInteger()")}} | Determines whether the passed value is an integer. |
| {{jsxref("Number.isNaN()")}} | Determines whether the passed value is {{jsxref("NaN")}}. More robust version of the original global {{jsxref("isNaN()")}}. |
| {{jsxref("Number.isSafeInteger()")}} | Determines whether the provided value is a number that is a _safe integer_. |
The `Number` prototype provides methods for retrieving information from `Number` objects in various formats. The following table summarizes the methods of `Number.prototype`.
| Method | Description |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| {{jsxref("Number/toExponential", "toExponential()")}} | Returns a string representing the number in exponential notation. |
| {{jsxref("Number/toFixed", "toFixed()")}} | Returns a string representing the number in fixed-point notation. |
| {{jsxref("Number/toPrecision", "toPrecision()")}} | Returns a string representing the number to a specified precision in fixed-point notation. |
## Math object
The built-in {{jsxref("Math")}} object has properties and methods for mathematical constants and functions. For example, the `Math` object's `PI` property has the value of pi (3.141β¦), which you would use in an application as
```js
Math.PI;
```
Similarly, standard mathematical functions are methods of `Math`. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
```js
Math.sin(1.56);
```
Note that all trigonometric methods of `Math` take arguments in radians.
The following table summarizes the `Math` object's methods.
<table class="standard-table">
<caption>
Methods of
<code>Math</code>
</caption>
<thead>
<tr>
<th scope="col">Method</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{jsxref("Math.abs", "abs()")}}</td>
<td>Absolute value</td>
</tr>
<tr>
<td>
{{jsxref("Math.sin", "sin()")}},
{{jsxref("Math.cos", "cos()")}},
{{jsxref("Math.tan", "tan()")}}
</td>
<td>Standard trigonometric functions; with the argument in radians.</td>
</tr>
<tr>
<td>
{{jsxref("Math.asin", "asin()")}},
{{jsxref("Math.acos", "acos()")}},
{{jsxref("Math.atan", "atan()")}},
{{jsxref("Math.atan2", "atan2()")}}
</td>
<td>Inverse trigonometric functions; return values in radians.</td>
</tr>
<tr>
<td>
{{jsxref("Math.sinh", "sinh()")}},
{{jsxref("Math.cosh", "cosh()")}},
{{jsxref("Math.tanh", "tanh()")}}
</td>
<td>Hyperbolic functions; argument in hyperbolic angle.</td>
</tr>
<tr>
<td>
{{jsxref("Math.asinh", "asinh()")}},
{{jsxref("Math.acosh", "acosh()")}},
{{jsxref("Math.atanh", "atanh()")}}
</td>
<td>Inverse hyperbolic functions; return values in hyperbolic angle.</td>
</tr>
<tr>
<td>
<p>
{{jsxref("Math.pow", "pow()")}},
{{jsxref("Math.exp", "exp()")}},
{{jsxref("Math.expm1", "expm1()")}},
{{jsxref("Math.log", "log()")}},
{{jsxref("Math.log10", "log10()")}},
{{jsxref("Math.log1p", "log1p()")}},
{{jsxref("Math.log2", "log2()")}}
</p>
</td>
<td>Exponential and logarithmic functions.</td>
</tr>
<tr>
<td>
{{jsxref("Math.floor", "floor()")}},
{{jsxref("Math.ceil", "ceil()")}}
</td>
<td>
Returns the largest/smallest integer less/greater than or equal to an
argument.
</td>
</tr>
<tr>
<td>
{{jsxref("Math.min", "min()")}},
{{jsxref("Math.max", "max()")}}
</td>
<td>
Returns the minimum or maximum (respectively) value of a comma separated
list of numbers as arguments.
</td>
</tr>
<tr>
<td>{{jsxref("Math.random", "random()")}}</td>
<td>Returns a random number between 0 and 1.</td>
</tr>
<tr>
<td>
{{jsxref("Math.round", "round()")}},
{{jsxref("Math.fround", "fround()")}},
{{jsxref("Math.trunc", "trunc()")}},
</td>
<td>Rounding and truncation functions.</td>
</tr>
<tr>
<td>
{{jsxref("Math.sqrt", "sqrt()")}},
{{jsxref("Math.cbrt", "cbrt()")}},
{{jsxref("Math.hypot", "hypot()")}}
</td>
<td>
Square root, cube root, Square root of the sum of square arguments.
</td>
</tr>
<tr>
<td>{{jsxref("Math.sign", "sign()")}}</td>
<td>
The sign of a number, indicating whether the number is positive,
negative or zero.
</td>
</tr>
<tr>
<td>
{{jsxref("Math.clz32", "clz32()")}},<br />{{jsxref("Math.imul", "imul()")}}
</td>
<td>
Number of leading zero bits in the 32-bit binary representation.<br />The
result of the C-like 32-bit multiplication of the two arguments.
</td>
</tr>
</tbody>
</table>
Unlike many other objects, you never create a `Math` object of your own. You always use the built-in `Math` object.
## BigInts
One shortcoming of number values is they only have 64 bits. In practice, due to using IEEE 754 encoding, they cannot represent any integer larger than [`Number.MAX_SAFE_INTEGER`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) (which is 2<sup>53</sup> - 1) accurately. To solve the need of encoding binary data and to interoperate with other languages that offer wide integers like `i64` (64-bit integers) and `i128` (128-bit integers), JavaScript also offers another data type to represent _arbitrarily large integers_: [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt).
A BigInt can be defined as an integer literal suffixed by `n`:
```js
const b1 = 123n;
// Can be arbitrarily large.
const b2 = -1234567890987654321n;
```
BigInts can also be constructed from number values or string values using the [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) constructor.
```js
const b1 = BigInt(123);
// Using a string prevents loss of precision, since long number
// literals don't represent what they seem like.
const b2 = BigInt("-1234567890987654321");
```
Conceptually, a BigInt is just an arbitrarily long sequence of bits which encodes an integer. You can safely do any arithmetic operations without losing precision or over-/underflowing.
```js
const integer = 12 ** 34; // 4.9222352429520264e+36; only has limited precision
const bigint = 12n ** 34n; // 4922235242952026704037113243122008064n
```
Compared to numbers, BigInt values yield higher precision when representing large _integers_; however, they cannot represent _floating-point numbers_. For example, division would round to zero:
```js
const bigintDiv = 5n / 2n; // 2n, because there's no 2.5 in BigInt
```
`Math` functions cannot be used on BigInt values. There is [an open proposal](https://github.com/tc39/proposal-bigint-math) to overload certain `Math` functions like `Math.max()` to allow BigInt values.
Choosing between BigInt and number depends on your use-case and your input's range. The precision of numbers should be able to accommodate most day-to-day tasks already, and BigInts are most suitable for handling binary data.
Read more about what you can do with BigInt values in the [Expressions and Operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bigint_operators) section, or the [BigInt reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt).
## Date object
JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The `Date` object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
The `Date` object range is -100,000,000 days to 100,000,000 days relative to the epoch.
To create a `Date` object:
```js
const dateObjectName = new Date([parameters]);
```
where `dateObjectName` is the name of the `Date` object being created; it can be a new object or a property of an existing object.
Calling `Date` without the `new` keyword returns a string representing the current date and time.
The `parameters` in the preceding syntax can be any of the following:
- Nothing: creates today's date and time. For example, `today = new Date();`.
- A string representing a date, in many different forms. The exact forms supported differ among engines, but the following form is always supported: `YYYY-MM-DDTHH:mm:ss.sssZ`. For example, `xmas95 = new Date("1995-12-25")`. If you omit hours, minutes, or seconds, the value will be set to zero.
- A set of integer values for year, month, and day. For example, `xmas95 = new Date(1995, 11, 25)`.
- A set of integer values for year, month, day, hour, minute, and seconds. For example, `xmas95 = new Date(1995, 11, 25, 9, 30, 0);`.
### Methods of the Date object
The `Date` object methods for handling dates and times fall into these broad categories:
- "set" methods, for setting date and time values in `Date` objects.
- "get" methods, for getting date and time values from `Date` objects.
- "to" methods, for returning string values from `Date` objects.
- parse and UTC methods, for parsing `Date` strings.
With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a `getDay` method that returns the day of the week, but no corresponding `setDay` method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
- Seconds and minutes: 0 to 59
- Hours: 0 to 23
- Day: 0 (Sunday) to 6 (Saturday)
- Date: 1 to 31 (day of the month)
- Months: 0 (January) to 11 (December)
- Year: years since 1900
For example, suppose you define the following date:
```js
const xmas95 = new Date("1995-12-25");
```
Then `xmas95.getMonth()` returns 11, and `xmas95.getFullYear()` returns 1995.
The `getTime` and `setTime` methods are useful for comparing dates. The `getTime` method returns the number of milliseconds since the epoch for a `Date` object.
For example, the following code displays the number of days left in the current year:
```js
const today = new Date();
const endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
const msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
let daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
daysLeft = Math.round(daysLeft); // Returns days left in the year
```
This example creates a `Date` object named `today` that contains today's date. It then creates a `Date` object named `endYear` and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between `today` and `endYear`, using `getTime` and rounding to a whole number of days.
The `parse` method is useful for assigning values from date strings to existing `Date` objects. For example, the following code uses `parse` and `setTime` to assign a date value to the `ipoDate` object:
```js
const ipoDate = new Date();
ipoDate.setTime(Date.parse("Aug 9, 1995"));
```
### Example
In the following example, the function `JSClock()` returns the time in the format of a digital clock.
```js
function JSClock() {
const time = new Date();
const hour = time.getHours();
const minute = time.getMinutes();
const second = time.getSeconds();
let temp = String(hour % 12);
if (temp === "0") {
temp = "12";
}
temp += (minute < 10 ? ":0" : ":") + minute;
temp += (second < 10 ? ":0" : ":") + second;
temp += hour >= 12 ? " P.M." : " A.M.";
return temp;
}
```
The `JSClock` function first creates a new `Date` object called `time`; since no arguments are given, time is created with the current date and time. Then calls to the `getHours`, `getMinutes`, and `getSeconds` methods assign the value of the current hour, minute, and second to `hour`, `minute`, and `second`.
The following statements build a string value based on the time. The first statement creates a variable `temp`. Its value is `hour % 12`, which is `hour` in the 12-hour system. Then, if the hour is `0`, it gets re-assigned to `12`, so that midnights and noons are displayed as `12:00` instead of `0:00`.
The next statement appends a `minute` value to `temp`. If the value of `minute` is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to `temp` in the same way.
Finally, a conditional expression appends "P.M." to `temp` if `hour` is 12 or greater; otherwise, it appends "A.M." to `temp`.
{{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Text_formatting")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/typed_arrays/index.md | ---
title: JavaScript typed arrays
slug: Web/JavaScript/Guide/Typed_arrays
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Iterators_and_generators")}}
JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.
Typed arrays are not intended to replace arrays for any kind of functionality. Instead, they provide developers with a familiar interface for manipulating binary data. This is useful when interacting with platform features, such as audio and video manipulation, access to raw data using [WebSockets](/en-US/docs/Web/API/WebSockets_API), and so forth. Each entry in a JavaScript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers.
Typed array objects share many of the same methods as arrays with similar semantics. However, typed arrays are _not_ to be confused with normal arrays, as calling {{jsxref("Array.isArray()")}} on a typed array returns `false`. Moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop).
To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into _buffers_ and _views_. A buffer is an object representing a chunk of data; it has no format to speak of, and offers no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a [view](#views). A view provides a _context_ β that is, a data type, starting offset, and number of elements.

## Buffers
There are two types of buffers: {{jsxref("ArrayBuffer")}} and {{jsxref("SharedArrayBuffer")}}. Both are low-level representations of a memory span. They have "array" in their names, but they don't have much to do with arrays β you cannot read or write to them directly. Instead, buffers are generic objects that just contain raw data. In order to access the memory represented by a buffer, you need to use a view.
Buffers support the following actions:
- _Allocate_: As soon as a new buffer is created, a new memory span is allocated and initialized to `0`.
- _Copy_: Using the {{jsxref("ArrayBuffer/slice", "slice()")}} method, you can efficiently copy a portion of the memory without creating views to manually copy each byte.
- _Transfer_: Using the {{jsxref("ArrayBuffer/transfer", "transfer()")}} and {{jsxref("ArrayBuffer/transferToFixedLength", "transferToFixedLength()")}} methods, you can transfer ownership of the memory span to a new buffer object. This is useful when transferring data between different execution contexts without copying. After the transfer, the original buffer is no longer usable. A `SharedArrayBuffer` cannot be transferred (as the buffer is already shared by all execution contexts).
- _Resize_: Using the {{jsxref("ArrayBuffer/resize", "resize()")}} method, you can resize the memory span (either claim more memory space, as long as it doesn't pass the pre-set {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} limit, or release some memory space). `SharedArrayBuffer` can only be [grown](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/grow) but not shrunk.
The difference between `ArrayBuffer` and `SharedArrayBuffer` is that the former is always owned by a single execution context at a time. If you pass an `ArrayBuffer` to a different execution context, it is _transferred_ and the original `ArrayBuffer` becomes unusable. This ensures that only one execution context can access the memory at a time. A `SharedArrayBuffer` is not transferred when passed to a different execution context, so it can be accessed by multiple execution contexts at the same time. This may introduce race conditions when multiple threads access the same memory span, so operations such as {{jsxref("Atomics")}} methods become useful.
## Views
There are currently two main kinds of views: typed array views and {{jsxref("DataView")}}. Typed arrays provide [utility methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#instance_methods) that allow you to conveniently transform binary data. `DataView` is more low-level and allows granular control of how data is accessed. The ways to read and write data using the two views are very different.
Both kinds of views cause {{jsxref("ArrayBuffer.isView()")}} to return `true`. They both have the following properties:
- `buffer`
- : The underlying buffer that the view references.
- `byteOffset`
- : The offset, in bytes, of the view from the start of its buffer.
- `byteLength`
- : The length, in bytes, of the view.
Both constructors accept the above three as separate arguments, although typed array constructors accept `length` as the number of elements rather than the number of bytes.
### Typed array views
Typed array views have self-descriptive names and provide views for all the usual numeric types like `Int8`, `Uint32`, `Float64` and so forth. There is one special typed array view, {{jsxref("Uint8ClampedArray")}}, which clamps the values between `0` and `255`. This is useful for [Canvas data processing](/en-US/docs/Web/API/ImageData), for example.
| Type | Value Range | Size in bytes | Web IDL type |
| ------------------------------- | ------------------------------------- | ------------- | --------------------- |
| {{jsxref("Int8Array")}} | -128 to 127 | 1 | `byte` |
| {{jsxref("Uint8Array")}} | 0 to 255 | 1 | `octet` |
| {{jsxref("Uint8ClampedArray")}} | 0 to 255 | 1 | `octet` |
| {{jsxref("Int16Array")}} | -32768 to 32767 | 2 | `short` |
| {{jsxref("Uint16Array")}} | 0 to 65535 | 2 | `unsigned short` |
| {{jsxref("Int32Array")}} | -2147483648 to 2147483647 | 4 | `long` |
| {{jsxref("Uint32Array")}} | 0 to 4294967295 | 4 | `unsigned long` |
| {{jsxref("Float32Array")}} | `-3.4e38` to `3.4e38` | 4 | `unrestricted float` |
| {{jsxref("Float64Array")}} | `-1.8e308` to `1.8e308` | 8 | `unrestricted double` |
| {{jsxref("BigInt64Array")}} | -2<sup>63</sup> to 2<sup>63</sup> - 1 | 8 | `bigint` |
| {{jsxref("BigUint64Array")}} | 0 to 2<sup>64</sup> - 1 | 8 | `bigint` |
All typed array views have the same methods and properties, as defined by the {{jsxref("TypedArray")}} class. They only differ in the underlying data type and the size in bytes. This is discussed in more detail in [Value encoding and normalization](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#value_encoding_and_normalization).
Typed arrays are, in principle, fixed-length, so array methods that may change the length of an array are not available. This includes `pop`, `push`, `shift`, `splice`, and `unshift`. In addition, `flat` is unavailable because there are no nested typed arrays, and related methods including `concat` and `flatMap` do not have great use cases so are unavailable. As `splice` is unavailable, so too is `toSpliced`. All other array methods are shared between `Array` and `TypedArray`.
On the other hand, `TypedArray` has the extra `set` and `subarray` methods that optimize working with multiple typed arrays that view the same buffer. The `set()` method allows setting multiple typed array indices at once, using data from another array or typed array. If the two typed arrays share the same underlying buffer, the operation may be more efficient as it's a fast memory move. The `subarray()` method creates a new typed array view that references the same buffer as the original typed array, but with a narrower span.
There's no way to directly change the length of a typed array without changing the underlying buffer. However, when the typed array views a resizable buffer and does not have a fixed `byteLength`, it is _length-tracking_, and will automatically resize to fit the underlying buffer as the resizable buffer is resized. See [Behavior when viewing a resizable buffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#behavior_when_viewing_a_resizable_buffer) for details.
Similar to regular arrays, you can access typed array elements using [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation). The corresponding bytes in the underlying buffer are retrieved and interpreted as a number. Any property access using a number (or the string representation of a number, since numbers are always converted to strings when accessing properties) will be proxied by the typed array β they never interact with the object itself. This means, for example:
- Out-of-bounds index access always returns `undefined`, without actually accessing the property on the object.
- Any attempt to write to such an out-of-bounds property has no effect: it does not throw an error but doesn't change the buffer or typed array either.
- Typed array indices appear to be configurable and writable, but any attempt to change their attributes will fail.
```js
const uint8 = new Uint8Array([1, 2, 3]);
console.log(uint8[0]); // 1
// For illustrative purposes only. Not for production code.
uint8[-1] = 0;
uint8[2.5] = 0;
uint8[NaN] = 0;
console.log(Object.keys(uint8)); // ["0", "1", "2"]
console.log(uint8[NaN]); // undefined
// Non-numeric access still works
uint8[true] = 0;
console.log(uint8[true]); // 0
Object.freeze(uint8); // TypeError: Cannot freeze array buffer views with elements
```
### DataView
The {{jsxref("DataView")}} is a low-level interface that provides a getter/setter API to read and write arbitrary data to the buffer. This is useful when dealing with different types of data, for example. Typed array views are in the native byte-order (see [Endianness](/en-US/docs/Glossary/Endianness)) of your platform. With a `DataView`, the byte-order can be controlled. By default, it's big-endianβthe bytes are ordered from most significant to least significant. This can be reversed, with the bytes ordered from least significant to most significant (little-endian), using getter/setter methods.
`DataView` does not require alignment; multi-byte read and write can be started at any specified offset. The setter methods work the same way.
The following example uses a `DataView` to get the binary representation of any number:
```js
function toBinary(
x,
{ type = "Float64", littleEndian = false, separator = " ", radix = 16 } = {},
) {
const bytesNeeded = globalThis[`${type}Array`].BYTES_PER_ELEMENT;
const dv = new DataView(new ArrayBuffer(bytesNeeded));
dv[`set${type}`](0, x, littleEndian);
const bytes = Array.from({ length: bytesNeeded }, (_, i) =>
dv
.getUint8(i)
.toString(radix)
.padStart(8 / Math.log2(radix), "0"),
);
return bytes.join(separator);
}
console.log(toBinary(1.1)); // 3f f1 99 99 99 99 99 9a
console.log(toBinary(1.1, { littleEndian: true })); // 9a 99 99 99 99 99 f1 3f
console.log(toBinary(20, { type: "Int8", radix: 2 })); // 00010100
```
## Web APIs using typed arrays
These are some examples of APIs that make use of typed arrays; there are others, and more are being added all the time.
- [`FileReader.prototype.readAsArrayBuffer()`](/en-US/docs/Web/API/FileReader/readAsArrayBuffer)
- : The `FileReader.prototype.readAsArrayBuffer()` method starts reading the contents of the specified [`Blob`](/en-US/docs/Web/API/Blob) or [`File`](/en-US/docs/Web/API/File).
- [`fetch()`](/en-US/docs/Web/API/fetch)
- : The [`body`](/en-US/docs/Web/API/fetch#body) option to `fetch()` can be a typed array or {{jsxref("ArrayBuffer")}}, enabling you to send these objects as the payload of a {{HTTPMethod("POST")}} request.
- [`ImageData.data`](/en-US/docs/Web/API/ImageData)
- : Is a {{jsxref("Uint8ClampedArray")}} representing a one-dimensional array containing the data in the RGBA order, with integer values between `0` and `255` inclusive.
## Examples
### Using views with buffers
First of all, we will need to create a buffer, here with a fixed length of 16-bytes:
```js
const buffer = new ArrayBuffer(16);
```
At this point, we have a chunk of memory whose bytes are all pre-initialized to 0. There's not a lot we can do with it, though. For example, we can confirm that the buffer is the right size:
```js
if (buffer.byteLength === 16) {
console.log("Yes, it's 16 bytes.");
} else {
console.log("Oh no, it's the wrong size!");
}
```
Before we can really work with this buffer, we need to create a view. Let's create a view that treats the data in the buffer as an array of 32-bit signed integers:
```js
const int32View = new Int32Array(buffer);
```
Now we can access the fields in the array just like a normal array:
```js
for (let i = 0; i < int32View.length; i++) {
int32View[i] = i * 2;
}
```
This fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values `0`, `2`, `4`, and `6`.
### Multiple views on the same data
Things start to get really interesting when you consider that you can create multiple views onto the same data. For example, given the code above, we can continue like this:
```js
const int16View = new Int16Array(buffer);
for (let i = 0; i < int16View.length; i++) {
console.log(`Entry ${i}: ${int16View[i]}`);
}
```
Here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers. Now we get the output `0`, `0`, `2`, `0`, `4`, `0`, `6`, `0` (assuming little-endian encoding):
```plain
Int16Array | 0 | 0 | 2 | 0 | 4 | 0 | 6 | 0 |
Int32Array | 0 | 2 | 4 | 6 |
ArrayBuffer | 00 00 00 00 | 02 00 00 00 | 04 00 00 00 | 06 00 00 00 |
```
You can go a step farther, though. Consider this:
```js
int16View[0] = 32;
console.log(`Entry 0 in the 32-bit array is now ${int32View[0]}`);
```
The output from this is `"Entry 0 in the 32-bit array is now 32"`.
In other words, the two arrays are indeed viewed on the same data buffer, treating it as different formats.
```plain
Int16Array | 32 | 0 | 2 | 0 | 4 | 0 | 6 | 0 |
Int32Array | 32 | 2 | 4 | 6 |
ArrayBuffer | 00 02 00 00 | 02 00 00 00 | 04 00 00 00 | 06 00 00 00 |
```
You can do this with any view type, although if you set an integer and then read it as a floating-point number, you will probably get a strange result because the bits are interpreted differently.
```js
const float32View = new Float32Array(buffer);
console.log(float32View[0]); // 4.484155085839415e-44
```
### Reading text from a buffer
Buffers don't always represent numbers. For example, reading a file can give you a text data buffer. You can read this data out of the buffer using a typed array.
The following reads UTF-8 text using the {{domxref("TextDecoder")}} web API:
```js
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
// Data manually written here, but pretend it was already in the buffer
uint8.set([228, 189, 160, 229, 165, 189]);
const text = new TextDecoder().decode(uint8);
console.log(text); // "δ½ ε₯½"
```
The following reads UTF-16 text using the {{jsxref("String.fromCharCode()")}} method:
```js
const buffer = new ArrayBuffer(8);
const uint16 = new Uint16Array(buffer);
// Data manually written here, but pretend it was already in the buffer
uint16.set([0x4f60, 0x597d]);
const text = String.fromCharCode(...uint16);
console.log(text); // "δ½ ε₯½"
```
### Working with complex data structures
By combining a single buffer with multiple views of different types, starting at different offsets into the buffer, you can interact with data objects containing multiple data types. This lets you, for example, interact with complex data structures from [WebGL](/en-US/docs/Web/API/WebGL_API) or data files.
Consider this C structure:
```cpp
struct someStruct {
unsigned long id;
char username[16];
float amountDue;
};
```
You can access a buffer containing data in this format like this:
```js
const buffer = new ArrayBuffer(24);
// ... read the data into the buffer ...
const idView = new Uint32Array(buffer, 0, 1);
const usernameView = new Uint8Array(buffer, 4, 16);
const amountDueView = new Float32Array(buffer, 20, 1);
```
Then you can access, for example, the amount due with `amountDueView[0]`.
> **Note:** The [data structure alignment](https://en.wikipedia.org/wiki/Data_structure_alignment) in a C structure is platform-dependent. Take precautions and considerations for these padding differences.
### Conversion to normal arrays
After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the {{jsxref("Array")}} prototype. This can be done using {{jsxref("Array.from()")}}:
```js
const typedArray = new Uint8Array([1, 2, 3, 4]);
const normalArray = Array.from(typedArray);
```
as well as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):
```js
const typedArray = new Uint8Array([1, 2, 3, 4]);
const normalArray = [...typedArray];
```
## See also
- [Faster Canvas Pixel Manipulation with Typed Arrays](https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/) on hacks.mozilla.org (2011)
- [Typed arrays - Binary data in the browser](https://web.dev/articles/webgl-typed-arrays) on web.dev (2012)
- [Endianness](/en-US/docs/Glossary/Endianness)
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
- {{jsxref("TypedArray")}}
- {{jsxref("SharedArrayBuffer")}}
{{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Iterators_and_generators")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/meta_programming/index.md | ---
title: Meta programming
slug: Web/JavaScript/Guide/Meta_programming
page-type: guide
---
{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Modules")}}
The {{jsxref("Proxy")}} and {{jsxref("Reflect")}} objects allow you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc.). With the help of these two objects you are able to program at the meta level of JavaScript.
## Proxies
{{jsxref("Proxy")}} objects allow you to intercept certain operations and to implement custom behaviors.
For example, getting a property on an object:
```js
const handler = {
get(target, name) {
return name in target ? target[name] : 42;
},
};
const p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 1, 42
```
The `Proxy` object defines a `target` (an empty object here) and a `handler` object, in which a `get` _trap_ is implemented. Here, an object that is proxied will not return `undefined` when getting undefined properties, but will instead return the number `42`.
Additional examples are available on the {{jsxref("Proxy")}} reference page.
### Terminology
The following terms are used when talking about the functionality of proxies.
- {{jsxref("Proxy/Proxy", "handler", "", "true")}}
- : Placeholder object which contains traps.
- traps
- : The methods that provide property access. (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 are called _invariants_. If you violate the invariants of a handler, a {{jsxref("TypeError")}} will be thrown.
## Handlers and traps
The following table summarizes the available traps available to `Proxy` objects. See the [reference pages](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) for detailed explanations and examples.
<table class="standard-table">
<thead>
<tr>
<th>Handler / trap</th>
<th>Interceptions</th>
<th>Invariants</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{{jsxref("Proxy/Proxy/getPrototypeOf", "handler.getPrototypeOf()")}}
</td>
<td>
{{jsxref("Object.getPrototypeOf()")}}<br />{{jsxref("Reflect.getPrototypeOf()")}}<br />{{jsxref("Object/proto", "__proto__")}}<br />{{jsxref("Object.prototype.isPrototypeOf()")}}<br />{{jsxref("Operators/instanceof", "instanceof")}}
</td>
<td>
<ul>
<li>
<code>getPrototypeOf</code> method must return an object or
<code>null</code>.
</li>
<li>
If <code><var>target</var></code> is not extensible,
<code>Object.getPrototypeOf(<var>proxy</var>)</code> method must
return the same value as
<code>Object.getPrototypeOf(<var>target</var>)</code>.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/setPrototypeOf", "handler.setPrototypeOf()")}}
</td>
<td>
{{jsxref("Object.setPrototypeOf()")}}<br />{{jsxref("Reflect.setPrototypeOf()")}}
</td>
<td>
If <code><var>target</var></code> is not extensible, the
<code>prototype</code> parameter must be the same value as
<code>Object.getPrototypeOf(<var>target</var>)</code>.
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/isExtensible", "handler.isExtensible()")}}
</td>
<td>
{{jsxref("Object.isExtensible()")}}<br />{{jsxref("Reflect.isExtensible()")}}
</td>
<td>
<code>Object.isExtensible(<var>proxy</var>)</code> must return the same
value as <code>Object.isExtensible(<var>target</var>)</code>.
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/preventExtensions", "handler.preventExtensions()")}}
</td>
<td>
{{jsxref("Object.preventExtensions()")}}<br />{{jsxref("Reflect.preventExtensions()")}}
</td>
<td>
<code>Object.preventExtensions(<var>proxy</var>)</code> only returns
<code>true</code> if
<code>Object.isExtensible(<var>proxy</var>)</code> is
<code>false</code>.
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
</td>
<td>
{{jsxref("Object.getOwnPropertyDescriptor()")}}<br />{{jsxref("Reflect.getOwnPropertyDescriptor()")}}
</td>
<td>
<ul>
<li>
<code>getOwnPropertyDescriptor</code> must return an object or
<code>undefined</code>.
</li>
<li>
A property cannot be reported as non-existent if it exists as a
non-configurable own property of <code><var>target</var></code
>.
</li>
<li>
A property cannot be reported as non-existent if it exists as an own
property of <code><var>target</var></code> and
<code><var>target</var></code> is not extensible.
</li>
<li>
A property cannot be reported as existent if it does not exists as
an own property of <code><var>target</var></code> and
<code><var>target</var></code> is not extensible.
</li>
<li>
A property cannot be reported as non-configurable if it does not
exist as an own property of <code><var>target</var></code> or if it
exists as a configurable own property of
<code><var>target</var></code
>.
</li>
<li>
The result of
<code>Object.getOwnPropertyDescriptor(<var>target</var>)</code> can
be applied to <code><var>target</var></code> using
<code>Object.defineProperty</code> and will not throw an exception.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/defineProperty", "handler.defineProperty()")}}
</td>
<td>
{{jsxref("Object.defineProperty()")}}<br />{{jsxref("Reflect.defineProperty()")}}
</td>
<td>
<ul>
<li>
A property cannot be added if <code><var>target</var></code
> is not extensible.
</li>
<li>
A property cannot be added as (or modified to be)
non-configurable if it does not exist as a non-configurable own
property of <code><var>target</var></code
>.
</li>
<li>
A property may not be non-configurable if a corresponding
configurable property of <code><var>target</var></code> exists.
</li>
<li>
If a property has a corresponding target object property, then
<code
>Object.defineProperty(<var>target</var>, <var>prop</var>,
<var>descriptor</var>)</code
>
will not throw an exception.
</li>
<li>
In strict mode, a <code>false</code> value returned from the
<code>defineProperty</code> handler will throw a
{{jsxref("TypeError")}} exception.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/has", "handler.has()")}}
</td>
<td>
<dl>
<dt>Property query</dt>
<dd><code>foo in proxy</code></dd>
<dt>Inherited property query</dt>
<dd>
<code>foo in Object.create(<var>proxy</var>)</code
><br />{{jsxref("Reflect.has()")}}
</dd>
</dl>
</td>
<td>
<ul>
<li>
A property cannot be reported as non-existent, if it exists as a
non-configurable own property of <code><var>target</var></code
>.
</li>
<li>
A property cannot be reported as non-existent if it exists as an own
property of <code><var>target</var></code> and
<code><var>target</var></code> is not extensible.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/get", "handler.get()")}}
</td>
<td>
<dl>
<dt>Property access</dt>
<dd>
<code><var>proxy</var>[foo]</code><br /><code
><var>proxy</var>.bar</code
>
</dd>
<dt>Inherited property access</dt>
<dd>
<!-- markdownlint-disable MD011 -->
<code>Object.create(<var>proxy</var>)[foo]</code
><br />{{jsxref("Reflect.get()")}}
</dd>
</dl>
</td>
<td>
<ul>
<li>
The value reported for a property must be the same as the value of
the corresponding <code><var>target</var></code> property if
<code><var>target</var></code
>'s property is a non-writable, non-configurable data property.
</li>
<li>
The value reported for a property must be <code>undefined</code> if
the corresponding <code><var>target</var></code> property is
non-configurable accessor property that has undefined as its
<code>[[Get]]</code> attribute.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/set", "handler.set()")}}
</td>
<td>
<dl>
<dt>Property assignment</dt>
<dd>
<code><var>proxy</var>[foo] = bar</code><br /><code
><var>proxy</var>.foo = bar</code
>
</dd>
<dt>Inherited property assignment</dt>
<dd>
<code>Object.create(<var>proxy</var>)[foo] = bar</code
><br />{{jsxref("Reflect.set()")}}
</dd>
<!-- markdownlint-enable MD011 -->
</dl>
</td>
<td>
<ul>
<li>
Cannot change the value of a property to be different from the value
of the corresponding <code><var>target</var></code> property if the
corresponding <code><var>target</var></code> property is a
non-writable, non-configurable data property.
</li>
<li>
Cannot set the value of a property if the corresponding
<code><var>target</var></code> property is a non-configurable
accessor property that has <code>undefined</code> as its
<code>[[Set]]</code> attribute.
</li>
<li>
In strict mode, a <code>false</code> return value from the
<code>set</code> handler will throw a
{{jsxref("TypeError")}} exception.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/deleteProperty", "handler.deleteProperty()")}}
</td>
<td>
<dl>
<dt>Property deletion</dt>
<dd>
<code>delete <var>proxy</var>[foo]</code><br /><code
>delete <var>proxy</var>.foo</code
><br />{{jsxref("Reflect.deleteProperty()")}}
</dd>
</dl>
</td>
<td>
A property cannot be deleted if it exists as a non-configurable own
property of <code><var>target</var></code
>.
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/ownKeys", "handler.ownKeys()")}}
</td>
<td>
{{jsxref("Object.getOwnPropertyNames()")}}<br />{{jsxref("Object.getOwnPropertySymbols()")}}<br />{{jsxref("Object.keys()")}}<br />{{jsxref("Reflect.ownKeys()")}}
</td>
<td>
<ul>
<li>The result of <code>ownKeys</code> is a List.</li>
<li>
The Type of each result List element is either
{{jsxref("String")}} or {{jsxref("Symbol")}}.
</li>
<li>
The result List must contain the keys of all non-configurable own
properties of <code><var>target</var></code
>.
</li>
<li>
If the <code><var>target</var></code> object is not extensible, then
the result List must contain all the keys of the own properties of
<code><var>target</var></code
> and no other values.
</li>
</ul>
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/apply", "handler.apply()")}}
</td>
<td>
<code>proxy(..args)</code
><br />{{jsxref("Function.prototype.apply()")}} and
{{jsxref("Function.prototype.call()")}}<br />{{jsxref("Reflect.apply()")}}
</td>
<td>
There are no invariants for the
<code><var>handler</var>.apply</code> method.
</td>
</tr>
<tr>
<td>
{{jsxref("Proxy/Proxy/construct", "handler.construct()")}}
</td>
<td>
<code>new proxy(...args)</code
><br />{{jsxref("Reflect.construct()")}}
</td>
<td>The result must be an <code>Object</code>.</td>
</tr>
</tbody>
</table>
## Revocable `Proxy`
The {{jsxref("Proxy.revocable()")}} method is used to create a revocable `Proxy` object. This means that the proxy can be revoked via the function `revoke` and switches the proxy off.
Afterwards, any operation on the proxy leads to a {{jsxref("TypeError")}}.
```js
const revocable = Proxy.revocable(
{},
{
get(target, name) {
return `[[${name}]]`;
},
},
);
const proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"
revocable.revoke();
console.log(proxy.foo); // TypeError: Cannot perform 'get' on a proxy that has been revoked
proxy.foo = 1; // TypeError: Cannot perform 'set' on a proxy that has been revoked
delete proxy.foo; // TypeError: Cannot perform 'deleteProperty' on a proxy that has been revoked
console.log(typeof proxy); // "object", typeof doesn't trigger any trap
```
## Reflection
{{jsxref("Reflect")}} is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the [proxy handler's](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy).
`Reflect` is not a function object.
`Reflect` helps with forwarding default operations from the handler to the `target`.
With {{jsxref("Reflect.has()")}} for example, you get the [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in) as a function:
```js
Reflect.has(Object, "assign"); // true
```
### A better apply() function
Before `Reflect`, you typically use the {{jsxref("Function.prototype.apply()")}} method to call a function with a given `this` value and `arguments` provided as an array (or an [array-like object](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)).
```js
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
```
With {{jsxref("Reflect.apply")}} this becomes less verbose and easier to understand:
```js
Reflect.apply(Math.floor, undefined, [1.75]);
// 1
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4
Reflect.apply("".charAt, "ponies", [3]);
// "i"
```
### Checking if property definition has been successful
With {{jsxref("Object.defineProperty")}}, which returns an object if successful, or throws a {{jsxref("TypeError")}} otherwise, you would use a {{jsxref("Statements/try...catch", "try...catch")}} block to catch any error that occurred while defining a property. Because {{jsxref("Reflect.defineProperty()")}} returns a Boolean success status, you can just use an {{jsxref("Statements/if...else", "if...else")}} block here:
```js
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}
```
{{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Modules")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/grammar_and_types/index.md | ---
title: Grammar and types
slug: Web/JavaScript/Guide/Grammar_and_types
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
This chapter discusses JavaScript's basic grammar, variable declarations, data types and literals.
## Basics
JavaScript borrows most of its syntax from Java, C, and C++, but it has also been influenced by Awk, Perl, and Python.
JavaScript is **case-sensitive** and uses the **Unicode** character set. For example, the word FrΓΌh (which means "early" in German) could be used as a variable name.
```js
const FrΓΌh = "foobar";
```
But, the variable `frΓΌh` is not the same as `FrΓΌh` because JavaScript is case sensitive.
In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by semicolons (;).
A semicolon is not necessary after a statement if it is written on its own line. But if more than one statement on a line is desired, then they _must_ be separated by semicolons.
> **Note:** ECMAScript also has rules for automatic insertion of semicolons ([ASI](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion)) to end statements. (For more information, see the detailed reference about JavaScript's [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar).)
It is considered best practice, however, to always write a semicolon after a statement, even when it is not strictly needed. This practice reduces the chances of bugs getting into the code.
The source text of JavaScript script gets scanned from left to right, and is converted into a sequence of input elements which are _tokens_, _control characters_, _line terminators_, _comments_, or {{Glossary("whitespace")}}. (Spaces, tabs, and newline characters are considered whitespace.)
## Comments
The syntax of **comments** is the same as in C++ and in many other languages:
```js
// a one line comment
/* this is a longer,
* multi-line comment
*/
```
You can't nest block comments. This often happens when you accidentally include a `*/` sequence in your comment, which will terminate the comment.
```js-nolint example-bad
/* You can't, however, /* nest comments */ SyntaxError */
```
In this case, you need to break up the `*/` pattern. For example, by inserting a backslash:
```js
/* You can /* nest comments *\/ by escaping slashes */
```
Comments behave like whitespace, and are discarded during script execution.
> **Note:** You might also see a third type of comment syntax at the start of some JavaScript files, which looks something like this: `#!/usr/bin/env node`.
>
> This is called **hashbang comment** syntax, and is a special comment used to specify the path to a particular JavaScript engine that should execute the script. See [Hashbang comments](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#hashbang_comments) for more details.
## Declarations
JavaScript has three kinds of variable declarations.
- {{jsxref("Statements/var", "var")}}
- : Declares a variable, optionally initializing it to a value.
- {{jsxref("Statements/let", "let")}}
- : Declares a block-scoped, local variable, optionally initializing it to a value.
- {{jsxref("Statements/const", "const")}}
- : Declares a block-scoped, read-only named constant.
### Variables
You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.
A JavaScript identifier usually starts with a letter, underscore (`_`), or dollar sign (`$`). Subsequent characters can also be digits (`0` β `9`). Because JavaScript is case sensitive, letters include the characters `A` through `Z` (uppercase) as well as `a` through `z` (lowercase).
You can use most Unicode letters such as `Γ₯` and `ΓΌ` in identifiers. (For more details, see the [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) reference.) You can also use [Unicode escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#string_literals) to represent characters in identifiers.
Some examples of legal names are `Number_hits`, `temp99`, `$credit`, and `_name`.
### Declaring variables
You can declare a variable in two ways:
- With the keyword {{jsxref("Statements/var", "var")}}. For example, `var x = 42`. This syntax can be used to declare both **local** and **global** variables, depending on the _execution context_.
- With the keyword {{jsxref("Statements/const", "const")}} or {{jsxref("Statements/let", "let")}}. For example, `let y = 13`. This syntax can be used to declare a block-scope local variable. (See [Variable scope](#variable_scope) below.)
You can declare variables to unpack values using the [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax. For example, `const { bar } = foo`. This will create a variable named `bar` and assign to it the value corresponding to the key of the same name from our object `foo`.
Variables should always be declared before they are used. JavaScript used to allow assigning to undeclared variables, which creates an **[undeclared global](/en-US/docs/Web/JavaScript/Reference/Statements/var#description)** variable. This is an error in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#assigning_to_undeclared_variables) and should be avoided altogether.
### Declaration and initialization
In a statement like `let x = 42`, the `let x` part is called a _declaration_, and the `= 42` part is called an _initializer_. The declaration allows the variable to be accessed later in code without throwing a {{jsxref("ReferenceError")}}, while the initializer assigns a value to the variable. In `var` and `let` declarations, the initializer is optional. If a variable is declared without an initializer, it is assigned the value [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).
```js
let x;
console.log(x); // logs "undefined"
```
In essence, `let x = 42` is equivalent to `let x; x = 42`.
`const` declarations always need an initializer, because they forbid any kind of assignment after declaration, and implicitly initializing it with `undefined` is likely a programmer mistake.
```js-nolint example-bad
const x; // SyntaxError: Missing initializer in const declaration
```
### Variable scope
A variable may belong to one of the following [scopes](/en-US/docs/Glossary/Scope):
- Global scope: The default scope for all code running in script mode.
- Module scope: The scope for code running in module mode.
- Function scope: The scope created with a {{Glossary("function")}}.
In addition, variables declared with [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) can belong to an additional scope:
- Block scope: The scope created with a pair of curly braces (a [block](/en-US/docs/Web/JavaScript/Reference/Statements/block)).
When you declare a variable outside of any function, it is called a _global_ variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a _local_ variable, because it is available only within that function.
`let` and `const` declarations can also be scoped to the [block statement](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#block_statement) that they are declared in.
```js
if (Math.random() > 0.5) {
const y = 5;
}
console.log(y); // ReferenceError: y is not defined
```
However, variables created with `var` are not block-scoped, but only local to the _function (or global scope)_ that the block resides within.
For example, the following code will log `5`, because the scope of `x` is the global context (or the function context if the code is part of a function). The scope of `x` is not limited to the immediate `if` statement block.
```js
if (true) {
var x = 5;
}
console.log(x); // x is 5
```
### Variable hoisting
`var`-declared variables are [hoisted](/en-US/docs/Glossary/Hoisting), meaning you can refer to the variable anywhere in its scope, even if its declaration isn't reached yet. You can see `var` declarations as being "lifted" to the top of its function or global scope. However, if you access a variable before it's declared, the value is always `undefined`, because only its _declaration_ is hoisted, but not its _initialization_.
```js
console.log(x === undefined); // true
var x = 3;
(function () {
console.log(x); // undefined
var x = "local value";
})();
```
The above examples will be interpreted the same as:
```js
var x;
console.log(x === undefined); // true
x = 3;
(function () {
var x;
console.log(x); // undefined
x = "local value";
})();
```
Because of hoisting, all `var` statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.
Whether `let` and `const` are hoisted is a matter of definition debate. Referencing the variable in the block before the variable declaration always results in a {{jsxref("ReferenceError")}}, because the variable is in a "[temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz)" from the start of the block until the declaration is processed.
```js
console.log(x); // ReferenceError
const x = 3;
console.log(y); // ReferenceError
let y = 3;
```
Unlike `var` declarations, which only hoist the declaration but not its value, [function declarations](/en-US/docs/Web/JavaScript/Guide/Functions#function_hoisting) are hoisted entirely β you can safely call the function anywhere in its scope. See the [hoisting](/en-US/docs/Glossary/Hoisting) glossary entry for more discussion.
### Global variables
Global variables are in fact properties of the _global object_.
In web pages, the global object is {{domxref("window")}}, so you can read and set global variables using the `window.variable` syntax. In all environments, the [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) variable (which itself is a global variable) may be used to read and set global variables. This is to provide a consistent interface among various JavaScript runtimes.
Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the `window` or `frame` name. For example, if a variable called `phoneNumber` is declared in a document, you can refer to this variable from an `iframe` as `parent.phoneNumber`.
### Constants
You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as any variable identifier: it must start with a letter, underscore, or dollar sign (`$`), and can contain alphabetic, numeric, or underscore characters.
```js
const PI = 3.14;
```
A constant cannot change value through assignment or be re-declared while the script is running. It must be initialized to a value. The scope rules for constants are the same as those for `let` block-scope variables.
You cannot declare a constant with the same name as a function or variable in the same scope. For example:
```js-nolint example-bad
// THIS WILL CAUSE AN ERROR
function f() {}
const f = 5;
// THIS WILL CAUSE AN ERROR TOO
function f() {
const g = 5;
var g;
}
```
However, `const` only prevents _re-assignments_, but doesn't prevent _mutations_. The properties of objects assigned to constants are not protected, so the following statement is executed without problems.
```js
const MY_OBJECT = { key: "value" };
MY_OBJECT.key = "otherValue";
```
Also, the contents of an array are not protected, so the following statement is executed without problems.
```js
const MY_ARRAY = ["HTML", "CSS"];
MY_ARRAY.push("JAVASCRIPT");
console.log(MY_ARRAY); // ['HTML', 'CSS', 'JAVASCRIPT'];
```
## Data structures and types
### Data types
The latest ECMAScript standard defines eight data types:
- Seven data types that are {{Glossary("Primitive", "primitives")}}:
1. {{Glossary("Boolean")}}. `true` and `false`.
2. {{Glossary("null")}}. A special keyword denoting a null value. (Because JavaScript is case-sensitive, `null` is not the same as `Null`, `NULL`, or any other variant.)
3. {{Glossary("undefined")}}. A top-level property whose value is not defined.
4. {{Glossary("Number")}}. An integer or floating point number. For example: `42` or `3.14159`.
5. {{Glossary("BigInt")}}. An integer with arbitrary precision. For example: `9007199254740992n`.
6. {{Glossary("String")}}. A sequence of characters that represent a text value. For example: `"Howdy"`.
7. [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol). A data type whose instances are unique and immutable.
- and {{Glossary("Object")}}
Although these data types are relatively few, they enable you to perform useful operations with your applications. [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) are the other fundamental elements of the language. While functions are technically a kind of object, you can think of objects as named containers for values, and functions as procedures that your script can perform.
### Data type conversion
JavaScript is a _dynamically typed_ language. This means you don't have to specify the data type of a variable when you declare it. It also means that data types are automatically converted as-needed during script execution.
So, for example, you could define a variable as follows:
```js
let answer = 42;
```
And later, you could assign the same variable a string value, for example:
```js
answer = "Thanks for all the fish!";
```
Because JavaScript is dynamically typed, this assignment does not cause an error message.
### Numbers and the '+' operator
In expressions involving numeric and string values with the `+` operator, JavaScript converts numeric values to strings. For example, consider the following statements:
```js
x = "The answer is " + 42; // "The answer is 42"
y = 42 + " is the answer"; // "42 is the answer"
z = "37" + 7; // "377"
```
With all other operators, JavaScript does _not_ convert numeric values to strings. For example:
```js
"37" - 7; // 30
"37" * 7; // 259
```
### Converting strings to numbers
In the case that a value representing a number is in memory as a string, there are methods for conversion.
- {{jsxref("parseInt()")}}
- {{jsxref("parseFloat()")}}
`parseInt` only returns whole numbers, so its use is diminished for decimals.
> **Note:** Additionally, a best practice for `parseInt` is to always include the _radix_ parameter. The radix parameter is used to specify which numerical system is to be used.
```js
parseInt("101", 2); // 5
```
An alternative method of retrieving a number from a string is with the `+` (unary plus) operator:
```js-nolint
"1.1" + "1.1" // '1.11.1'
(+"1.1") + (+"1.1"); // 2.2
// Note: the parentheses are added for clarity, not required.
```
## Literals
_Literals_ represent values in JavaScript. These are fixed valuesβnot variablesβthat you _literally_ provide in your script. This section describes the following types of literals:
- [Array literals](#array_literals)
- [Boolean literals](#boolean_literals)
- [Numeric literals](#numeric_literals)
- [Object literals](#object_literals)
- [RegExp literals](#regexp_literals)
- [String literals](#string_literals)
### Array literals
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (`[]`). When you create an array using an array literal, it is initialized with the specified values as its elements, and its `length` is set to the number of arguments specified.
The following example creates the `coffees` array with three elements and a `length` of three:
```js
const coffees = ["French Roast", "Colombian", "Kona"];
```
An array literal creates a new array object every time the literal is evaluated. For example, an array defined with a literal in the global scope is created once when the script loads. However, if the array literal is inside a function, a new array is instantiated every time that function is called.
> **Note:** Array literals create `Array` objects. See {{jsxref("Array")}} and [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) for details on `Array` objects.
#### Extra commas in array literals
If you put two commas in a row in an array literal, the array leaves an empty slot for the unspecified element. The following example creates the `fish` array:
```js
const fish = ["Lion", , "Angel"];
```
When you log this array, you will see:
```js
console.log(fish);
// [ 'Lion', <1 empty item>, 'Angel' ]
```
Note that the second item is "empty", which is not exactly the same as the actual `undefined` value. When using array-traversing methods like [`Array.prototype.map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), empty slots are skipped. However, index-accessing `fish[1]` still returns `undefined`.
If you include a trailing comma at the end of the list of elements, the comma is ignored.
In the following example, the `length` of the array is three. There is no `myList[3]`. All other commas in the list indicate a new element.
```js
const myList = ["home", , "school"];
```
In the following example, the `length` of the array is four, and `myList[0]` and `myList[2]` are missing.
```js
const myList = [, "home", , "school"];
```
In the following example, the `length` of the array is four, and `myList[1]` and `myList[3]` are missing. **Only the last comma is ignored.**
```js
const myList = ["home", , "school", ,];
```
> **Note:** [Trailing commas](/en-US/docs/Web/JavaScript/Reference/Trailing_commas) help keep git diffs clean when you have a multi-line array, because appending an item to the end only adds one line, but does not modify the previous line.
>
> ```diff
> const myList = [
> "home",
> "school",
> + "hospital",
> ];
> ```
Understanding the behavior of extra commas is important to understanding JavaScript as a language.
However, when writing your own code, you should explicitly declare the missing elements as `undefined`, or at least insert a comment to highlight its absence. Doing this increases your code's clarity and maintainability.
```js-nolint
const myList = ["home", /* empty */, "school", /* empty */, ];
```
### Boolean literals
The Boolean type has two literal values: `true` and `false`.
> **Note:** Do not confuse the primitive Boolean values `true` and `false` with the true and false values of the {{jsxref("Boolean")}} object.
>
> The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.
### Numeric literals
JavaScript numeric literals include integer literals in different bases as well as floating-point literals in base-10.
Note that the language specification requires numeric literals to be unsigned. Nevertheless, code fragments like `-123.4` are fine, being interpreted as a unary `-` operator applied to the numeric literal `123.4`.
#### Integer literals
Integer and {{jsxref("BigInt")}} literals can be written in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).
- A _decimal_ integer literal is a sequence of digits without a leading `0` (zero).
- A leading `0` (zero) on an integer literal, or a leading `0o` (or `0O`) indicates it is in _octal_. Octal integer literals can include only the digits `0` β `7`.
- A leading `0x` (or `0X`) indicates a _hexadecimal_ integer literal. Hexadecimal integers can include digits (`0` β `9`) and the letters `a` β `f` and `A` β `F`. (The case of a character does not change its value. Therefore: `0xa` = `0xA` = `10` and `0xf` = `0xF` = `15`.)
- A leading `0b` (or `0B`) indicates a _binary_ integer literal. Binary integer literals can only include the digits `0` and `1`.
- A trailing `n` suffix on an integer literal indicates a {{jsxref("BigInt")}} literal. The {{jsxref("BigInt")}} literal can use any of the above bases. Note that leading-zero octal syntax like `0123n` is not allowed, but `0o123n` is fine.
Some examples of integer literals are:
```plain
0, 117, 123456789123456789n (decimal, base 10)
015, 0001, 0o777777777777n (octal, base 8)
0x1123, 0x00111, 0x123456789ABCDEFn (hexadecimal, "hex" or base 16)
0b11, 0b0011, 0b11101001010101010101n (binary, base 2)
```
For more information, see [Numeric literals in the Lexical grammar reference](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals).
#### Floating-point literals
A floating-point literal can have the following parts:
- An unsigned decimal integer,
- A decimal point (`.`),
- A fraction (another decimal number),
- An exponent.
The exponent part is an `e` or `E` followed by an integer, which can be signed (preceded by `+` or `-`). A floating-point literal must have at least one digit, and either a decimal point or `e` (or `E`).
More succinctly, the syntax is:
```plain
[digits].[digits][(E|e)[(+|-)]digits]
```
For example:
```js-nolint
3.1415926
.123456789
3.1E+12
.1e-23
```
### Object literals
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (`{}`).
> **Warning:** Do not use an object literal at the beginning of a statement! This will lead to an error (or not behave as you expect), because the `{` will be interpreted as the beginning of a block.
The following is an example of an object literal. The first element of the `car` object defines a property, `myCar`, and assigns to it a new string, `"Saturn"`; the second element, the `getCar` property, is immediately assigned the result of invoking the function `(carTypes("Honda"))`; the third element, the `special` property, uses an existing variable (`sales`).
```js
const sales = "Toyota";
function carTypes(name) {
return name === "Honda" ? name : `Sorry, we don't sell ${name}.`;
}
const car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };
console.log(car.myCar); // Saturn
console.log(car.getCar); // Honda
console.log(car.special); // Toyota
```
Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.
```js
const car = { manyCars: { a: "Saab", b: "Jeep" }, 7: "Mazda" };
console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
```
Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier", "identifier")}} or number, it must be enclosed in quotes.
Property names that are not valid identifiers cannot be accessed as a dot (`.`) property.
```js-nolint example-bad
const unusualPropertyNames = {
'': 'An empty string',
'!': 'Bang!'
}
console.log(unusualPropertyNames.''); // SyntaxError: Unexpected string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
```
Instead, they must be accessed with the bracket notation (`[]`).
```js example-good
console.log(unusualPropertyNames[""]); // An empty string
console.log(unusualPropertyNames["!"]); // Bang!
```
#### Enhanced Object literals
Object literals support a range of shorthand syntaxes that include setting the prototype at construction, shorthand for `foo: foo` assignments, defining methods, making `super` calls, and computing property names with expressions.
Together, these also bring object literals and class declarations closer together, and allow object-based design to benefit from some of the same conveniences.
```js
const obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for 'handler: handler'
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
["prop_" + (() => 42)()]: 42,
};
```
### RegExp literals
A regex literal (which is defined in detail [later](/en-US/docs/Web/JavaScript/Guide/Regular_expressions)) is a pattern enclosed between slashes. The following is an example of a regex literal.
```js
const re = /ab+c/;
```
### String literals
A string literal is zero or more characters enclosed in double (`"`) or single (`'`) quotation marks. A string must be delimited by quotation marks of the same type (that is, either both single quotation marks, or both double quotation marks).
The following are examples of string literals:
```js-nolint
'foo'
"bar"
'1234'
'one line \n another line'
"Joyo's cat"
```
You should use string literals unless you specifically need to use a `String` object. See {{jsxref("String")}} for details on `String` objects.
You can call any of the {{jsxref("String")}} object's methods on a string literal value. JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the `length` property with a string literal:
```js
// Will print the number of symbols in the string including whitespace.
console.log("Joyo's cat".length); // In this case, 10.
```
[Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) are also available. Template literals are enclosed by the back-tick (`` ` ``) ([grave accent](https://en.wikipedia.org/wiki/Grave_accent)) character instead of double or single quotes.
Template literals provide syntactic sugar for constructing strings. (This is similar to string interpolation features in Perl, Python, and more.)
```js-nolint
// Basic literal string creation
`In JavaScript '\n' is a line-feed.`
// Multiline strings
`In JavaScript, template strings can run
over multiple lines, but double and single
quoted strings cannot.`
// String interpolation
const name = 'Lev', time = 'today';
`Hello ${name}, how are you ${time}?`
```
[Tagged templates](/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) are a compact syntax for specifying a template literal along with a call to a "tag" function for parsing it. A tagged template is just a more succinct and semantic way to invoke a function that processes a string and a set of relevant values. The name of the template tag function precedes the template literal β as in the following example, where the template tag function is named `print`. The `print` function will interpolate the arguments and serialize any objects or arrays that may come up, avoiding the pesky `[object Object]`.
```js
const formatArg = (arg) => {
if (Array.isArray(arg)) {
// Print a bulleted list
return arg.map((part) => `- ${part}`).join("\n");
}
if (arg.toString === Object.prototype.toString) {
// This object will be serialized to "[object Object]".
// Let's print something nicer.
return JSON.stringify(arg);
}
return arg;
};
const print = (segments, ...args) => {
// For any well-formed template literal, there will always be N args and
// (N+1) string segments.
let message = segments[0];
segments.slice(1).forEach((segment, index) => {
message += formatArg(args[index]) + segment;
});
console.log(message);
};
const todos = [
"Learn JavaScript",
"Learn Web APIs",
"Set up my website",
"Profit!",
];
const progress = { javascript: 20, html: 50, css: 10 };
print`I need to do:
${todos}
My current progress is: ${progress}
`;
// I need to do:
// - Learn JavaScript
// - Learn Web APIs
// - Set up my website
// - Profit!
// My current progress is: {"javascript":20,"html":50,"css":10}
```
Since tagged template literals are just sugar of function calls, you can re-write the above as an equivalent function call:
```js
print(["I need to do:\n", "\nMy current progress is: ", "\n"], todos, progress);
```
This may be reminiscent of the `console.log`-style interpolation:
```js
console.log("I need to do:\n%o\nMy current progress is: %o\n", todos, progress);
```
You can see how the tagged template reads more naturally than a traditional "formatter" function, where the variables and the template itself have to be declared separately.
#### Using special characters in strings
In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.
```js
"one line \n another line";
```
The following table lists the special characters that you can use in JavaScript strings.
| Character | Meaning |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `\0` | Null Byte |
| `\b` | Backspace |
| `\f` | Form Feed |
| `\n` | New Line |
| `\r` | Carriage Return |
| `\t` | Tab |
| `\v` | Vertical tab |
| `\'` | Apostrophe or single quote |
| `\"` | Double quote |
| `\\` | Backslash character |
| `\XXX` | The character with the Latin-1 encoding specified by up to three octal digits `XXX` between `0` and `377`. For example, `\251` is the octal sequence for the copyright symbol. |
| `\xXX` | The character with the Latin-1 encoding specified by the two hexadecimal digits `XX` between `00` and `FF`. For example, `\xA9` is the hexadecimal sequence for the copyright symbol. |
| `\uXXXX` | The Unicode character specified by the four hexadecimal digits `XXXX`. For example, `\u00A9` is the Unicode sequence for the copyright symbol. See [Unicode escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#string_literals). |
| `\u{XXXXX}` | Unicode code point escapes. For example, `\u{2F804}` is the same as the simple Unicode escapes `\uD87E\uDC04`. |
#### Escaping characters
For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.
You can insert a quotation mark inside a string by preceding it with a backslash. This is known as _escaping_ the quotation mark. For example:
```js-nolint
const quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);
```
The result of this would be:
```plain
He read "The Cremation of Sam McGee" by R.W. Service.
```
To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path `c:\temp` to a string, use the following:
```js
const home = "c:\\temp";
```
You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.
```js
const str =
"this string \
is broken \
across multiple \
lines.";
console.log(str); // this string is broken across multiple lines.
```
## More information
This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:
- [Control flow and error handling](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling) guide
- [Loops and iteration](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions)
- [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators) guide
In the next chapter, we will have a look at control flow constructs and error handling.
{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/introduction/index.md | ---
title: Introduction
slug: Web/JavaScript/Guide/Introduction
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
This chapter introduces JavaScript and discusses some of its fundamental concepts.
## What you should already know
This guide assumes you have the following basic background:
- A general understanding of the Internet and the World Wide Web ([WWW](/en-US/docs/Glossary/World_Wide_Web)).
- Good working knowledge of HyperText Markup Language ([HTML](/en-US/docs/Glossary/HTML)).
- Some programming experience. If you are new to programming, try one of the tutorials linked on the main page about [JavaScript](/en-US/docs/Web/JavaScript).
## Where to find JavaScript information
The JavaScript documentation on MDN includes the following:
- [Learn Web Development](/en-US/docs/Learn) provides information for beginners and introduces basic concepts of programming and the Internet.
- [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide) (this guide) provides an overview about the JavaScript language and its objects.
- [JavaScript Reference](/en-US/docs/Web/JavaScript/Reference) provides detailed reference material for JavaScript.
If you are new to JavaScript, start with the articles in the [learning area](/en-US/docs/Learn) and the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide). Once you have a firm grasp of the fundamentals, you can use the [JavaScript Reference](/en-US/docs/Web/JavaScript/Reference) to get more details on individual objects and statements.
## What is JavaScript?
JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.js, which allow you to add more functionality to a website than downloading files (such as realtime collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them.
JavaScript contains a standard library of objects, such as `Array`, `Date`, and `Math`, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:
- _Client-side JavaScript_ extends the core language by supplying objects to control a browser and its _Document Object Model_ (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
- _Server-side JavaScript_ extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.
This means that in the browser, JavaScript can change the way the webpage (DOM) looks. And, likewise, Node.js JavaScript on the server can respond to custom requests sent by code executed in the browser.
## JavaScript and Java
JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.
In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.
JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.
Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting the Java bytecode. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.
In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.
| JavaScript | Java |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically. | Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically. |
| Variable data types are not declared (dynamic typing, loosely typed). | Variable data types must be declared (static typing, strongly typed). |
| Cannot automatically write to hard disk. | Can automatically write to hard disk. |
## JavaScript and the ECMAScript specification
JavaScript is standardized at [Ecma International](https://www.ecma-international.org/) β the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification.
The ECMA-262 standard is also approved by the [ISO](https://www.iso.org/home.html) (International Organization for Standardization) as ISO-16262. You can also find the specification on [the Ecma International website](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/). The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the [World Wide Web Consortium (W3C)](https://www.w3.org/) and/or [WHATWG (Web Hypertext Application Technology Working Group)](https://whatwg.org). The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article [JavaScript technologies overview](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview).
### JavaScript documentation versus the ECMAScript specification
The ECMAScript specification is a set of requirements for implementing ECMAScript. It is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or V8 in Chrome).
The ECMAScript document is _not_ intended to help script programmers. Use the JavaScript documentation for information when writing scripts.
The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.
The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.
## Getting started with JavaScript
To get started with JavaScript, all you need is a modern web browser. Recent versions of [Firefox](https://www.mozilla.org/en-CA/firefox/new/), [Chrome](https://www.google.com/chrome/index.html), [Microsoft Edge](https://www.microsoft.com/en-us/edge), and [Safari](https://www.apple.com/safari/) all support the features discussed in this guide.
A very useful tool for exploring JavaScript is the JavaScript Console (sometimes called the Web Console, or just the console): this is a tool which enables you to enter JavaScript and run it in the current page.
The screenshots here show the [Firefox Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/), but all modern browsers ship with a console that works in a similar way.
### Opening the console
The exact instructions for opening the console vary from one browser to another:
- [Opening the console in Firefox](https://firefox-source-docs.mozilla.org/devtools-user/web_console/#opening-the-web-console)
- [Opening the console in Chrome](https://developer.chrome.com/docs/devtools/open)
- [Opening the console in Microsoft Edge](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/console/)
### Entering and running JavaScript
The console appears at the bottom of the browser window. Along the bottom of the console is an input line that you can use to enter JavaScript, and the output appears in the panel above:

The console works the exact same way as `eval`: the last expression entered is returned. For the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by `console.log` around `eval`, like so:
```js
console.log(eval("3 + 5"));
```
### Multi-line input in the console
By default, if you press <kbd>Enter</kbd> (or <kbd>Return</kbd>, depending on your keyboard) after entering a line of code, then the string you typed is executed. To enter multi-line input:
- If the string you typed was incomplete (for example, you typed `function foo() {`) then the console will treat <kbd>Enter</kbd> as a line break, and let you type another line.
- If you hold down <kbd>Shift</kbd> while pressing <kbd>Enter</kbd>, then the console will treat this as a line break, and let you type another line.
- In Firefox only, you can activate [multi-line input mode](https://firefox-source-docs.mozilla.org/devtools-user/web_console/the_command_line_interpreter/index.html#multi-line-mode), in which you can enter multiple lines in a mini-editor, then run the whole thing when you are ready.
To get started with writing JavaScript, open the console, copy the following code, and paste it in at the prompt:
```js
(function () {
"use strict";
/* Start of your code */
function greetMe(yourName) {
alert(`Hello ${yourName}`);
}
greetMe("World");
/* End of your code */
})();
```
Press <kbd>Enter</kbd> to watch it unfold in your browser!
## What's next
In the following pages, this guide introduces you to the JavaScript syntax and language features, so that you will be able to write more complex applications.
But for now, remember to always include the `(function(){"use strict";` before your code, and add `})();` to the end of your code. The [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) and [IIFE](/en-US/docs/Glossary/IIFE) articles explain what those do, but for now they can be thought of as doing the following:
1. Prevent semantics in JavaScript that trip up beginners.
2. Prevent code snippets executed in the console from interacting with one another (e.g., having something created in one console execution being used for a different console execution).
{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/guide | data/mdn-content/files/en-us/web/javascript/guide/keyed_collections/index.md | ---
title: Keyed collections
slug: Web/JavaScript/Guide/Keyed_collections
page-type: guide
---
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Indexed_collections", "Web/JavaScript/Guide/Working_with_objects")}}
This chapter introduces collections of data which are indexed by a key; `Map` and `Set` objects contain elements which are iterable in the order of insertion.
## Maps
### Map object
A {{jsxref("Map")}} object is a simple key/value map and can iterate its elements in insertion order.
The following code shows some basic operations with a `Map`. See also the {{jsxref("Map")}} reference page for more examples and the complete API. You can use a {{jsxref("Statements/for...of", "for...of")}} loop to return an array of `[key, value]` for each iteration.
```js
const sayings = new Map();
sayings.set("dog", "woof");
sayings.set("cat", "meow");
sayings.set("elephant", "toot");
sayings.size; // 3
sayings.get("dog"); // woof
sayings.get("fox"); // undefined
sayings.has("bird"); // false
sayings.delete("dog");
sayings.has("dog"); // false
for (const [key, value] of sayings) {
console.log(`${key} goes ${value}`);
}
// "cat goes meow"
// "elephant goes toot"
sayings.clear();
sayings.size; // 0
```
### Object and Map compared
Traditionally, {{jsxref("Object", "objects", "", 1)}} have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. `Map` objects, however, have a few more advantages that make them better maps.
- The keys of an `Object` are [strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or [symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), whereas they can be of any value for a `Map`.
- You can get the `size` of a `Map` easily, while you have to manually keep track of size for an `Object`.
- The iteration of maps is in insertion order of the elements.
- An `Object` has a prototype, so there are default keys in the map. (This can be bypassed using `map = Object.create(null)`.)
These three tips can help you to decide whether to use a `Map` or an `Object`:
- Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
- Use maps if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value.
- Use objects when there is logic that operates on individual elements.
### WeakMap object
A {{jsxref("WeakMap")}} is a collection of key/value pairs whose keys must be objects or [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry), with values of any arbitrary [JavaScript type](/en-US/docs/Web/JavaScript/Data_structures), 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) β because non-registered symbols are guaranteed to be unique and cannot be re-created.
The `WeakMap` API is essentially the same as the `Map` API. However, a `WeakMap` doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration. So there is no method to obtain a list of the keys in a `WeakMap`. If there were, the list would depend on the state of garbage collection, introducing non-determinism.
For more information and example code, see also "Why WeakMap?" on the {{jsxref("WeakMap")}} reference page.
One use case of `WeakMap` objects is to store private data for an object, or to hide implementation details. The following example is from Nick Fitzgerald's blog post ["Hiding Implementation Details with ECMAScript 6 WeakMaps"](https://fitzgeraldnick.com/2014/01/13/hiding-implementation-details-with-e6-weakmaps.html). The private data and methods belong inside the object and are stored in the `privates` object, which is a `WeakMap`. Everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because `privates` is not exported from the module.
```js
const privates = new WeakMap();
function Public() {
const me = {
// Private data goes here
};
privates.set(this, me);
}
Public.prototype.method = function () {
const me = privates.get(this);
// Do stuff with private data in `me`
// β¦
};
module.exports = Public;
```
## Sets
### Set object
{{jsxref("Set")}} objects are collections of unique values. You can iterate its elements in insertion order. A value in a `Set` may only occur once; it is unique in the `Set`'s collection.
The following code shows some basic operations with a `Set`. See also the {{jsxref("Set")}} reference page for more examples and the complete API.
```js
const mySet = new Set();
mySet.add(1);
mySet.add("some text");
mySet.add("foo");
mySet.has(1); // true
mySet.delete("foo");
mySet.size; // 2
for (const item of mySet) {
console.log(item);
}
// 1
// "some text"
```
### Converting between Array and Set
You can create an {{jsxref("Array")}} from a Set using {{jsxref("Array.from")}} or the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). Also, the `Set` constructor accepts an `Array` to convert in the other direction.
> **Note:** `Set` objects store _unique values_βso any duplicate elements from an Array are deleted when converting!
```js
Array.from(mySet);
[...mySet2];
mySet2 = new Set([1, 2, 3, 4]);
```
### Array and Set compared
Traditionally, a set of elements has been stored in arrays in JavaScript in a lot of situations. The `Set` object, however, has some advantages:
- Deleting Array elements by value (`arr.splice(arr.indexOf(val), 1)`) is very slow.
- `Set` objects let you delete elements by their value. With an array, you would have to `splice` based on an element's index.
- The value {{jsxref("NaN")}} cannot be found with `indexOf` in an array.
- `Set` objects store unique values. You don't have to manually keep track of duplicates.
### WeakSet object
{{jsxref("WeakSet")}} objects are collections of garbage-collectable values, including objects and [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). A value in the `WeakSet` may only occur once. It is unique in the `WeakSet`'s collection.
The main differences to the {{jsxref("Set")}} object are:
- In contrast to `Sets`, `WeakSets` are **collections of _objects or symbols only_**, and not of arbitrary values of any type.
- The `WeakSet` is _weak_: References to objects in the collection are held weakly. If there is no other reference to an object stored in the `WeakSet`, they can be garbage collected. That also means that there is no list of current objects stored in the collection.
- `WeakSets` are not enumerable.
The use cases of `WeakSet` objects are limited. They will not leak memory, so it can be safe to use DOM elements as a key and mark them for tracking purposes, for example.
## Key and value equality of Map and Set
Both the key equality of `Map` objects and the value equality of `Set` objects are based on the [SameValueZero algorithm](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality):
- Equality works like the identity comparison operator `===`.
- `-0` and `+0` are considered equal.
- {{jsxref("NaN")}} is considered equal to itself (contrary to `===`).
{{PreviousNext("Web/JavaScript/Guide/Indexed_collections", "Web/JavaScript/Guide/Working_with_objects")}}
| 0 |
data/mdn-content/files/en-us/web/javascript | data/mdn-content/files/en-us/web/javascript/reference/index.md | ---
title: JavaScript reference
slug: Web/JavaScript/Reference
page-type: landing-page
---
{{jsSidebar}}
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](/en-US/docs/Web/JavaScript/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.
## Built-ins
[JavaScript standard built-in objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects), along with their methods and properties.
### Value properties
- {{jsxref("globalThis")}}
- {{jsxref("Infinity")}}
- {{jsxref("NaN")}}
- {{jsxref("undefined")}}
### Function properties
- {{jsxref("Global_Objects/eval", "eval()")}}
- {{jsxref("isFinite()")}}
- {{jsxref("isNaN()")}}
- {{jsxref("parseFloat()")}}
- {{jsxref("parseInt()")}}
- {{jsxref("decodeURI()")}}
- {{jsxref("decodeURIComponent()")}}
- {{jsxref("encodeURI()")}}
- {{jsxref("encodeURIComponent()")}}
- {{jsxref("escape()")}} {{deprecated_inline}}
- {{jsxref("unescape()")}} {{deprecated_inline}}
### Fundamental objects
- {{jsxref("Object")}}
- {{jsxref("Function")}}
- {{jsxref("Boolean")}}
- {{jsxref("Symbol")}}
### Error objects
- {{jsxref("Error")}}
- {{jsxref("AggregateError")}}
- {{jsxref("EvalError")}}
- {{jsxref("RangeError")}}
- {{jsxref("ReferenceError")}}
- {{jsxref("SyntaxError")}}
- {{jsxref("TypeError")}}
- {{jsxref("URIError")}}
- {{jsxref("InternalError")}} {{non-standard_inline}}
### Numbers and dates
- {{jsxref("Number")}}
- {{jsxref("BigInt")}}
- {{jsxref("Math")}}
- {{jsxref("Date")}}
### Text processing
- {{jsxref("String")}}
- {{jsxref("RegExp")}}
### Indexed collections
- {{jsxref("Array")}}
- {{jsxref("Int8Array")}}
- {{jsxref("Uint8Array")}}
- {{jsxref("Uint8ClampedArray")}}
- {{jsxref("Int16Array")}}
- {{jsxref("Uint16Array")}}
- {{jsxref("Int32Array")}}
- {{jsxref("Uint32Array")}}
- {{jsxref("BigInt64Array")}}
- {{jsxref("BigUint64Array")}}
- {{jsxref("Float32Array")}}
- {{jsxref("Float64Array")}}
### Keyed collections
- {{jsxref("Map")}}
- {{jsxref("Set")}}
- {{jsxref("WeakMap")}}
- {{jsxref("WeakSet")}}
### Structured data
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
- {{jsxref("DataView")}}
- {{jsxref("Atomics")}}
- {{jsxref("JSON")}}
### Managing memory
- {{jsxref("WeakRef")}}
- {{jsxref("FinalizationRegistry")}}
### Control abstraction objects
- {{jsxref("Iterator")}}
- {{jsxref("AsyncIterator")}}
- {{jsxref("Promise")}}
- {{jsxref("GeneratorFunction")}}
- {{jsxref("AsyncGeneratorFunction")}}
- {{jsxref("Generator")}}
- {{jsxref("AsyncGenerator")}}
- {{jsxref("AsyncFunction")}}
### Reflection
- {{jsxref("Reflect")}}
- {{jsxref("Proxy")}}
### Internationalization
- {{jsxref("Intl")}}
- {{jsxref("Intl.Collator")}}
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Intl.DisplayNames")}}
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Intl.Locale")}}
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Intl.PluralRules")}}
- {{jsxref("Intl.RelativeTimeFormat")}}
- {{jsxref("Intl.Segmenter")}}
## Statements
[JavaScript statements and declarations](/en-US/docs/Web/JavaScript/Reference/Statements)
### Control flow
- {{jsxref("Statements/return", "return")}}
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/continue", "continue")}}
- {{jsxref("Statements/throw", "throw")}}
- {{jsxref("Statements/if...else", "if...else")}}
- {{jsxref("Statements/switch", "switch")}}
- {{jsxref("Statements/try...catch", "try...catch")}}
### Declaring variables
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Statements/let", "let")}}
- {{jsxref("Statements/const", "const")}}
### Functions and classes
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("Statements/async_function*", "async function*")}}
- {{jsxref("Statements/class", "class")}}
### Iterations
- {{jsxref("Statements/do...while", "do...while")}}
- {{jsxref("Statements/for", "for")}}
- {{jsxref("Statements/for...in", "for...in")}}
- {{jsxref("Statements/for...of", "for...of")}}
- {{jsxref("Statements/for-await...of", "for await...of")}}
- {{jsxref("Statements/while", "while")}}
### Others
- {{jsxref("Statements/Empty", "Empty", "", 1)}}
- {{jsxref("Statements/block", "Block", "", 1)}}
- {{jsxref("Statements/Expression_statement", "Expression statement", "", 1)}}
- {{jsxref("Statements/debugger", "debugger")}}
- {{jsxref("Statements/export", "export")}}
- {{jsxref("Statements/import", "import")}}
- {{jsxref("Statements/label", "label", "", 1)}}
- {{jsxref("Statements/with", "with")}} {{deprecated_inline}}
## Expressions and operators
[JavaScript expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators).
### Primary expressions
- {{jsxref("Operators/this", "this")}}
- [Literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#literals)
- {{jsxref("Array", "[]")}}
- {{jsxref("Operators/Object_initializer", "{}")}}
- {{jsxref("Operators/function", "function")}}
- {{jsxref("Operators/class", "class")}}
- {{jsxref("Operators/function*", "function*")}}
- {{jsxref("Operators/async_function", "async function")}}
- {{jsxref("Operators/async_function*", "async function*")}}
- {{jsxref("RegExp", "/ab+c/i")}}
- {{jsxref("Template_literals", "`string`")}}
- {{jsxref("Operators/Grouping", "( )")}}
### Left-hand-side expressions
- {{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
- {{jsxref("Operators/Optional_chaining", "?.")}}
- {{jsxref("Operators/new", "new")}}
- {{jsxref("Operators/new%2Etarget", "new.target")}}
- {{jsxref("Operators/import%2Emeta", "import.meta")}}
- {{jsxref("Operators/super", "super")}}
- {{jsxref("Operators/import", "import()")}}
### Increment and decrement
- {{jsxref("Operators/Increment", "A++")}}
- {{jsxref("Operators/Decrement", "A--")}}
- {{jsxref("Operators/Increment", "++A")}}
- {{jsxref("Operators/Decrement", "--A")}}
### Unary operators
- {{jsxref("Operators/delete", "delete")}}
- {{jsxref("Operators/void", "void")}}
- {{jsxref("Operators/typeof", "typeof")}}
- {{jsxref("Operators/Unary_plus", "+")}}
- {{jsxref("Operators/Unary_negation", "-")}}
- {{jsxref("Operators/Bitwise_NOT", "~")}}
- {{jsxref("Operators/Logical_NOT", "!")}}
- {{jsxref("Operators/await", "await")}}
### Arithmetic operators
- {{jsxref("Operators/Exponentiation", "**")}}
- {{jsxref("Operators/Multiplication", "*")}}
- {{jsxref("Operators/Division", "/")}}
- {{jsxref("Operators/Remainder", "%")}}
- {{jsxref("Operators/Addition", "+")}} (Plus)
- {{jsxref("Operators/Subtraction", "-")}}
### Relational operators
- {{jsxref("Operators/Less_than", "<")}} (Less than)
- {{jsxref("Operators/Greater_than", ">")}} (Greater than)
- {{jsxref("Operators/Less_than_or_equal", "<=")}}
- {{jsxref("Operators/Greater_than_or_equal", ">=")}}
- {{jsxref("Operators/instanceof", "instanceof")}}
- {{jsxref("Operators/in", "in")}}
### Equality operators
- {{jsxref("Operators/Equality", "==")}}
- {{jsxref("Operators/Inequality", "!=")}}
- {{jsxref("Operators/Strict_equality", "===")}}
- {{jsxref("Operators/Strict_inequality", "!==")}}
### Bitwise shift operators
- {{jsxref("Operators/Left_shift", "<<")}}
- {{jsxref("Operators/Right_shift", ">>")}}
- {{jsxref("Operators/Unsigned_right_shift", ">>>")}}
### Binary bitwise operators
- {{jsxref("Operators/Bitwise_AND", "&")}}
- {{jsxref("Operators/Bitwise_OR", "|")}}
- {{jsxref("Operators/Bitwise_XOR", "^")}}
### Binary logical operators
- {{jsxref("Operators/Logical_AND", "&&")}}
- {{jsxref("Operators/Logical_OR", "||")}}
- {{jsxref("Operators/Nullish_coalescing", "??")}}
### Conditional (ternary) operator
- {{jsxref("Operators/Conditional_operator", "(condition ? ifTrue : ifFalse)")}}
### Assignment operators
- {{jsxref("Operators/Assignment", "=")}}
- {{jsxref("Operators/Multiplication_assignment", "*=")}}
- {{jsxref("Operators/Division_assignment", "/=")}}
- {{jsxref("Operators/Remainder_assignment", "%=")}}
- {{jsxref("Operators/Addition_assignment", "+=")}}
- {{jsxref("Operators/Subtraction_assignment", "-=")}}
- {{jsxref("Operators/Left_shift_assignment", "<<=")}}
- {{jsxref("Operators/Right_shift_assignment", ">>=")}}
- {{jsxref("Operators/Unsigned_right_shift_assignment", ">>>=")}}
- {{jsxref("Operators/Bitwise_AND_assignment", "&=")}}
- {{jsxref("Operators/Bitwise_XOR_assignment", "^=")}}
- {{jsxref("Operators/Bitwise_OR_assignment", "|=")}}
- {{jsxref("Operators/Exponentiation_assignment", "**=")}}
- {{jsxref("Operators/Logical_AND_assignment", "&&=")}}
- {{jsxref("Operators/Logical_OR_assignment", "||=")}}
- {{jsxref("Operators/Nullish_coalescing_assignment", "??=")}}
- [`[a, b] = arr`, `{ a, b } = obj`](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
### Yield operators
- {{jsxref("Operators/yield", "yield")}}
- {{jsxref("Operators/yield*", "yield*")}}
### Spread syntax
- {{jsxref("Operators/Spread_syntax", "...obj")}}
### Comma operator
- {{jsxref("Operators/Comma_operator", ",")}}
## Functions
[JavaScript functions.](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("Functions/Arrow_functions", "Arrow Functions", "", 1)}}
- {{jsxref("Functions/Default_parameters", "Default parameters", "", 1)}}
- {{jsxref("Functions/rest_parameters", "Rest parameters", "", 1)}}
- {{jsxref("Functions/arguments", "arguments")}}
- {{jsxref("Functions/Method_definitions", "Method definitions", "", 1)}}
- {{jsxref("Functions/get", "getter", "", 1)}}
- {{jsxref("Functions/set", "setter", "", 1)}}
## Classes
[JavaScript classes.](/en-US/docs/Web/JavaScript/Reference/Classes)
- {{jsxref("Classes/Constructor", "constructor")}}
- {{jsxref("Classes/extends", "extends")}}
- [Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties)
- [Public class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields)
- {{jsxref("Classes/static", "static")}}
- [Static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks)
## Additional reference pages
- {{jsxref("Lexical_grammar", "Lexical grammar", "", 1)}}
- [Data types and data structures](/en-US/docs/Web/JavaScript/Data_structures)
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- [Trailing commas](/en-US/docs/Web/JavaScript/Reference/Trailing_commas)
- [Errors](/en-US/docs/Web/JavaScript/Reference/Errors)
- {{jsxref("Strict_mode", "Strict mode", "", 1)}}
- {{jsxref("Deprecated_and_obsolete_features", "Deprecated features", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/trailing_commas/index.md | ---
title: Trailing commas
slug: Web/JavaScript/Reference/Trailing_commas
page-type: javascript-language-feature
browser-compat: javascript.grammar.trailing_commas
---
{{jsSidebar("More")}}
**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](/en-US/docs/Glossary/JSON), however, disallows all trailing commas.
## Description
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:
- [Array literals](#arrays)
- [Object literals](#objects)
- [Parameter definitions](#parameter_definitions)
- [Function calls](#function_calls)
- [Named imports](#named_imports)
- [Named exports](#named_exports)
- [Array and object destructuring](#trailing_commas_in_destructuring)
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.
```diff
[
"foo",
+ "baz",
"bar",
- "baz",
]
```
## Examples
### Trailing commas in literals
#### Arrays
JavaScript ignores trailing commas in arrays literals:
```js-nolint
const arr = [
1,
2,
3,
];
arr; // [1, 2, 3]
arr.length; // 3
```
If more than one trailing comma is used, an elision (or hole) is produced. An array with holes is called [_sparse_](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) (a _dense_ array has no holes). When iterating arrays for example with {{jsxref("Array.prototype.forEach()")}} or {{jsxref("Array.prototype.map()")}}, array holes are skipped. Sparse arrays are generally unfavorable, so you should avoid having multiple trailing commas.
```js
const arr = [1, 2, 3, , ,];
arr.length; // 5
```
#### Objects
Trailing commas in object literals are legal as well:
```js
const object = {
foo: "bar",
baz: "qwerty",
age: 42,
};
```
### Trailing commas in functions
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property of function declarations or their [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object.
```js-nolint
function f(p) {}
function f(p,) {}
(p) => {};
(p,) => {};
```
The trailing comma also works with [method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) for classes or objects:
```js-nolint
class C {
one(a,) {}
two(a, b,) {}
}
const obj = {
one(a,) {},
two(a, b,) {},
};
```
#### Function calls
The following function invocation pairs are legal and equivalent to each other.
```js-nolint
f(p);
f(p,);
Math.max(10, 20);
Math.max(10, 20,);
```
#### Illegal trailing commas
Function parameter definitions or function invocations only containing a comma will throw a {{jsxref("SyntaxError")}}. Furthermore, when using [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), trailing commas are not allowed:
```js-nolint example-bad
function f(,) {} // SyntaxError: missing formal parameter
(,) => {}; // SyntaxError: expected expression, got ','
f(,) // SyntaxError: expected expression, got ','
function f(...p,) {} // SyntaxError: parameter after rest parameter
(...p,) => {} // SyntaxError: expected closing parenthesis, got ','
```
### Trailing commas in destructuring
A trailing comma is also allowed on the left-hand side when using [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):
```js-nolint
// array destructuring with trailing comma
[a, b,] = [1, 2];
// object destructuring with trailing comma
const o = {
p: 42,
q: true,
};
const { p, q, } = o;
```
Again, when using a rest element, a {{jsxref("SyntaxError")}} will be thrown:
```js-nolint example-bad
const [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
```
### Trailing commas in JSON
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`:
```js example-bad
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
```
Omit the trailing commas to parse the JSON correctly:
```js example-good
JSON.parse("[1, 2, 3, 4 ]");
JSON.parse('{"foo" : 1 }');
```
### Trailing commas in named imports and named exports
Trailing commas are valid in [named imports](/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import) and [named exports](/en-US/docs/Web/JavaScript/Reference/Statements/export).
#### Named imports
```js-nolint
import {
A,
B,
C,
} from "D";
import { X, Y, Z, } from "W";
import { A as B, C as D, E as F, } from "Z";
```
#### Named exports
```js-nolint
export {
A,
B,
C,
};
export { A, B, C, };
export { A as B, C as D, E as F, };
```
### Quantifier prefix
> **Note:** The trailing comma in a [quantifier](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) actually changes its semantics from matching "exactly `n`" to matching "at least `n`".
```js
/x{2}/; // Exactly 2 occurrences of "x"; equivalent to /xx/
/x{2,}/; // At least 2 occurrences of "x"; equivalent to /xx+/
/x{2,4}/; // 2 to 4 occurrences of "x"; equivalent to /xxx?x?/
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/strict_mode/index.md | ---
title: Strict mode
slug: Web/JavaScript/Reference/Strict_mode
page-type: guide
spec-urls: https://tc39.es/ecma262/multipage/strict-mode-of-ecmascript.html
---
{{jsSidebar("More")}}
> **Note:** Sometimes you'll see the default, non-strict mode referred to as _[sloppy mode](/en-US/docs/Glossary/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](/en-US/docs/Glossary/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.
## Invoking strict mode
Strict mode applies to _entire scripts_ or to _individual functions_. It doesn't apply to [block statements](/en-US/docs/Web/JavaScript/Reference/Statements/block) enclosed in `{}` braces; attempting to apply it to such contexts does nothing. [`eval`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) code, [`Function`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) code, [event handler](/en-US/docs/Web/HTML/Attributes#event_handler_attributes) attributes, strings passed to [`setTimeout()`](/en-US/docs/Web/API/setTimeout), and related functions are either function bodies or entire scripts, and invoking strict mode in them works as expected.
### Strict mode for scripts
To invoke strict mode for an entire script, put the _exact_ statement `"use strict";` (or `'use strict';`) before any other statements.
```js
// Whole-script strict mode syntax
"use strict";
const v = "Hi! I'm a strict mode script!";
```
### Strict mode for functions
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.
```js
function myStrictFunction() {
// Function-level strict mode syntax
"use strict";
function nested() {
return "And so am I!";
}
return `Hi! I'm a strict mode function! ${nested()}`;
}
function myNotStrictFunction() {
return "I'm not strict.";
}
```
The `"use strict"` directive can only be applied to the body of functions with simple parameters. Using `"use strict"` in functions with [rest](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [default](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), or [destructured](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameters is a [syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Strict_non_simple_params).
```js-nolint example-bad
function sum(a = 1, b = 2) {
// SyntaxError: "use strict" not allowed in function with default parameter
"use strict";
return a + b;
}
```
### Strict mode for modules
The entire contents of [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) are automatically in strict mode, with no statement needed to initiate it.
```js
function myStrictFunction() {
// because this is a module, I'm strict by default
}
export default myStrictFunction;
```
### Strict mode for classes
All parts of a [class](/en-US/docs/Web/JavaScript/Reference/Classes)'s body are strict mode code, including both [class declarations](/en-US/docs/Web/JavaScript/Reference/Statements/class) and [class expressions](/en-US/docs/Web/JavaScript/Reference/Operators/class).
```js
class C1 {
// All code here is evaluated in strict mode
test() {
delete Object.prototype;
}
}
new C1().test(); // TypeError, because test() is in strict mode
const C2 = class {
// All code here is evaluated in strict mode
};
// Code here may not be in strict mode
delete Object.prototype; // Will not throw error
```
## Changes in strict mode
Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories:
- changes converting mistakes into errors (as syntax errors or at runtime)
- changes simplifying how variable references are resolved
- changes simplifying `eval` and `arguments`
- changes making it easier to write "secure" JavaScript
- changes anticipating future ECMAScript evolution.
### Converting mistakes into errors
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:
```js
"use strict";
let mistypeVariable;
// Assuming no global variable mistypeVarible exists
// this line throws a ReferenceError due to the
// misspelling of "mistypeVariable" (lack of an "a")
mistypeVarible = 17;
```
#### 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:
- assignment to a non-writable data property
- assignment to a getter-only accessor property
- assignment to a new property on a [non-extensible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible) object
For example, [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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.
```js
"use strict";
// Assignment to a non-writable global
undefined = 5; // TypeError
Infinity = 5; // TypeError
// Assignment to a non-writable property
const obj1 = {};
Object.defineProperty(obj1, "x", { value: 42, writable: false });
obj1.x = 9; // TypeError
// Assignment to a getter-only property
const obj2 = {
get x() {
return 17;
},
};
obj2.x = 5; // TypeError
// Assignment to a new property on a non-extensible object
const fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = "ohai"; // TypeError
```
#### Failing to delete object properties
Attempts to [delete](/en-US/docs/Web/JavaScript/Reference/Operators/delete) a non-configurable or otherwise undeletable (e.g. it's intercepted by a proxy's [`deleteProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty) handler which returns `false`) property throw in strict mode (where before the attempt would have no effect):
```js
"use strict";
delete Object.prototype; // TypeError
delete [].length; // TypeError
```
Strict mode also forbids deleting plain names. `delete name` in strict mode is a syntax error:
```js-nolint example-bad
"use strict";
var x;
delete x; // syntax error
```
If the name is a configurable global property, prefix it with [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) to delete it.
```js example-good
"use strict";
delete globalThis.x;
```
#### 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`](/en-US/docs/Web/JavaScript/Reference/Functions/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:
```js-nolint example-bad
function sum(a, a, c) {
// syntax error
"use strict";
return a + a + c; // wrong if this code ran
}
```
#### Legacy octal literals
Strict mode [forbids a `0`-prefixed octal literal or octal escape sequence](/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal). 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:
```js-nolint example-bad
"use strict";
const sum =
015 + // syntax error
197 +
142;
```
The standardized way to denote octal literals is via the `0o` prefix. For example:
```js example-good
const sumWithOctal = 0o10 + 8;
console.log(sumWithOctal); // 16
```
Octal escape sequences, such as `"\45"`, which is equal to `"%"`, can be used to represent characters by extended-{{Glossary("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](/en-US/docs/Glossary/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 {{jsxref("TypeError")}} is thrown.
```js
"use strict";
false.true = ""; // TypeError
(14).sailing = "home"; // TypeError
"with".you = "far away"; // TypeError
```
#### Duplicate property names
Duplicate property names used to be considered a {{jsxref("SyntaxError")}} in strict mode. With the introduction of [computed property names](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), making duplication possible at runtime, this restriction was removed in ES2015.
```js
"use strict";
const o = { p: 1, p: 2 }; // syntax error prior to ECMAScript 2015
```
> **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.
### Simplifying scope management
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`](/en-US/docs/Web/JavaScript/Reference/Statements/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:
```js-nolint example-bad
"use strict";
const x = 17;
with (obj) {
// Syntax error
// If this weren't strict mode, would this be const x, or
// would it instead be obj.x? It's impossible in general
// to say without running the code, so the name can't be
// optimized.
x;
}
```
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](https://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/). 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:
```js
var x = 17;
var evalX = eval("'use strict'; var x = 42; x;");
console.assert(x === 17);
console.assert(evalX === 42);
```
Whether the string passed to `eval()` is evaluated in strict mode depends on how `eval()` is invoked ([direct eval or indirect eval](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_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](/en-US/docs/Web/JavaScript/Reference/Statements/function#block-level_function_declaration) are only explicitly specified in strict mode (whereas they were once disallowed in strict mode), while sloppy mode behavior remains divergent among browsers.
### Making eval and arguments simpler
Strict mode makes [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) and [`eval`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/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:
```js-nolint example-bad
"use strict";
eval = 17;
arguments++;
++eval;
const obj = { set p(arguments) {} };
let eval;
try {
} catch (arguments) {}
function x(eval) {}
function arguments() {}
const y = function eval() {};
const f = new Function("arguments", "'use strict'; return 17;");
```
#### 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]`.
```js
function f(a) {
"use strict";
a = 42;
return [a, arguments[0]];
}
const pair = f(17);
console.assert(pair[0] === 42);
console.assert(pair[1] === 17);
```
### "Securing" JavaScript
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`apply`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), or [`bind`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis):
```js
"use strict";
function fun() {
return this;
}
console.assert(fun() === undefined);
console.assert(fun.call(2) === 2);
console.assert(fun.apply(null) === null);
console.assert(fun.call(undefined) === undefined);
console.assert(fun.bind(true)() === true);
```
#### 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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller) is the function that most recently called `fun`, and [`fun.arguments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/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:
```js
function restricted() {
"use strict";
restricted.caller; // throws a TypeError
restricted.arguments; // throws a TypeError
}
function privilegedInvoker() {
return restricted();
}
privilegedInvoker();
```
Similarly, [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/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:
```js
"use strict";
const f = function () {
return arguments.callee;
};
f(); // throws a TypeError
```
### Future-proofing JavaScript
#### Extra reserved words
[Reserved words](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#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.
- `implements`
- `interface`
- [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let)
- `package`
- `private`
- `protected`
- `public`
- [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static)
- [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield)
## Transitioning to strict mode
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.
### Syntax errors
When adding `'use strict';`, the following cases will throw a {{jsxref("SyntaxError")}} before the script is executing:
- Octal syntax `const n = 023;`
- [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) statement
- Using [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) on a variable name `delete myVariable`;
- Using [`eval`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) or [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) as variable or function argument name
- Using one of the newly [reserved keywords](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words) (in prevision for future language features): `implements`, `interface`, `let`, `package`, `private`, `protected`, `public`, `static`, and `yield`
- Declaring two function parameters with the same name `function f(a, b, b) {}`
- Declaring the same property name twice in an object literal `{a: 1, b: 3, a: 7}`. This constraint was later removed ([bug 1041128](https://bugzil.la/1041128)).
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.
### New runtime errors
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.
- Assigning to an undeclared variable throws a {{jsxref("ReferenceError")}}. This used to set a property on the global object, which is rarely the expected effect. If you really want to set a value to the global object, explicitly assign it as a property on `globalThis`.
- Failing to assign to an object's property (e.g. it's read-only) throws a {{jsxref("TypeError")}}. In sloppy mode, this would silently fail.
- Deleting a non-deletable property throws a {{jsxref("TypeError")}}. In sloppy mode, this would silently fail.
- Accessing [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee), [`strictFunction.caller`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller), or [`strictFunction.arguments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments) throws a {{jsxref("TypeError")}} if the function is in strict mode. If you are using `arguments.callee` to call the function recursively, you can use a named function expression instead.
### Semantic differences
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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) or [`apply`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/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.
## Specifications
{{Specifications}}
## See also
- [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) guide
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/classes/index.md | ---
title: Classes
slug: Web/JavaScript/Reference/Classes
page-type: guide
browser-compat: javascript.classes
---
{{jsSidebar("Classes")}}
Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on [prototypes](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) but also have some syntax and semantics that are unique to classes.
For more examples and explanations, see the [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide.
## Description
### Defining classes
Classes are in fact "special [functions](/en-US/docs/Web/JavaScript/Reference/Functions)", and just as you can define [function expressions](/en-US/docs/Web/JavaScript/Reference/Operators/function) and [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function), a class can be defined in two ways: a [class expression](/en-US/docs/Web/JavaScript/Reference/Operators/class) or a [class declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class).
```js
// Declaration
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// Expression; the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// Expression; the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
```
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](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz) restrictions as `let` or `const` and behave as if they are [not hoisted](/en-US/docs/Web/JavaScript/Guide/Using_classes#class_declaration_hoisting).
### Class body
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](/en-US/docs/Web/JavaScript/Reference/Strict_mode) even without the `"use strict"` directive.
A class element can be characterized by three aspects:
- Kind: Getter, setter, method, or field
- Location: Static or instance
- Visibility: Public or private
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](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions)
- : Public instance method
- [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get)
- : Public instance getter
- [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set)
- : Public instance setter
- [Public class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields)
- : Public instance field
- [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static)
- : Public static method, getter, setter, and field
- [Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties)
- : 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](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#duplicate_property_names).
In addition, there are two special class element syntaxes: [`constructor`](#constructor) and [static initialization blocks](#static_initialization_blocks), with their own references.
#### Constructor
The {{jsxref("Classes/constructor", "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 {{jsxref("SyntaxError")}} is thrown if the class contains more than one occurrence of a `constructor` method.
A constructor can use the [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) keyword to call the constructor of the super class.
You can create instance properties inside the constructor:
```js
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
```
Alternatively, if your instance properties' values do not depend on the constructor's arguments, you can define them as [class fields](#field_declarations).
#### Static initialization blocks
[Static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) allow flexible initialization of [static properties](#static_methods_and_fields), 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](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).
```js
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
*getSides() {
yield this.height;
yield this.width;
yield this.height;
yield this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
console.log([...square.getSides()]); // [10, 10, 10, 10]
```
#### Static methods and fields
The {{jsxref("Classes/static", "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.
```js
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static displayName = "Point";
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.displayName; // undefined
p1.distance; // undefined
p2.displayName; // undefined
p2.distance; // undefined
console.log(Point.displayName); // "Point"
console.log(Point.distance(p1, p2)); // 7.0710678118654755
```
#### Field declarations
With the class field declaration syntax, the [constructor](#constructor) example can be written as:
```js
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
```
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](#private_class_features_2) 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](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) for more information.
#### Private properties
Using private fields, the definition can be refined as below.
```js
class Rectangle {
#height = 0;
#width;
constructor(height, width) {
this.#height = height;
this.#width = width;
}
}
```
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 properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
### Inheritance
The {{jsxref("Classes/extends", "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).
```js
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog("Mitzie");
d.speak(); // Mitzie barks.
```
If there is a constructor present in the subclass, it needs to first call `super()` before using `this`. The {{jsxref("Operators/super", "super")}} keyword can also be used to call corresponding methods of super class.
```js
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(`${this.name} roars.`);
}
}
const l = new Lion("Fuzzy");
l.speak();
// Fuzzy makes a noise.
// Fuzzy roars.
```
### Evaluation order
When a [`class` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class) or [`class` expression](/en-US/docs/Web/JavaScript/Reference/Operators/class) is evaluated, its various components are evaluated in the following order:
1. The {{jsxref("Classes/extends", "extends")}} clause, if present, is first evaluated. It must evaluate to a valid constructor function or `null`, or a {{jsxref("TypeError")}} is thrown.
2. The {{jsxref("Classes/constructor", "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 {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) (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](/en-US/docs/Web/JavaScript/Reference/Classes/static) (public or private), its initializer is evaluated with `this` set to the class itself, and the property is created on the class.
- [Static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_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 {{jsxref("Classes/constructor", "constructor")}} reference.
## Examples
### Binding this with instance and static methods
When a static or instance method is called without a value for {{jsxref("Operators/this", "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"`](/en-US/docs/Web/JavaScript/Reference/Strict_mode) directive isn't present, because code within the `class` body is always executed in strict mode.
```js
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
const obj = new Animal();
obj.speak(); // the Animal object
const speak = obj.speak;
speak(); // undefined
Animal.eat(); // class Animal
const eat = Animal.eat;
eat(); // undefined
```
If we rewrite the above using traditional function-based syntax in nonβstrict mode, then `this` method calls are automatically bound to {{jsxref("globalThis")}}. In strict mode, the value of `this` remains as `undefined`.
```js
function Animal() {}
Animal.prototype.speak = function () {
return this;
};
Animal.eat = function () {
return this;
};
const obj = new Animal();
const speak = obj.speak;
speak(); // global object (in nonβstrict mode)
const eat = Animal.eat;
eat(); // global object (in non-strict mode)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [`class`](/en-US/docs/Web/JavaScript/Reference/Statements/class)
- [`class` expression](/en-US/docs/Web/JavaScript/Reference/Operators/class)
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [ES6 In Depth: Classes](https://hacks.mozilla.org/2015/07/es6-in-depth-classes/) on hacks.mozilla.org (2015)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/public_class_fields/index.md | ---
title: Public class fields
slug: Web/JavaScript/Reference/Classes/Public_class_fields
page-type: javascript-language-feature
browser-compat: javascript.classes.public_class_fields
---
{{jsSidebar("Classes")}}
**Public fields** are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they participate in prototype inheritance.
## Syntax
```js-nolint
class ClassWithField {
instanceField;
instanceFieldWithInitializer = "instance field";
static staticField;
static staticFieldWithInitializer = "static field";
}
```
There are some additional syntax restrictions:
- The name of a static property (field or method) cannot be `prototype`.
- The name of a class field (static or instance) cannot be `constructor`.
## Description
This page introduces public instance fields in detail.
- For public static fields, see [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static).
- For private fields, see [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
- For public methods, see [method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).
- For public accessors, see [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set).
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.
```js
const PREFIX = "prefix";
class ClassWithField {
field;
fieldWithInitializer = "instance field";
[`${PREFIX}Field`] = "prefixed field";
}
const instance = new ClassWithField();
console.log(Object.hasOwn(instance, "field")); // true
console.log(instance.field); // undefined
console.log(instance.fieldWithInitializer); // "instance field"
console.log(instance.prefixField); // "prefixed field"
```
Computed field names are only evaluated once, at [class definition time](/en-US/docs/Web/JavaScript/Reference/Classes#evaluation_order). 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 {{jsxref("ReferenceError")}} because the class is not initialized yet. {{jsxref("Operators/await", "await")}} and {{jsxref("Operators/yield", "yield")}} work as expected in this expression.
```js
class C {
[Math.random()] = 1;
}
console.log(new C());
console.log(new C());
// Both instances have the same field name
```
In the field initializer, [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) refers to the class instance under construction, and [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) refers to the `prototype` property of the base class, which contains the base class's instance methods, but not its instance fields.
```js
class Base {
baseField = "base field";
anotherBaseField = this.baseField;
baseMethod() {
return "base method output";
}
}
class Derived extends Base {
subField = super.baseMethod();
}
const base = new Base();
const sub = new Derived();
console.log(base.anotherBaseField); // "base field"
console.log(sub.subField); // "base method output"
```
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.)
```js
class C {
obj = {};
}
const instance1 = new C();
const instance2 = new C();
console.log(instance1.obj === instance2.obj); // false
```
The expression is evaluated synchronously. You cannot use {{jsxref("Operators/await", "await")}} or {{jsxref("Operators/yield", "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.
```js
class Base {
constructor() {
console.log("Base constructor:", this.field);
}
}
class Derived extends Base {
field = 1;
constructor() {
super();
console.log("Derived constructor:", this.field);
this.field = 2;
}
}
const instance = new Derived();
// Base constructor: undefined
// Derived constructor: 1
console.log(instance.field); // 2
```
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.
```js
class C {
a = 1;
b = this.c;
c = this.a + 1;
d = this.c + 1;
}
const instance = new C();
console.log(instance.d); // 3
console.log(instance.b); // undefined
```
> **Note:** This is more important with [private fields](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties), because accessing a non-initialized private field throws a {{jsxref("TypeError")}}, even if the private field is declared below. (If the private field is not declared, it would be an early {{jsxref("SyntaxError")}}.)
Because class fields are added using the [`[[DefineOwnProperty]]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty) semantic (which is essentially {{jsxref("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.
```js
class Base {
set field(val) {
console.log(val);
}
}
class DerivedWithField extends Base {
field = 1;
}
const instance = new DerivedWithField(); // No log
class DerivedWithConstructor extends Base {
constructor() {
super();
this.field = 1;
}
}
const instance2 = new DerivedWithConstructor(); // Logs 1
```
> **Note:** Before the class fields specification was finalized with the `[[DefineOwnProperty]]` semantic, most transpilers, including [Babel](https://babeljs.io/) and [tsc](https://www.typescriptlang.org/), transformed class fields to the `DerivedWithConstructor` form, which has caused subtle bugs after class fields were standardized.
## Examples
### Using class fields
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 {{jsxref("Date.now()")}} or object initializers).
```js example-bad
class Person {
name = nameArg; // nameArg is out of scope of the constructor
constructor(nameArg) {}
}
```
```js example-good
class Person {
// All instances of Person will have the same name
name = "Dragomir";
}
```
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.
```js
class Person {
name;
age;
constructor(name, age) {
this.name = name;
this.age = age;
}
}
```
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.
```js
class Person {
name;
age;
constructor(properties) {
Object.assign(this, properties);
}
}
```
Because initializers are evaluated after the base class has executed, you can access properties created by the base class constructor.
```js
class Person {
name;
age;
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Professor extends Person {
name = `Professor ${this.name}`;
}
console.log(new Professor("Radev", 54).name); // "Professor Radev"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- [Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties)
- {{jsxref("Statements/class", "class")}}
- [The semantics of all JS class elements](https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html) by Shu-yu Guo (2018)
- [Public and private class fields](https://v8.dev/features/class-fields) on v8.dev (2018)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/static_initialization_blocks/index.md | ---
title: Static initialization blocks
slug: Web/JavaScript/Reference/Classes/Static_initialization_blocks
page-type: javascript-language-feature
browser-compat: javascript.classes.static_initialization_blocks
---
{{jsSidebar("Classes")}}
**Static initialization blocks** are declared within a {{jsxref("Statements/class", "class")}}. It contains statements to be evaluated during class initialization. This permits more flexible initialization logic than {{jsxref("Classes/static", "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++).
{{EmbedInteractiveExample("pages/js/classes-static-initialization.html")}}
## Syntax
```js-nolint
class ClassWithSIB {
static {
// β¦
}
}
```
## Description
Without static initialization blocks, complex static initialization might be achieved by calling a static method after the class declaration:
```js
class MyClass {
static init() {
// Access to private static fields is allowed here
}
}
MyClass.init();
```
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 {{jsxref("Statements/class", "class")}} can have any number of `static {}` initialization blocks in its class body.
These are [evaluated](/en-US/docs/Web/JavaScript/Reference/Classes#evaluation_order), 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.
```js
var y = "Outer y";
class A {
static field = "Inner y";
static {
var y = this.field;
}
}
// var defined in static block is not hoisted
console.log(y); // 'Outer y'
```
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 {{jsxref("Operators/super", "super()")}} in a class static initialization block, or to use the {{jsxref("Functions/arguments", "arguments")}} object.
The statements are evaluated synchronously. You cannot use {{jsxref("Operators/await", "await")}} or {{jsxref("Operators/yield", "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](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) declared within the class without causing a syntax error.
[Static field](/en-US/docs/Web/JavaScript/Reference/Classes/static) 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](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties), because accessing a non-initialized private field throws a {{jsxref("TypeError")}}, even if the private field is declared below. (If the private field is not declared, it would be an early {{jsxref("SyntaxError")}}.)
A static initialization block may not have decorators (the class itself may).
## Examples
### Multiple blocks
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.
```js
class MyClass {
static field1 = console.log("static field1");
static {
console.log("static block1");
}
static field2 = console.log("static field2");
static {
console.log("static block2");
}
}
// 'static field1'
// 'static block1'
// 'static field2'
// 'static block2'
```
Note that any static initialization of a super class is performed first, before that of its sub classes.
### Using this and super
The `this` inside a static block refers to the constructor object of the class.
This code shows how to access a public static field.
```js
class A {
static field = "static field";
static {
console.log(this.field);
}
}
// 'static field'
```
The [`super.property`](/en-US/docs/Web/JavaScript/Reference/Operators/super) syntax can be used inside a `static` block to reference static properties of a super class.
```js
class A {
static field = "static field";
}
class B extends A {
static {
console.log(super.field);
}
}
// 'static field'
```
### Access to private properties
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](https://v8.dev/features/class-static-initializer-blocks#access-to-private-fields)):
```js
let getDPrivateField;
class D {
#privateField;
constructor(v) {
this.#privateField = v;
}
static {
getDPrivateField = (d) => d.#privateField;
}
}
console.log(getDPrivateField(new D("private"))); // 'private'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- {{jsxref("Classes/static", "static")}}
- {{jsxref("Statements/class", "class")}}
- [Class static initialization blocks](https://v8.dev/features/class-static-initializer-blocks) on v8.dev (2021)
- [ES2022 feature: class static initialization blocks](https://2ality.com/2021/09/class-static-block.html) by Dr. Axel Rauschmayer (2021)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/extends/index.md | ---
title: extends
slug: Web/JavaScript/Reference/Classes/extends
page-type: javascript-language-feature
browser-compat: javascript.classes.extends
---
{{jsSidebar("Classes")}}
The **`extends`** keyword is used in [class declarations](/en-US/docs/Web/JavaScript/Reference/Statements/class) or [class expressions](/en-US/docs/Web/JavaScript/Reference/Operators/class) to create a class that is a child of another class.
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
## Syntax
```js-nolint
class ChildClass extends ParentClass { /* β¦ */ }
```
- `ParentClass`
- : An expression that evaluates to a constructor function (including a class) or `null`.
## Description
The `extends` keyword can be used to subclass custom classes as well as built-in objects.
Any constructor that can be called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) and has the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property can be the candidate for the parent class. The two conditions must both hold β for example, [bound functions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) and {{jsxref("Proxy")}} can be constructed, but they don't have a `prototype` property, so they cannot be subclassed.
```js
function OldStyleClass() {
this.someProperty = 1;
}
OldStyleClass.prototype.someMethod = function () {};
class ChildClass extends OldStyleClass {}
class ModernClass {
someProperty = 1;
someMethod() {}
}
class AnotherChildClass extends ModernClass {}
```
The `prototype` property of the `ParentClass` must be an {{jsxref("Object")}} or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/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`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator.)
```js
function ParentClass() {}
ParentClass.prototype = 3;
class ChildClass extends ParentClass {}
// Uncaught TypeError: Class extends value does not have valid prototype property 3
console.log(Object.getPrototypeOf(new ParentClass()));
// [Object: null prototype] {}
// Not actually a number!
```
`extends` sets the prototype for both `ChildClass` and `ChildClass.prototype`.
| | Prototype of `ChildClass` | Prototype of `ChildClass.prototype` |
| --------------------------------- | ------------------------- | ----------------------------------- |
| `extends` clause absent | `Function.prototype` | `Object.prototype` |
| [`extends null`](#extending_null) | `Function.prototype` | `null` |
| `extends ParentClass` | `ParentClass` | `ParentClass.prototype` |
```js
class ParentClass {}
class ChildClass extends ParentClass {}
// Allows inheritance of static properties
Object.getPrototypeOf(ChildClass) === ParentClass;
// Allows inheritance of instance properties
Object.getPrototypeOf(ChildClass.prototype) === ParentClass.prototype;
```
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](#mix-ins). The `this` value in the `extends` expression is the `this` surrounding the class definition, and referring to the class's name is a {{jsxref("ReferenceError")}} because the class is not initialized yet. {{jsxref("Operators/await", "await")}} and {{jsxref("Operators/yield", "yield")}} work as expected in this expression.
```js
class SomeClass extends class {
constructor() {
console.log("Base class");
}
} {
constructor() {
super();
console.log("Derived class");
}
}
new SomeClass();
// Base class
// Derived class
```
While the base class may return anything from its constructor, the derived class must return an object or `undefined`, or a {{jsxref("TypeError")}} will be thrown.
```js
class ParentClass {
constructor() {
return 1;
}
}
console.log(new ParentClass()); // ParentClass {}
// The return value is ignored because it's not an object
// This is consistent with function constructors
class ChildClass extends ParentClass {
constructor() {
super();
return 1;
}
}
console.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined
```
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](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields). This trick is called ["return overriding"](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties#returning_overriding_object), which allows a derived class's fields (including [private](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) ones) to be defined on unrelated objects.
### Subclassing built-ins
> **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](https://github.com/tc39/proposal-rm-builtin-subclassing). Consider using composition instead of inheritance when enhancing built-ins.
Here are some things you may expect when extending a class:
- When calling a static factory method (like {{jsxref("Promise.resolve()")}} or {{jsxref("Array.from()")}}) on a subclass, the returned instance is always an instance of the subclass.
- When calling an instance method that returns a new instance (like {{jsxref("Promise.prototype.then()")}} or {{jsxref("Array.prototype.map()")}}) on a subclass, the returned instance is always an instance of the subclass.
- Instance methods try to delegate to a minimal set of primitive methods where possible. For example, for a subclass of {{jsxref("Promise")}}, overriding {{jsxref("Promise/then", "then()")}} automatically causes the behavior of {{jsxref("Promise/catch", "catch()")}} to change; or for a subclass of {{jsxref("Map")}}, overriding {{jsxref("Map/set", "set()")}} automatically causes the behavior of the {{jsxref("Map/Map", "Map()")}} constructor to change.
However, the above expectations take non-trivial efforts to implement properly.
- The first one requires the static method to read the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) to get the constructor for constructing the returned instance. This means `[p1, p2, p3].map(Promise.resolve)` throws an error because the `this` inside `Promise.resolve` is `undefined`. A way to fix this is to fall back to the base class if `this` is not a constructor, like {{jsxref("Array.from()")}} does, but that still means the base class is special-cased.
- The second one requires the instance method to read [`this.constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) to get the constructor function. However, `new this.constructor()` may break legacy code, because the `constructor` property is both writable and configurable and is not protected in any way. Therefore, many copying built-in methods use the constructor's [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species) property instead (which by default just returns `this`, the constructor itself). However, `@@species` allows running arbitrary code and creating instances of arbitrary type, which poses a security concern and greatly complicates subclassing semantics.
- The third one leads to visible invocations of custom code, which makes a lot of optimizations harder to implement. For example, if the `Map()` constructor is called with an iterable of _x_ elements, then it must visibly invoke the `set()` method _x_ times, instead of just copying the elements into the internal storage.
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_](#avoiding_inheritance).
### Extending null
`extends null` was designed to allow easy creation of [objects that do not inherit from `Object.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects). 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](https://github.com/tc39/ecma262/pull/1321).
```js
new (class extends null {})();
// TypeError: Super constructor null of anonymous class is not a constructor
new (class extends null {
constructor() {}
})();
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
new (class extends null {
constructor() {
super();
}
})();
// TypeError: Super constructor null of anonymous class is not a constructor
```
Instead, you need to explicitly return an instance from the constructor.
```js
class NullClass extends null {
constructor() {
// Using new.target allows derived classes to
// have the correct prototype chain
return Object.create(new.target.prototype);
}
}
const proto = Object.getPrototypeOf;
console.log(proto(proto(new NullClass()))); // null
```
## Examples
### Using extends
The first example creates a class called `Square` from a class called `Polygon`. This example is extracted from this [live demo](https://googlechrome.github.io/samples/classes-es6/index.html) [(source)](https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html).
```js
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = "Square";
}
get area() {
return this.height * this.width;
}
}
```
### Extending plain objects
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 {{jsxref("Object.setPrototypeOf()")}}:
```js
const Animal = {
speak() {
console.log(`${this.name} makes a noise.`);
},
};
class Dog {
constructor(name) {
this.name = name;
}
}
Object.setPrototypeOf(Dog.prototype, Animal);
const d = new Dog("Mitzie");
d.speak(); // Mitzie makes a noise.
```
### Extending built-in objects
This example extends the built-in {{jsxref("Date")}} object. This example is extracted from this [live demo](https://googlechrome.github.io/samples/classes-es6/index.html) [(source)](https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html).
```js-nolint
class MyDate extends Date {
getFormattedDate() {
const months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
return `${this.getDate()}-${months[this.getMonth()]}-${this.getFullYear()}`;
}
}
```
### Extending `Object`
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 {{jsxref("Object.keys()")}}. However, because no `Object` static method uses the `this` value, there's still no value in inheriting these static methods.
The {{jsxref("Object/Object", "Object()")}} constructor special-cases the subclassing scenario. If it's implicitly called via [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super), it always initializes a new object with `new.target.prototype` as its prototype. Any value passed to `super()` is ignored.
```js
class C extends Object {
constructor(v) {
super(v);
}
}
console.log(new C(1) instanceof Number); // false
console.log(C.keys({ a: 1, b: 2 })); // [ 'a', 'b' ]
```
Compare this behavior with a custom wrapper that does not special-case subclassing:
```js
function MyObject(v) {
return new Object(v);
}
class D extends MyObject {
constructor(v) {
super(v);
}
}
console.log(new D(1) instanceof Number); // true
```
### Species
You might want to return {{jsxref("Array")}} objects in your derived array class `MyArray`. The species pattern lets you override default constructors.
For example, when using methods such as {{jsxref("Array.prototype.map()")}} that return the default constructor, you want these methods to return a parent `Array` object, instead of the `MyArray` object. The {{jsxref("Symbol.species")}} symbol lets you do this:
```js
class MyArray extends Array {
// Overwrite species to the parent Array constructor
static get [Symbol.species]() {
return Array;
}
}
const a = new MyArray(1, 2, 3);
const mapped = a.map((x) => x * x);
console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
```
This behavior is implemented by many built-in copying methods. For caveats of this feature, see the [subclassing built-ins](#subclassing_built-ins) discussion.
### Mix-ins
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:
```js
const calculatorMixin = (Base) =>
class extends Base {
calc() {}
};
const randomizerMixin = (Base) =>
class extends Base {
randomize() {}
};
```
A class that uses these mix-ins can then be written like this:
```js
class Foo {}
class Bar extends calculatorMixin(randomizerMixin(Foo)) {}
```
### Avoiding inheritance
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`:
```js
class ReadOnlyMap extends Map {
set() {
throw new TypeError("A read-only map must be set at construction time.");
}
}
```
It turns out that `ReadOnlyMap` is not constructible, because the [`Map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/Map) constructor calls the instance's `set()` method.
```js
const m = new ReadOnlyMap([["a", 1]]); // TypeError: A read-only map must be set at construction time.
```
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](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Circle%E2%80%93ellipse_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.
```js
class ReadOnlyMap {
#data;
constructor(values) {
this.#data = new Map(values);
}
get(key) {
return this.#data.get(key);
}
has(key) {
return this.#data.has(key);
}
get size() {
return this.#data.size;
}
*keys() {
yield* this.#data.keys();
}
*values() {
yield* this.#data.values();
}
*entries() {
yield* this.#data.entries();
}
*[Symbol.iterator]() {
yield* this.#data[Symbol.iterator]();
}
}
```
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](#subclassing_built-ins). For example, if the `Map` class adds an [`emplace()`](https://github.com/tc39/proposal-upsert) 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.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- {{jsxref("Classes/constructor", "constructor")}}
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Operators/super", "super")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/static/index.md | ---
title: static
slug: Web/JavaScript/Reference/Classes/static
page-type: javascript-language-feature
browser-compat: javascript.classes.static
---
{{jsSidebar("Classes")}}
The **`static`** keyword defines a [static method or field](/en-US/docs/Web/JavaScript/Reference/Classes#static_methods_and_fields) for a class, or a [static initialization block](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) (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](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) interchangeably.
{{EmbedInteractiveExample("pages/js/classes-static.html", "taller")}}
## Syntax
```js-nolint
class ClassWithStatic {
static staticField;
static staticFieldWithInitializer = value;
static staticMethod() {
// β¦
}
}
```
There are some additional syntax restrictions:
- The name of a static property (field or method) cannot be `prototype`.
- The name of a class field (static or instance) cannot be `constructor`.
## Description
This page introduces public static properties of classes, which include static methods, static accessors, and static fields.
- For private static features, see [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
- For instance features, see [methods definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get), [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set), and [public class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields).
Public static features are declared using the `static` keyword. They are added to the class constructor at the time of [class evaluation](/en-US/docs/Web/JavaScript/Reference/Classes#evaluation_order) using the [`[[DefineOwnProperty]]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty) semantic (which is essentially {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names). The `this` value in the computed expression is the `this` surrounding the class definition, and referring to the class's name is a {{jsxref("ReferenceError")}} because the class is not initialized yet. {{jsxref("Operators/await", "await")}} and {{jsxref("Operators/yield", "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.
```js
class ClassWithStaticField {
static staticField;
static staticFieldWithInitializer = "static field";
}
class SubclassWithStaticField extends ClassWithStaticField {
static subStaticField = "subclass field";
}
console.log(Object.hasOwn(ClassWithStaticField, "staticField")); // true
console.log(ClassWithStaticField.staticField); // undefined
console.log(ClassWithStaticField.staticFieldWithInitializer); // "static field"
console.log(SubclassWithStaticField.staticFieldWithInitializer); // "static field"
console.log(SubclassWithStaticField.subStaticField); // "subclass field"
```
In the field initializer, [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) refers to the current class (which you can also access through its name), and [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) refers to the base class constructor.
```js
class ClassWithStaticField {
static baseStaticField = "base static field";
static anotherBaseStaticField = this.baseStaticField;
static baseStaticMethod() {
return "base static method output";
}
}
class SubClassWithStaticField extends ClassWithStaticField {
static subStaticField = super.baseStaticMethod();
}
console.log(ClassWithStaticField.anotherBaseStaticField); // "base static field"
console.log(SubClassWithStaticField.subStaticField); // "base static method output"
```
The expression is evaluated synchronously. You cannot use {{jsxref("Operators/await", "await")}} or {{jsxref("Operators/yield", "yield")}} in the initializer expression. (Think of the initializer expression as being implicitly wrapped in a function.)
Static field initializers and [static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/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](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties), because accessing a non-initialized private field throws a {{jsxref("TypeError")}}, even if the private field is declared below. (If the private field is not declared, it would be an early {{jsxref("SyntaxError")}}.)
## Examples
### Using static members in classes
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.
```js
class Triple {
static customName = "Tripler";
static description = "I triple any number you provide";
static calculate(n = 1) {
return n * 3;
}
}
class SquaredTriple extends Triple {
static longDescription;
static description = "I square the triple of any number you provide";
static calculate(n) {
return super.calculate(n) * super.calculate(n);
}
}
console.log(Triple.description); // 'I triple any number you provide'
console.log(Triple.calculate()); // 3
console.log(Triple.calculate(6)); // 18
const tp = new Triple();
console.log(SquaredTriple.calculate(3)); // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description); // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName); // 'Tripler'
// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate()); // 'tp.calculate is not a function'
```
### Calling static members from another static method
In order to call a static method or property within another static method of the same class, you can use the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) keyword.
```js
class StaticMethodCall {
static staticProperty = "static property";
static staticMethod() {
return `Static method and ${this.staticProperty} has been called`;
}
static anotherStaticMethod() {
return `${this.staticMethod()} from another static method`;
}
}
StaticMethodCall.staticMethod();
// 'Static method and static property has been called'
StaticMethodCall.anotherStaticMethod();
// 'Static method and static property has been called from another static method'
```
### Calling static members from a class constructor and other methods
Static members are not directly accessible using the {{jsxref("Operators/this", "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`
```js
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticProperty); // 'static property'
console.log(this.constructor.staticProperty); // 'static property'
console.log(StaticMethodCall.staticMethod()); // 'static method has been called.'
console.log(this.constructor.staticMethod()); // 'static method has been called.'
}
static staticProperty = "static property";
static staticMethod() {
return "static method has been called.";
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- [Static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks)
- {{jsxref("Statements/class", "class")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/constructor/index.md | ---
title: constructor
slug: Web/JavaScript/Reference/Classes/constructor
page-type: javascript-language-feature
browser-compat: javascript.classes.constructor
---
{{jsSidebar("Classes")}}
The **`constructor`** method is a special method of a [class](/en-US/docs/Web/JavaScript/Reference/Classes) 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 {{jsxref("Object.prototype.constructor")}}.
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
## Syntax
```js-nolint
constructor() { /* β¦ */ }
constructor(argument0) { /* β¦ */ }
constructor(argument0, argument1) { /* β¦ */ }
constructor(argument0, argument1, /* β¦, */ argumentN) { /* β¦ */ }
```
There are some additional syntax restrictions:
- A class method called `constructor` cannot be a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get), [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set), [async](/en-US/docs/Web/JavaScript/Reference/Statements/async_function), or [generator](/en-US/docs/Web/JavaScript/Reference/Statements/function*).
- A class cannot have more than one `constructor` method.
## Description
A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.
```js
class Person {
constructor(name) {
this.name = name;
}
introduce() {
console.log(`Hello, my name is ${this.name}`);
}
}
const otto = new Person("Otto");
otto.introduce(); // Hello, my name is Otto
```
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:
```js-nolint
constructor() {}
```
If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:
```js-nolint
constructor(...args) {
super(...args);
}
```
> **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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) through [argument spreading](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
That enables code like this to work:
```js
class ValidationError extends Error {
printCustomerMessage() {
return `Validation failed :-( (details: ${this.message})`;
}
}
try {
throw new ValidationError("Not a valid phone number");
} catch (error) {
if (error instanceof ValidationError) {
console.log(error.name); // This is Error instead of ValidationError!
console.log(error.printCustomerMessage());
} else {
console.log("Unknown error", error);
throw error;
}
}
```
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()`](/en-US/docs/Web/JavaScript/Reference/Operators/super).
For example:
```js
class ValidationError extends Error {
constructor(message) {
super(message); // call parent class constructor
this.name = "ValidationError";
this.code = "42";
}
printCustomerMessage() {
return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
}
}
try {
throw new ValidationError("Not a valid phone number");
} catch (error) {
if (error instanceof ValidationError) {
console.log(error.name); // Now this is ValidationError!
console.log(error.printCustomerMessage());
} else {
console.log("Unknown error", error);
throw error;
}
}
```
Using [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_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`](/en-US/docs/Web/JavaScript/Reference/Operators/this) and access the class that is called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) through [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target). Note that methods (including [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set)) and the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_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`.
```js example-bad
new (class C extends class B {
constructor() {
console.log(this.foo());
}
} {
#a = 1;
foo() {
return this.#a; // TypeError: Cannot read private member #a from an object whose class did not declare it
// It's not really because the class didn't declare it,
// but because the private field isn't initialized yet
// when the superclass constructor is running
}
})();
```
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 {{jsxref("TypeError")}} will be thrown.
```js
class ParentClass {
constructor() {
return 1;
}
}
console.log(new ParentClass()); // ParentClass {}
// The return value is ignored because it's not an object
// This is consistent with function constructors
class ChildClass extends ParentClass {
constructor() {
return 1;
}
}
console.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined
```
If the parent class constructor returns an object, that object will be used as the `this` value on which [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) of the derived class will be defined. This trick is called ["return overriding"](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties#returning_overriding_object), which allows a derived class's fields (including [private](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) ones) to be defined on unrelated objects.
The `constructor` follows normal [method](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) syntax, so [parameter default values](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), etc. can all be used.
```js
class Person {
constructor(name = "Anonymous") {
this.name = name;
}
introduce() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person();
person.introduce(); // Hello, my name is Anonymous
```
The constructor must be a literal name. Computed properties cannot become constructors.
```js
class Foo {
// This is a computed property. It will not be picked up as a constructor.
["constructor"]() {
console.log("called");
this.a = 1;
}
}
const foo = new Foo(); // No log
console.log(foo); // Foo {}
foo.constructor(); // Logs "called"
console.log(foo); // Foo { a: 1 }
```
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.
## Examples
### Using the constructor
This code snippet is taken from the [classes sample](https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html) ([live demo](https://googlechrome.github.io/samples/classes-es6/index.html)).
```js
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// NOTE: In derived classes, `super()` must be called before you
// can use `this`. Leaving this out will cause a ReferenceError.
this.name = "Square";
}
get area() {
return this.height * this.width;
}
set area(value) {
this.height = value ** 0.5;
this.width = value ** 0.5;
}
}
```
### Calling super in a constructor bound to a different prototype
`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.
```js
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Rectangle {
constructor() {
this.name = "Rectangle";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
// Make Square extend Rectangle (which is a base class) instead of Polygon
Object.setPrototypeOf(Square, Rectangle);
const newInstance = new Square();
// newInstance is still an instance of Polygon, because we didn't
// change the prototype of Square.prototype, so the prototype chain
// of newInstance is still
// newInstance --> Square.prototype --> Polygon.prototype
console.log(newInstance instanceof Polygon); // true
console.log(newInstance instanceof Rectangle); // false
// However, because super() calls Rectangle as constructor, the name property
// of newInstance is initialized with the logic in Rectangle
console.log(newInstance.name); // Rectangle
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- [Static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks)
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Operators/super", "super()")}}
- {{jsxref("Object.prototype.constructor")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/classes | data/mdn-content/files/en-us/web/javascript/reference/classes/private_properties/index.md | ---
title: Private properties
slug: Web/JavaScript/Reference/Classes/Private_properties
page-type: javascript-language-feature
browser-compat:
- javascript.classes.private_class_fields
- javascript.classes.private_class_fields_in
- javascript.classes.private_class_methods
---
{{jsSidebar("Classes")}}
**Private properties** are counterparts of the regular class properties which are public, including [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields), class methods, etc. Private properties get created by using a hash `#` prefix and cannot be legally referenced outside of the class. The privacy encapsulation of these class properties is enforced by JavaScript itself.
Private properties were not native to the language before this syntax existed. In prototypal inheritance, its behavior may be emulated with [`WeakMap`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap#emulating_private_members) objects or [closures](/en-US/docs/Web/JavaScript/Closures#emulating_private_methods_with_closures), but they can't compare to the `#` syntax in terms of ergonomics.
## Syntax
```js-nolint
class ClassWithPrivate {
#privateField;
#privateFieldWithInitializer = 42;
#privateMethod() {
// β¦
}
static #privateStaticField;
static #privateStaticFieldWithInitializer = 42;
static #privateStaticMethod() {
// β¦
}
}
```
There are some additional syntax restrictions:
- All private identifiers declared within a class must be unique. The namespace is shared between static and instance properties. The only exception is when the two declarations define a getter-setter pair.
- The private identifier cannot be `#constructor`.
## Description
Most class properties have their private counterparts:
- Private fields
- Private methods
- Private static fields
- Private static methods
- Private getters
- Private setters
- Private static getters
- Private static setters
These features are collectively called _private properties_. However, [constructors](/en-US/docs/Web/JavaScript/Reference/Classes/constructor) cannot be private in JavaScript. To prevent classes from being constructed outside of the class, you have to [use a private flag](#simulating_private_constructors).
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](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#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`](/en-US/docs/Web/JavaScript/Reference/Operators/delete).
```js-nolint example-bad
class ClassWithPrivateField {
#privateField;
constructor() {;
delete this.#privateField; // Syntax error
this.#undeclaredField = 42; // Syntax error
}
}
const instance = new ClassWithPrivateField();
instance.#privateField; // Syntax error
```
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 {{jsxref("TypeError")}} is thrown, instead of returning `undefined` as normal properties do.
```js example-bad
class C {
#x;
static getX(obj) {
return obj.#x;
}
}
console.log(C.getX(new C())); // undefined
console.log(C.getX({})); // TypeError: Cannot read private member #x from an object whose class did not declare it
```
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`](/en-US/docs/Web/JavaScript/Reference/Operators/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.
```js example-good
class C {
#x;
constructor(x) {
this.#x = x;
}
static getX(obj) {
if (#x in obj) return obj.#x;
return "obj must be an instance of C";
}
}
console.log(C.getX(new C("foo"))); // "foo"
console.log(C.getX(new C(0.196))); // 0.196
console.log(C.getX(new C(new Date()))); // the current date and time
console.log(C.getX({})); // "obj must be an instance of C"
```
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](#returning_overriding_object)).
Private properties are not part of the [prototypical inheritance](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) 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, {{jsxref("Object.freeze()")}} and {{jsxref("Object.seal()")}} have no effect on private properties.
For more information on how and when private fields are initialized, see [public class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields).
## Examples
### Private fields
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:
- are added before the constructor runs in a base class, or immediately after [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super) is invoked in a subclass, and
- are only available on instances of the class.
```js
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
}
}
class Subclass extends ClassWithPrivateField {
#subPrivateField;
constructor() {
super();
this.#subPrivateField = 23;
}
}
new Subclass(); // In some dev tools, it shows Subclass {#privateField: 42, #subPrivateField: 23}
```
> **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.
```js
class Stamper extends class {
// A base class whose constructor returns the object it's given
constructor(obj) {
return obj;
}
} {
// This declaration will "stamp" the private field onto the object
// returned by the base class constructor
#stamp = 42;
static getStamp(obj) {
return obj.#stamp;
}
}
const obj = {};
new Stamper(obj);
// `Stamper` calls `Base`, which returns `obj`, so `obj` is
// now the `this` value. `Stamper` then defines `#stamp` on `obj`
console.log(obj); // In some dev tools, it shows {#stamp: 42}
console.log(Stamper.getStamp(obj)); // 42
console.log(obj instanceof Stamper); // false
// You cannot stamp private properties twice
new Stamper(obj); // Error: Initializing an object twice is an error with private fields
```
> **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:
- are added to the class constructor at class evaluation time, and
- are only available on the class itself.
```js
class ClassWithPrivateStaticField {
static #privateStaticField = 42;
static publicStaticMethod() {
return ClassWithPrivateStaticField.#privateStaticField;
}
}
console.log(ClassWithPrivateStaticField.publicStaticMethod()); // 42
```
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`](/en-US/docs/Web/JavaScript/Reference/Operators/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`.
```js
class ClassWithPrivateStaticField {
static #privateStaticField = 42;
static publicStaticMethod() {
return this.#privateStaticField;
}
}
class Subclass extends ClassWithPrivateStaticField {}
Subclass.publicStaticMethod(); // TypeError: Cannot read private member #privateStaticField from an object whose class did not declare it
```
This is the same if you call the method with `super`, because [`super` methods are not called with the super class as `this`](/en-US/docs/Web/JavaScript/Reference/Operators/super#calling_methods_from_super).
```js
class ClassWithPrivateStaticField {
static #privateStaticField = 42;
static publicStaticMethod() {
// When invoked through super, `this` still refers to Subclass
return this.#privateStaticField;
}
}
class Subclass extends ClassWithPrivateStaticField {
static callSuperMethod() {
return super.publicStaticMethod();
}
}
Subclass.callSuperMethod(); // TypeError: Cannot read private member #privateStaticField from an object whose class did not declare it
```
You are advised to always access private static fields through the class name, not through `this`, so inheritance doesn't break the method.
### Private methods
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:
- are installed immediately before the instance fields are installed, and
- are only available on instances of the class, not on its `.prototype` property.
```js
class ClassWithPrivateMethod {
#privateMethod() {
return 42;
}
publicMethod() {
return this.#privateMethod();
}
}
const instance = new ClassWithPrivateMethod();
console.log(instance.publicMethod()); // 42
```
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](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) counterparts.
```js
class ClassWithPrivateAccessor {
#message;
get #decoratedMessage() {
return `π¬${this.#message}π`;
}
set #decoratedMessage(msg) {
this.#message = msg;
}
constructor() {
this.#decoratedMessage = "hello world";
console.log(this.#decoratedMessage);
}
}
new ClassWithPrivateAccessor(); // π¬hello worldπ
```
Unlike public methods, private methods are not accessible on the `.prototype` property of their class.
```js
class C {
#method() {}
static getMethod(x) {
return x.#method;
}
}
console.log(C.getMethod(new C())); // [Function: #method]
console.log(C.getMethod(C.prototype)); // TypeError: Receiver must be an instance of class C
```
#### Private static methods
Like their public counterparts, private static methods:
- are added to the class constructor at class evaluation time, and
- are only available on the class itself.
```js
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod() {
return ClassWithPrivateStaticMethod.#privateStaticMethod();
}
}
console.log(ClassWithPrivateStaticMethod.publicStaticMethod()); // 42
```
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`.
```js
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod() {
return this.#privateStaticMethod();
}
}
class Subclass extends ClassWithPrivateStaticMethod {}
console.log(Subclass.publicStaticMethod()); // TypeError: Cannot read private member #privateStaticMethod from an object whose class did not declare it
```
### Simulating private constructors
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.
```js
class PrivateConstructor {
static #isInternalConstructing = false;
constructor() {
if (!PrivateConstructor.#isInternalConstructing) {
throw new TypeError("PrivateConstructor is not constructable");
}
PrivateConstructor.#isInternalConstructing = false;
// More initialization logic
}
static create() {
PrivateConstructor.#isInternalConstructing = true;
const instance = new PrivateConstructor();
return instance;
}
}
new PrivateConstructor(); // TypeError: PrivateConstructor is not constructable
PrivateConstructor.create(); // PrivateConstructor {}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using classes](/en-US/docs/Web/JavaScript/Guide/Using_classes) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- [Public class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields)
- {{jsxref("Statements/class", "class")}}
- [Private Syntax FAQ](https://github.com/tc39/proposal-class-fields/blob/main/PRIVATE_SYNTAX_FAQ.md) in the TC39 class-fields proposal
- [The semantics of all JS class elements](https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html) by Shu-yu Guo (2018)
- [Public and private class fields](https://v8.dev/features/class-fields) on v8.dev (2018)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/errors/index.md | ---
title: JavaScript error reference
slug: Web/JavaScript/Reference/Errors
page-type: landing-page
---
{{jsSidebar("Errors")}}
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 {{jsxref("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](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong).
## List of errors
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!
{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/unexpected_token/index.md | ---
title: "SyntaxError: Unexpected token"
slug: Web/JavaScript/Reference/Errors/Unexpected_token
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exceptions "unexpected token" occur when a specific language construct
was expected, but something else was provided. This might be a simple typo.
## Message
```plain
SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
A specific language construct was expected, but something else was provided. This might
be a simple typo.
## Examples
### Expression expected
For example, when chaining expressions, trailing commas are not allowed.
```js-nolint example-bad
for (let i = 0; i < 5,; ++i) {
console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'
```
Correct would be omitting the comma or adding another expression:
```js example-good
for (let i = 0; i < 5; ++i) {
console.log(i);
}
```
### Not enough parentheses
Sometimes, you leave out parentheses around `if` statements:
```js-nolint example-bad
function round(n, upperBound, lowerBound) {
if (n > upperBound) || (n < lowerBound) { // Not enough parenthese here!
throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
} else if (n < (upperBound + lowerBound) / 2) {
return lowerBound;
} else {
return upperBound;
}
} // SyntaxError: expected expression, got '||'
```
The parentheses may look correct at first, but note how the `||` is outside the
parentheses. Correct would be putting parentheses around the `||`:
```js-nolint example-good
function round(n, upperBound, lowerBound) {
if ((n > upperBound) || (n < lowerBound)) {
throw new Error(
`Number ${n} is more than ${upperBound} or less than ${lowerBound}`,
);
} else if (n < (upperBound + lowerBound) / 2) {
return lowerBound;
} else {
return upperBound;
}
}
```
## See also
- {{jsxref("SyntaxError")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_const_assignment/index.md | ---
title: 'TypeError: invalid assignment to const "x"'
slug: Web/JavaScript/Reference/Errors/Invalid_const_assignment
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid assignment to const" occurs when it was attempted to
alter a constant value. JavaScript
[`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const)
declarations can't be re-assigned or redeclared.
## Message
```plain
TypeError: Assignment to constant variable. (V8-based)
TypeError: invalid assignment to const 'x' (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
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`](/en-US/docs/Web/JavaScript/Reference/Statements/const)
keyword.
## Examples
### Invalid redeclaration
Assigning a value to the same constant name in the same block-scope will throw.
```js example-bad
const COLUMNS = 80;
// β¦
COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'
```
### Fixing the error
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.
```js example-good
const COLUMNS = 80;
const WIDE_COLUMNS = 120;
```
#### 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`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or
global variable with
[`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var).
```js example-good
let columns = 80;
// β¦
columns = 120;
```
#### 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?
```js example-good
const COLUMNS = 80;
function setupBigScreenEnvironment() {
const COLUMNS = 120;
}
```
### const and immutability
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:
```js example-bad
const obj = { foo: "bar" };
obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'
```
But you can mutate the properties in a variable:
```js example-good
obj.foo = "baz";
obj; // { foo: "baz" }
```
## See also
- [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const)
- [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let)
- [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/already_has_pragma/index.md | ---
title: "Warning: -file- is being assigned a //# sourceMappingURL, but already has one"
slug: Web/JavaScript/Reference/Errors/Already_has_pragma
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
Warning: -file- is being assigned a //# sourceMappingURL, but already has one.
```
## Error type
A warning. JavaScript execution won't be halted.
## What went wrong?
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](https://developer.chrome.com/blog/sourcemaps/), 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.
## Examples
### Setting source maps
Setting a source map by using a comment in the file:
```js example-good
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
Or, alternatively, you can set a header to your JavaScript file:
```http example-good
X-SourceMap: /path/to/file.js.map
```
## See also
- [Use a source map](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html) in the Firefox source docs
- [Introduction to JavaScript source maps](https://developer.chrome.com/blog/sourcemaps/) on developer.chrome.com (2012)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/json_bad_parse/index.md | ---
title: "SyntaxError: JSON.parse: bad parsing"
slug: Web/JavaScript/Reference/Errors/JSON_bad_parse
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exceptions thrown by {{jsxref("JSON.parse()")}} occur when string failed
to be parsed as JSON.
## Message
```plain
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
{{jsxref("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
### JSON.parse() does not allow trailing commas
Both lines will throw a SyntaxError:
```js example-bad
JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
```
Omit the trailing commas to parse the JSON correctly:
```js example-good
JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');
```
### Property names must be double-quoted strings
You cannot use single-quotes around properties, like 'foo'.
```js example-bad
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
```
Instead write "foo":
```js example-good
JSON.parse('{"foo": 1}');
```
### Leading zeros and decimal points
You cannot use leading zeros, like 01, and decimal points must be followed by at least
one digit.
```js example-bad
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data
JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data
```
Instead write just 1 without a zero and use at least one digit after a decimal point:
```js example-good
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
```
## See also
- {{jsxref("JSON")}}
- {{jsxref("JSON.parse()")}}
- {{jsxref("JSON.stringify()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/delete_in_strict_mode/index.md | ---
title: "SyntaxError: applying the 'delete' operator to an unqualified name is deprecated"
slug: Web/JavaScript/Reference/Errors/Delete_in_strict_mode
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/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`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator.
## Message
```plain
SyntaxError: Delete of an unqualified identifier in strict mode. (V8-based)
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)
SyntaxError: Cannot delete unqualified property 'a' in strict mode. (Safari)
```
## Error type
{{jsxref("SyntaxError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
Normal variables in JavaScript can't be deleted using the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/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](/en-US/docs/Web/JavaScript/Memory_management) page and the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator page for more details.
This error only happens in [strict mode code](/en-US/docs/Web/JavaScript/Reference/Strict_mode). In non-strict code, the operation just returns `false`.
## Examples
### Freeing the contents of a variable
Attempting to delete a plain variable throws an error in strict mode:
```js-nolint example-bad
"use strict";
var x;
// β¦
delete x;
// SyntaxError: applying the 'delete' operator to an unqualified name
// is deprecated
```
To free the contents of a variable, you can set it to [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null):
```js example-good
"use strict";
var x;
// β¦
x = null;
// x can be garbage collected
```
## See also
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- [Memory management](/en-US/docs/Web/JavaScript/Memory_management)
- [TypeError: property "x" is non-configurable and can't be deleted](/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_for-in_initializer/index.md | ---
title: "SyntaxError: for-in loop head declarations may not have initializers"
slug: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)-only exception
"for-in loop head declarations may not have initializers"
occurs when the head of a [for...in](/en-US/docs/Web/JavaScript/Reference/Statements/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.
## Message
```plain
SyntaxError: for-in loop variable declaration may not have an initializer. (V8-based)
SyntaxError: for-in loop head declarations may not have initializers (Firefox)
SyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-in loop header. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
The head of a [for...in](/en-US/docs/Web/JavaScript/Reference/Statements/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](/en-US/docs/Web/JavaScript/Reference/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
This example throws a `SyntaxError`:
```js-nolint example-bad
const obj = { a: 1, b: 2, c: 3 };
for (const i = 0 in obj) {
console.log(obj[i]);
}
// SyntaxError: for-in loop head declarations may not have initializers
```
### Valid for-in loop
You can remove the initializer (`i = 0`) in the head of the for-in loop.
```js example-good
const obj = { a: 1, b: 2, c: 3 };
for (const i in obj) {
console.log(obj[i]);
}
```
### Array iteration
The for...in loop [shouldn't be used for Array iteration](/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in).
Did you intend to use a [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for) loop
instead of a `for-in` loop to iterate an {{jsxref("Array")}}? The
`for` loop allows you to set an initializer then as well:
```js example-good
const arr = ["a", "b", "c"];
for (let i = 2; i < arr.length; i++) {
console.log(arr[i]);
}
// "c"
```
## See also
- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
- [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/in_operator_no_object/index.md | ---
title: "TypeError: cannot use 'in' operator to search for 'x' in 'y'"
slug: Web/JavaScript/Reference/Errors/in_operator_no_object
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "right-hand side of 'in' should be an object" occurs when the
[`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in)
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.
## Message
```plain
TypeError: Cannot use 'in' operator to search for 'x' in 'y' (V8-based & Firefox)
TypeError: right-hand side of 'in' should be an object, got null (Firefox)
TypeError: "y" is not an Object. (evaluating '"x" in "y"') (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
The [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in) 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
### Searching in strings
Unlike in other programming languages (e.g. Python), you can't search in strings using
the [`in` operator](/en-US/docs/Web/JavaScript/Reference/Operators/in).
```js example-bad
"Hello" in "Hello World";
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'
```
Instead you will need to use {{jsxref("String.prototype.includes()")}}, for example.
```js example-good
"Hello World".includes("Hello");
// true
```
### The operand can't be null or undefined
Make sure the object you are inspecting isn't actually [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or
{{jsxref("undefined")}}.
```js example-bad
const foo = null;
"bar" in foo;
// TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome)
// TypeError: right-hand side of 'in' should be an object, got null (Firefox)
```
The `in` operator always expects an object.
```js example-good
const foo = { baz: "bar" };
"bar" in foo; // false
"PI" in Math; // true
"pi" in Math; // false
```
### Searching in arrays
Be careful when using the `in` operator to search in {{jsxref("Array")}}
objects. The `in` operator checks the index number, not the value at that
index.
```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
3 in trees; // true
"oak" in trees; // false
```
## See also
- [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_initializer_in_const/index.md | ---
title: "SyntaxError: missing = in const declaration"
slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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"`).
## Message
```plain
SyntaxError: Missing initializer in const declaration (V8-based)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
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`](/en-US/docs/Web/JavaScript/Reference/Statements/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
### Missing const initializer
Unlike `var` or `let`, you must specify a value for a
`const` declaration. This throws:
```js-nolint example-bad
const COLUMNS;
// SyntaxError: missing = in const declaration
```
### Fixing the error
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:
```js example-good
const COLUMNS = 80;
```
#### `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`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or
global variable with
[`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var). Both
don't require an initial value.
```js example-good
let columns;
```
## See also
- [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const)
- [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let)
- [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_assign_to_property/index.md | ---
title: 'TypeError: can''t assign to property "x" on "y": not an object'
slug: Web/JavaScript/Reference/Errors/Cant_assign_to_property
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript strict mode exception "can't assign to property" occurs when attempting
to create a property on [primitive](/en-US/docs/Glossary/Primitive) value
such as a [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), a [string](/en-US/docs/Glossary/String), a [number](/en-US/docs/Glossary/Number) or a [boolean](/en-US/docs/Glossary/Boolean). [Primitive](/en-US/docs/Glossary/Primitive) values cannot hold any [property](/en-US/docs/Glossary/Property/JavaScript).
## Message
```plain
TypeError: Cannot create property 'x' on number '1' (V8-based)
TypeError: can't assign to property "x" on 1: not an object (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), a {{jsxref("TypeError")}} is raised when attempting to
create a property on [primitive](/en-US/docs/Glossary/Primitive) value such
as a [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), a [string](/en-US/docs/Glossary/String), a [number](/en-US/docs/Glossary/Number) or a [boolean](/en-US/docs/Glossary/Boolean). [Primitive](/en-US/docs/Glossary/Primitive) values cannot hold any [property](/en-US/docs/Glossary/Property/JavaScript).
The problem might be that an unexpected value is flowing at an unexpected place, or
that an object variant of a {{jsxref("String")}} or a {{jsxref("Number")}} is expected.
## Examples
### Invalid cases
```js example-bad
"use strict";
const foo = "my string";
// The following line does nothing if not in strict mode.
foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
```
### Fixing the issue
Either fix the code to prevent the [primitive](/en-US/docs/Glossary/Primitive) from being used in such places, or fix the issue by creating the object equivalent {{jsxref("Object")}}.
```js example-good
"use strict";
const foo = new String("my string");
foo.bar = {};
```
## See also
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- [primitive](/en-US/docs/Glossary/Primitive)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/called_on_incompatible_type/index.md | ---
title: "TypeError: X.prototype.y called on incompatible type"
slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
TypeError: Method Set.prototype.add called on incompatible receiver undefined (V8-based)
TypeError: Bind must be called on a function (V8-based)
TypeError: Function.prototype.toString called on incompatible object (Firefox)
TypeError: Function.prototype.bind called on incompatible target (Firefox)
TypeError: Type error (Safari)
TypeError: undefined is not an object (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
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 {{jsxref("Function.prototype.call()")}} or
{{jsxref("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 {{jsxref("Function.prototype.bind()")}} function to
force the `this` argument to the expected object.
## Examples
### Invalid cases
```js example-bad
const mySet = new Set();
["bar", "baz"].forEach(mySet.add);
// mySet.add is a function, but "mySet" is not captured as this.
const myFun = function () {
console.log(this);
};
["bar", "baz"].forEach(myFun.bind);
// myFun.bind is a function, but "myFun" is not captured as this.
```
### Valid cases
```js example-good
const mySet = new Set();
["bar", "baz"].forEach(mySet.add.bind(mySet));
// This works due to binding "mySet" as this.
const myFun = function () {
console.log(this);
};
["bar", "baz"].forEach((x) => myFun.bind(x));
// This works using the "bind" function. It creates a lambda forwarding the argument.
```
## See also
- {{jsxref("Function.prototype.call()")}}
- {{jsxref("Function.prototype.apply()")}}
- {{jsxref("Function.prototype.bind()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_curly_after_function_body/index.md | ---
title: "SyntaxError: missing } after function body"
slug: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
SyntaxError: missing } after function body (Firefox)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
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
### Forgotten closing curly bracket
Oftentimes, there is a missing curly bracket in your function code:
```js-nolint example-bad
function charge() {
if (sunny) {
useSolarCells();
} else {
promptBikeRide();
}
```
Correct would be:
```js example-good
function charge() {
if (sunny) {
useSolarCells();
} else {
promptBikeRide();
}
}
```
It can be more obscure when using [IIFEs](/en-US/docs/Glossary/IIFE) or other constructs that use
a lot of different parenthesis and curly braces, for example.
```js-nolint example-bad
(function () {
if (Math.random() < 0.01) {
doSomething();
}
)();
```
Oftentimes, indenting differently or double checking indentation helps to spot these
errors.
```js example-good
(function () {
if (Math.random() < 0.01) {
doSomething();
}
})();
```
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/getter_only/index.md | ---
title: 'TypeError: setting getter-only property "x"'
slug: Web/JavaScript/Reference/Errors/Getter_only
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/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](/en-US/docs/Web/JavaScript/Reference/Functions/get) is specified.
## Message
```plain
TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
## Error type
{{jsxref("TypeError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
There is an attempt to set a new value to a property for which only a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) is specified.
While this will be silently ignored in non-strict mode, it will throw a
{{jsxref("TypeError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
## Examples
### Property with no setter
The example below shows how to set a getter for a property.
It doesn't specify a [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set), so a
`TypeError` will be thrown upon trying to set the `temperature`
property to `30`. For more details see also the
{{jsxref("Object.defineProperty()")}} page.
```js example-bad
"use strict";
function Archiver() {
const temperature = null;
Object.defineProperty(this, "temperature", {
get() {
console.log("get!");
return temperature;
},
});
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 30;
// TypeError: setting getter-only property "temperature"
```
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](/en-US/docs/Web/JavaScript/Reference/Functions/set) for it, for
example like this:
```js example-good
"use strict";
function Archiver() {
let temperature = null;
const archive = [];
Object.defineProperty(this, "temperature", {
get() {
console.log("get!");
return temperature;
},
set(value) {
temperature = value;
archive.push({ val: temperature });
},
});
this.getArchive = function () {
return archive;
};
}
const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```
## See also
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.defineProperties()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_return/index.md | ---
title: "SyntaxError: return not in function"
slug: Web/JavaScript/Reference/Errors/Bad_return
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "return not in function" occurs when a [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement is called outside of a [function](/en-US/docs/Web/JavaScript/Guide/Functions).
## Message
```plain
SyntaxError: Illegal return statement (V8-based)
SyntaxError: return not in function (Firefox)
SyntaxError: Return statements are only valid inside functions. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
A [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement is called outside of a [function](/en-US/docs/Web/JavaScript/Guide/Functions). 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
### Missing curly braces
```js-nolint example-bad
function cheer(score) {
if (score === 147)
return "Maximum!";
}
if (score > 100) {
return "Century!";
}
}
// SyntaxError: return not in function
```
The curly braces look correct at a first glance, but this code snippet is missing a `{` after the first `if` statement. Correct would be:
```js example-good
function cheer(score) {
if (score === 147) {
return "Maximum!";
}
if (score > 100) {
return "Century!";
}
}
```
## See also
- [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/resulting_string_too_large/index.md | ---
title: "RangeError: repeat count must be less than infinity"
slug: Web/JavaScript/Reference/Errors/Resulting_string_too_large
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "repeat count must be less than infinity" occurs when the
{{jsxref("String.prototype.repeat()")}} method is used with a `count`
argument that is infinity.
## Message
```plain
RangeError: Invalid string length (V8-based)
RangeError: Invalid count value: Infinity (V8-based)
RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)
RangeError: Out of memory (Safari)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
The {{jsxref("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 {{jsxref("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
2<sup>30</sup> - 2 (\~2GiB).
## Examples
### Invalid cases
```js example-bad
"abc".repeat(Infinity); // RangeError
"a".repeat(2 ** 30); // RangeError
```
### Valid cases
```js example-good
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
```
## See also
- {{jsxref("String.prototype.repeat()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.md | ---
title: 'TypeError: can''t define property "x": "obj" is not extensible'
slug: Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "can't define property "x": "obj" is not extensible" occurs
when {{jsxref("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.
## Message
```plain
TypeError: Cannot add property x, object is not extensible (V8-based)
TypeError: Cannot define property x, object is not extensible (V8-based)
TypeError: can't define property "x": Object is not extensible (Firefox)
TypeError: Attempting to define property on object that is not extensible. (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
Usually, an object is extensible and new properties can be added to it. However, in
this case {{jsxref("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
### Adding new properties to a non-extensible objects
In [strict mode](/en-US/docs/Web/JavaScript/Reference/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.
```js example-bad
"use strict";
const obj = {};
Object.preventExtensions(obj);
obj.x = "foo";
// TypeError: can't define property "x": Object is not extensible
```
In both, [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) and
sloppy mode, a call to {{jsxref("Object.defineProperty()")}} throws when adding a new
property to a non-extensible object.
```js example-bad
const obj = {};
Object.preventExtensions(obj);
Object.defineProperty(obj, "x", { value: "foo" });
// TypeError: can't define property "x": Object is not extensible
```
To fix this error, you will either need to remove the call to
{{jsxref("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.
```js example-good
"use strict";
const obj = {};
obj.x = "foo"; // add property first and only then prevent extensions
Object.preventExtensions(obj);
```
## See also
- {{jsxref("Object.preventExtensions()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_for-of_initializer/index.md | ---
title: "SyntaxError: a declaration in the head of a for-of loop can't have an initializer"
slug: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop contains an initializer expression such as `for (const i = 0 of iterable)`. This is not allowed in for-of loops.
## Message
```plain
SyntaxError: for-of loop variable declaration may not have an initializer. (V8-based)
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-of loop header. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The head of a [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/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`](/en-US/docs/Web/JavaScript/Reference/Statements/for) loop that does allow an initializer.
## Examples
### Invalid for-of loop
```js-nolint example-bad
const iterable = [10, 20, 30];
for (const value = 50 of iterable) {
console.log(value);
}
// SyntaxError: a declaration in the head of a for-of loop can't
// have an initializer
```
### Valid for-of loop
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.
```js example-good
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 50;
console.log(value);
}
// 60
// 70
// 80
```
## See also
- [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
- [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_use_nullish_coalescing_unparenthesized/index.md | ---
title: "SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions"
slug: Web/JavaScript/Reference/Errors/Cant_use_nullish_coalescing_unparenthesized
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "cannot use `??` unparenthesized within `||` and `&&` expressions" occurs when an [nullish coalescing operator](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) is used with a [logical OR](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) or [logical AND](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) in the same expression without parentheses.
## Message
```plain
SyntaxError: Unexpected token '??' (V8-based)
SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions (Firefox)
SyntaxError: Unexpected token '??'. Coalescing and logical operators used together in the same expression; parentheses must be used to disambiguate. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) chain looks like this:
```plain
| > && > || > =
| > ?? > =
```
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:
```js-nolint example-bad
a ?? b || c;
a || b ?? c;
a ?? b && c;
a && b ?? c;
```
Instead, make your intent clear by parenthesizing either side explicitly:
```js example-good
(a ?? b) || c;
a ?? (b && c);
```
## Examples
When migrating legacy code that uses `||` and `&&` for guarding against `null` or `undefined`, you may often convert it partially:
```js-nolint example-bad
function getId(user, fallback) {
// Previously: user && user.id || fallback
return user && user.id ?? fallback; // SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
}
```
Instead, consider parenthesizing the `&&`:
```js
function getId(user, fallback) {
return (user && user.id) ?? fallback;
}
```
Even better, consider using [optional chaining](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) instead of `&&`:
```js example-good
function getId(user, fallback) {
return user?.id ?? fallback;
}
```
## See also
- [Issue about nullish coalescing precedence](https://github.com/tc39/proposal-nullish-coalescing/issues/15) in the TC39 nullish-coalescing proposal
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- [Operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_parenthesis_after_condition/index.md | ---
title: "SyntaxError: missing ) after condition"
slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing ) after condition" occurs when there is an error with
how an
[`if`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
condition is written. It must appear in parenthesis after the `if` keyword.
## Message
```plain
SyntaxError: missing ) after condition (Firefox)
SyntaxError: Unexpected token '{'. Expected ')' to end an 'if' condition. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
There is an error with how an
[`if`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
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:
```js
if (condition) {
// do something if the condition is true
}
```
## Examples
### Missing parenthesis
It might just be an oversight, carefully check all you parenthesis in your code.
```js-nolint example-bad
if (Math.PI < 3 {
console.log("wait what?");
}
// SyntaxError: missing ) after condition
```
To fix this code, you would need to add a parenthesis that closes the condition.
```js example-good
if (Math.PI < 3) {
console.log("wait what?");
}
```
### Misused is keyword
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.
```js-nolint example-bad
if (done is true) {
console.log("we are done!");
}
// SyntaxError: missing ) after condition
```
Instead you need to use a correct [comparison operator](/en-US/docs/Web/JavaScript/Reference/Operators).
For example:
```js
if (done === true) {
console.log("we are done!");
}
```
Or even better:
```js example-good
if (done) {
console.log("we are done!");
}
```
## See also
- [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
- [Relational operators](/en-US/docs/Web/JavaScript/Reference/Operators#relational_operators)
- [Making decisions in your code β conditionals](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.md | ---
title: "SyntaxError: invalid assignment left-hand side"
slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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 `===`.
## Message
```plain
SyntaxError: Invalid left-hand side in assignment (V8-based)
SyntaxError: invalid assignment left-hand side (Firefox)
SyntaxError: Left side of assignment is not a reference. (Safari)
```
## Error type
{{jsxref("SyntaxError")}} or {{jsxref("ReferenceError")}}, depending on the syntax.
## What went wrong?
There was an unexpected assignment somewhere. This might be due to a mismatch of an [assignment operator](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators) and an [equality operator](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators), for example. While a single `=` sign assigns a value to a variable, the `==` or `===` operators compare a value.
## Examples
### Typical invalid assignments
```js-nolint example-bad
if (Math.PI + 1 = 3 || Math.PI + 1 = 4) {
console.log("no way!");
}
// SyntaxError: invalid assignment left-hand side
const str = "Hello, "
+= "is it me "
+= "you're looking for?";
// SyntaxError: invalid assignment left-hand side
```
In the `if` statement, you want to use an equality operator (`===`), and for the string concatenation, the plus (`+`) operator is needed.
```js-nolint example-good
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {
console.log("no way!");
}
const str = "Hello, "
+ "from the "
+ "other side!";
```
### Assignments producing ReferenceErrors
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.
```js-nolint example-bad
function foo() {
return { a: 1 };
}
foo() = 1; // ReferenceError: invalid assignment left-hand side
```
Function calls, [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) calls, [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super), and [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/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.
```js example-good
function foo() {
return { a: 1 };
}
foo().a = 1;
```
> **Note:** In Firefox and Safari, the first example produces a `ReferenceError` in non-strict mode, and a `SyntaxError` in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). Chrome throws a runtime `ReferenceError` for both strict and non-strict modes.
### Using optional chaining as assignment target
[Optional chaining](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) is not a valid target of assignment.
```js-nolint example-bad
obj?.foo = 1; // SyntaxError: invalid assignment left-hand side
```
Instead, you have to first guard the nullish case.
```js example-good
if (obj) {
obj.foo = 1;
}
```
## See also
- [Assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators)
- [Equality operators](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/unexpected_type/index.md | ---
title: 'TypeError: "x" is (not) "y"'
slug: Web/JavaScript/Reference/Errors/Unexpected_type
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "_x_ is (not) _y_" occurs when there was an
unexpected type. Oftentimes, unexpected {{jsxref("undefined")}} or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
values.
## Message
```plain
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: "x" is undefined (Firefox)
TypeError: "undefined" is not an object (Firefox)
TypeError: undefined is not an object (evaluating 'obj.x') (Safari)
TypeError: "x" is not a symbol (V8-based & Firefox)
TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
There was an unexpected type. This occurs oftentimes with {{jsxref("undefined")}} or
[`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) values.
Also, certain methods, such as {{jsxref("Object.create()")}} or
{{jsxref("Symbol.keyFor()")}}, require a specific type, that must be provided.
## Examples
### Invalid cases
You cannot invoke a method on an `undefined` or `null` variable.
```js example-bad
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined
const foo2 = null;
foo2.substring(1); // TypeError: foo is null
```
Certain methods might require a specific type.
```js example-bad
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol
const foo2 = "bar";
Object.create(foo2); // TypeError: "foo" is not an object or null
```
### Fixing the issue
To fix null pointer to `undefined` or `null` values, you can test if the value is `undefined` or `null` first.
```js example-good
if (foo !== undefined && foo !== null) {
// Now we know that foo is defined, we are good to go.
}
```
Or, if you are confident that `foo` will not be another [falsy](/en-US/docs/Glossary/Falsy) value like `""` or `0`, or if filtering those cases out is not an issue, you can simply test for its truthiness.
```js example-good
if (foo) {
// Now we know that foo is truthy, it will necessarily not be null/undefined.
}
```
## See also
- {{jsxref("undefined")}}
- [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.md | ---
title: "TypeError: invalid 'instanceof' operand 'x'"
slug: Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid 'instanceof' operand" occurs when the right-hand side
operands of the [`instanceof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof)
isn't used with a constructor object, i.e. an object which has a `prototype` property and is callable.
## Message
```plain
TypeError: Right-hand side of 'instanceof' is not an object (V8-based)
TypeError: Right-hand side of 'instanceof' is not callable (V8-based)
TypeError: invalid 'instanceof' operand "x" (Firefox)
TypeError: ({}) is not a function (Firefox)
TypeError: Right hand side of instanceof is not an object (Safari)
TypeError: {} is not a function. (evaluating '"x" instanceof {}') (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
The [`instanceof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) 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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) method.
## Examples
### instanceof vs. typeof
```js example-bad
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
42 instanceof 0; // TypeError: invalid 'instanceof' operand 0
function Foo() {}
const f = Foo(); // Foo() is called and returns undefined
const x = new Foo();
x instanceof f; // TypeError: invalid 'instanceof' operand f
x instanceof x; // TypeError: x is not a function
```
To fix these errors, you will either need to replace
the [`instanceof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof)
with the [`typeof` operator](/en-US/docs/Web/JavaScript/Reference/Operators/typeof),
or to make sure you use the function name, instead of the result of its evaluation.
```js example-good
typeof "test" === "string"; // true
typeof 42 === "number"; // true
function Foo() {}
const f = Foo; // Do not call Foo.
const x = new Foo();
x instanceof f; // true
x instanceof Foo; // true
```
## See also
- [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof)
- [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/deprecated_source_map_pragma/index.md | ---
title: "SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead"
slug: Web/JavaScript/Reference/Errors/Deprecated_source_map_pragma
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
```
## Error type
A warning that a {{jsxref("SyntaxError")}} occurred. JavaScript execution won't be halted.
## What went wrong?
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](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html), 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](https://stackoverflow.com/questions/24473882/what-does-this-comment-cc-on-0-do-inside-an-if-statement-in-javascript) in IE is a little known feature, but it broke source maps with [jQuery](https://bugs.jquery.com/ticket/13274) and other libraries.
## Examples
### Deprecated syntax
Syntax with the "@" sign is deprecated.
```js example-bad
//@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
### Standard syntax
Use the "#" sign instead.
```js example-good
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```
Or, alternatively, you can set a {{HTTPHeader("SourceMap")}} header to your JavaScript file to avoid having a comment at all:
```http example-good
SourceMap: /path/to/file.js.map
```
## See also
- [Use a source map](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/use_a_source_map/index.html) in the Firefox source docs
- [Introduction to JavaScript source maps](https://developer.chrome.com/blog/sourcemaps/) on developer.chrome.com (2012)
- {{HTTPHeader("SourceMap")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/equal_as_assign/index.md | ---
title: "SyntaxError: test for equality (==) mistyped as assignment (=)?"
slug: Web/JavaScript/Reference/Errors/Equal_as_assign
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when
there was an assignment (`=`) when you would normally expect a test for
equality (`==`).
## Message
```plain
Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
```
## Error type
(Firefox only) {{jsxref("SyntaxError")}} warning which is reported only if
`javascript.options.strict` preference is set to `true`.
## What went wrong?
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
### Assignment within conditional expressions
It is advisable to not use simple assignments in a conditional expression (such as
[`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)),
because the assignment can be confused with equality when glancing over the code. For
example, do not use the following code:
```js-nolint example-bad
if (x = y) {
// do the right thing
}
```
If you need to use an assignment in a conditional expression, a common practice is to
put additional parentheses around the assignment. For example:
```js
if ((x = y)) {
// do the right thing
}
```
Otherwise, you probably meant to use a comparison operator (e.g. `==` or
`===`):
```js
if (x === y) {
// do the right thing
}
```
## See also
- [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
- [Equality operators](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/not_defined/index.md | ---
title: 'ReferenceError: "x" is not defined'
slug: Web/JavaScript/Reference/Errors/Not_defined
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "_variable_ is not defined" occurs when there is a
non-existent variable referenced somewhere.
## Message
```plain
ReferenceError: "x" is not defined (V8-based & Firefox)
ReferenceError: Can't find variable: x (Safari)
```
## Error type
{{jsxref("ReferenceError")}}.
## What went wrong?
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](/en-US/docs/Glossary/Scope).
> **Note:** When loading a library (such as jQuery), make sure it is
> loaded before you access library variables, such as "$". Put the
> {{HTMLElement("script")}} element that loads the library before your code that uses
> it.
## Examples
### Variable not declared
```js example-bad
foo.substring(1); // ReferenceError: foo is not defined
```
The "foo" variable isn't defined anywhere. It needs to be some string, so that the
{{jsxref("String.prototype.substring()")}} method will work.
```js example-good
const foo = "bar";
foo.substring(1); // "ar"
```
### Wrong scope
A variable needs to be available in the current context of execution. Variables defined
inside a [function](/en-US/docs/Web/JavaScript/Reference/Functions) cannot be
accessed from anywhere outside the function, because the variable is defined only in the
scope of the function
```js example-bad
function numbers() {
const num1 = 2;
const num2 = 3;
return num1 + num2;
}
console.log(num1); // ReferenceError num1 is not defined.
```
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.
```js example-good
const num1 = 2;
const num2 = 3;
function numbers() {
return num1 + num2;
}
console.log(numbers()); // 5
```
## See also
- [Scope](/en-US/docs/Glossary/Scope)
- [Declaring variables in the JavaScript Guide](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declaring_variables)
- [Function scope in the JavaScript Guide](/en-US/docs/Web/JavaScript/Guide/Functions#function_scope)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/either_be_both_static_or_non-static/index.md | ---
title: "SyntaxError: getter and setter for private name #x should either be both static or non-static"
slug: Web/JavaScript/Reference/Errors/Either_be_both_static_or_non-static
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "mismatched placement" occurs when a private [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) are mismatched in whether or not they are {{jsxref("Classes/static", "static")}}.
## Message
```plain
SyntaxError: Identifier '#x' has already been declared (V8-based)
SyntaxError: getter and setter for private name #x should either be both static or non-static (Firefox)
SyntaxError: Cannot declare a private non-static getter if there is a static private setter with used name. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
Private [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set) for the same name must either be both {{jsxref("Classes/static", "static")}}, or both non-static. This limitation does not exist for public methods.
## Examples
### Mismatched placement
```js-nolint example-bad
class Test {
static set #foo(_) {}
get #foo() {}
}
// SyntaxError: getter and setter for private name #foo should either be both static or non-static
```
Since `foo` is [private](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties), the methods must be either both {{jsxref("Classes/static", "static")}}:
```js example-good
class Test {
static set #foo(_) {}
static get #foo() {}
}
```
or non-static:
```js example-good
class Test {
set #foo(_) {}
get #foo() {}
}
```
## See also
- {{jsxref("Functions/get", "get")}}
- {{jsxref("Functions/set", "set")}}
- {{jsxref("Classes/static", "static")}}
- [Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_bigint_syntax/index.md | ---
title: "SyntaxError: invalid BigInt syntax"
slug: Web/JavaScript/Reference/Errors/Invalid_BigInt_syntax
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid BigInt syntax" occurs when a string value is being coerced to a {{jsxref("BigInt")}} but it failed to be parsed as an integer.
## Message
```plain
SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
When using the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/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
### Invalid cases
```js example-bad
const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");
// SyntaxError: invalid BigInt syntax
```
### Valid cases
```js example-good
const a = BigInt("1");
const b = BigInt(" 1 ");
const c = BigInt.asIntN(4, "8");
```
## See also
- [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/stmt_after_return/index.md | ---
title: "Warning: unreachable code after return statement"
slug: Web/JavaScript/Reference/Errors/Stmt_after_return
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript warning "unreachable code after return statement" occurs when using an
expression after a {{jsxref("Statements/return", "return")}} statement, or when using a
semicolon-less return statement but including an expression directly after.
## Message
```plain
Warning: unreachable code after return statement (Firefox)
```
## Error type
Warning
## What went wrong?
Unreachable code after a return statement might occur in these situations:
- When using an expression after a {{jsxref("Statements/return", "return")}}
statement, or
- when using a semicolon-less return statement but including an expression directly
after.
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:
- {{jsxref("Statements/throw", "throw")}}
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Statements/function", "function")}}
## Examples
### Invalid cases
```js-nolint example-bad
function f() {
let x = 3;
x += 4;
return x; // return exits the function immediately
x -= 3; // so this line will never run; it is unreachable
}
function g() {
return // this is treated like `return;`
3 + 4; // so the function returns, and this line is never reached
}
```
### Valid cases
```js-nolint example-good
function f() {
let x = 3;
x += 4;
x -= 3;
return x; // OK: return after all other statements
}
function g() {
return 3 + 4 // OK: semicolon-less return with expression on the same line
}
```
## See also
- [Automatic semicolon insertion](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/no_properties/index.md | ---
title: 'TypeError: "x" has no properties'
slug: Web/JavaScript/Reference/Errors/No_properties
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "null (or undefined) has no properties" occurs when you
attempt to access properties of [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and {{jsxref("undefined")}}. They
don't have any.
## Message
```plain
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: null has no properties (Firefox)
TypeError: undefined has no properties (Firefox)
TypeError: undefined is not an object (evaluating 'undefined.x') (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
Both [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and {{jsxref("undefined")}}, have no properties you could
access.
## Examples
### null and undefined have no properties
```js example-bad
null.foo;
// TypeError: null has no properties
undefined.bar;
// TypeError: undefined has no properties
```
## See also
- [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
- {{jsxref("undefined")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cyclic_prototype/index.md | ---
title: "TypeError: can't set prototype: it would cause a prototype chain cycle"
slug: Web/JavaScript/Reference/Errors/Cyclic_prototype
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "TypeError: can't set prototype: it would cause a prototype chain cycle" occurs when an object's prototype is set to an object such that the [prototype chain](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#the_prototype_chain) becomes circular (`a` and `b` both have each other in their prototype chains).
## Message
```plain
TypeError: Cyclic __proto__ value (V8-based)
TypeError: can't set prototype: it would cause a prototype chain cycle (Firefox)
TypeError: cyclic __proto__ value (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
A loop, also called a cycle, was introduced in a prototype chain. That means that when walking this prototype chain, the same place would be accessed over and over again, instead of eventually reaching `null`.
This error is thrown at the time of setting the prototype. In an operation like `Object.setPrototypeOf(a, b)`, if `a` already exists in the prototype chain of `b`, this error will be thrown.
## Examples
```js example-bad
const a = {};
Object.setPrototypeOf(a, a);
// TypeError: can't set prototype: it would cause a prototype chain cycle
```
```js example-bad
const a = {};
const b = {};
const c = {};
Object.setPrototypeOf(a, b);
Object.setPrototypeOf(b, c);
Object.setPrototypeOf(c, a);
// TypeError: can't set prototype: it would cause a prototype chain cycle
```
## See also
- [Object Prototypes](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)
- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.md | ---
title: "ReferenceError: can't access lexical declaration 'X' before initialization"
slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) variables are accessed before the place where they are declared is executed.
## Message
```plain
ReferenceError: Cannot access 'X' before initialization (V8-based)
ReferenceError: can't access lexical declaration 'X' before initialization (Firefox)
ReferenceError: Cannot access uninitialized variable. (Safari)
```
## Error type
{{jsxref("ReferenceError")}}
## What went wrong?
A lexical variable was accessed before it was initialized.
This happens within any block statement, when variables declared with [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/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](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz).
This issue does not occur for variables declared using `var`, because they are initialized with a default value of `undefined` when they are [hoisted](/en-US/docs/Glossary/Hoisting).
This error can also occur in [cyclic imports](/en-US/docs/Web/JavaScript/Guide/Modules#cyclic_imports) when a module uses a variable that depends on the module itself being evaluated.
## Examples
### Invalid cases
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.
```js example-bad
function test() {
// Accessing the 'const' variable foo before it's declared
console.log(foo); // ReferenceError: foo is not initialized
const foo = 33; // 'foo' is declared and initialized here using the 'const' keyword
}
test();
```
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`.
```js example-bad
// -- a.js (entry module) --
import { b } from "./b.js";
export const a = 2;
// -- b.js --
import { a } from "./a.js";
console.log(a); // ReferenceError: Cannot access 'a' before initialization
export const b = 1;
```
### Valid cases
In the following example, we correctly declare a variable using the `const` keyword before accessing it.
```js example-good
function test() {
// Declaring variable foo
const foo = 33;
console.log(foo); // 33
}
test();
```
In this example, the imported variable `a` is asynchronously accessed, so both modules are evaluated before the access to `a` occurs.
```js example-good
// -- a.js (entry module) --
import { b } from "./b.js";
export const a = 2;
// -- b.js --
import { a } from "./a.js";
setTimeout(() => {
console.log(a); // 2
}, 10);
export const b = 1;
```
## See also
- {{jsxref("Statements/let", "let")}}
- {{jsxref("Statements/const", "const")}}
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Statements/class", "class")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_bracket_after_list/index.md | ---
title: "SyntaxError: missing ] after element list"
slug: Web/JavaScript/Reference/Errors/Missing_bracket_after_list
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
SyntaxError: missing ] after element list (Firefox)
SyntaxError: Unexpected token ';'. Expected either a closing ']' or a ',' following an array element. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
There is an error with the array initializer syntax somewhere. Likely there is a
closing square bracket (`]`) or a comma (`,`) missing.
## Examples
### Incomplete array initializer
```js-nolint example-bad
const list = [1, 2,
const instruments = [
"Ukulele",
"Guitar",
"Piano",
};
const data = [{ foo: "bar" } { bar: "foo" }];
```
Correct would be:
```js example-good
const list = [1, 2];
const instruments = ["Ukulele", "Guitar", "Piano"];
const data = [{ foo: "bar" }, { bar: "foo" }];
```
## See also
- {{jsxref("Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/no_non-null_object/index.md | ---
title: 'TypeError: "x" is not a non-null object'
slug: Web/JavaScript/Reference/Errors/No_non-null_object
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "is not a non-null object" occurs when an object is expected
somewhere and wasn't provided. [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) is not an object and won't work.
## Message
```plain
TypeError: Property description must be an object: x (V8-based)
TypeError: Property descriptor must be an object, got "x" (Firefox)
TypeError: Property description must be an object. (Safari)
TypeError: Invalid value used in weak set (V8-based)
TypeError: WeakSet value must be an object, got "x" (Firefox)
TypeError: Attempted to add a non-object value to a WeakSet (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
An object is expected somewhere and wasn't provided. [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) is not an
object and won't work. You must provide a proper object in the given situation.
## Examples
### Property descriptor expected
When methods like {{jsxref("Object.create()")}} or
{{jsxref("Object.defineProperty()")}} and {{jsxref("Object.defineProperties()")}} are
used, the optional descriptor parameter expects a property descriptor object. Providing
no object (like just a number), will throw an error:
```js example-bad
Object.defineProperty({}, "key", 1);
// TypeError: 1 is not a non-null object
Object.defineProperty({}, "key", null);
// TypeError: null is not a non-null object
```
A valid property descriptor object might look like this:
```js example-good
Object.defineProperty({}, "key", { value: "foo", writable: false });
```
### WeakMap and WeakSet objects require object or symbol keys
{{jsxref("WeakMap")}} and {{jsxref("WeakSet")}} objects store object or symbol keys. You can't
use other types as keys.
```js example-bad
const ws = new WeakSet();
ws.add("foo");
// TypeError: "foo" is not a non-null object
```
Use objects instead:
```js example-good
ws.add({ foo: "bar" });
ws.add(window);
```
## See also
- {{jsxref("Object.create()")}}
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.defineProperties()")}}
- {{jsxref("WeakMap")}}
- {{jsxref("WeakSet")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/unnamed_function_statement/index.md | ---
title: "SyntaxError: function statement requires a name"
slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "function statement requires a name" occurs
when there is a [function statement](/en-US/docs/Web/JavaScript/Reference/Statements/function)
in the code that requires a name.
## Message
```plain
SyntaxError: Function statements require a function name (V8-based)
SyntaxError: function statement requires a name (Firefox)
SyntaxError: Function statements must have a name. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
There is a [function statement](/en-US/docs/Web/JavaScript/Reference/Statements/function) 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](/en-US/docs/Glossary/IIFE), or if the function code is placed correctly in this context at all.
## Examples
### Statements vs. expressions
A _[function statement](/en-US/docs/Web/JavaScript/Reference/Statements/function)_ (or _function declaration_) requires a name.
This won't work:
```js-nolint example-bad
function () {
return "Hello world";
}
// SyntaxError: function statement requires a name
```
You can use a [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) (assignment) instead:
```js example-good
const greet = function () {
return "Hello world";
};
```
If your function is intended to be an [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (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:
```js example-good
(function () {
// β¦
})();
```
### Labeled functions
[Labels](/en-US/docs/Web/JavaScript/Reference/Statements/label) are an entirely different feature from function names. You can't use a label as a function name.
```js-nolint example-bad
function Greeter() {
german: function () {
return "Moin";
}
}
// SyntaxError: function statement requires a name
```
In addition, labeled function declarations themselves are a deprecated feature. Use regular function declarations instead.
```js example-good
function Greeter() {
function german() {
return "Moin";
}
}
```
### Object methods
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.
```js example-good
const greeter = {
german: function () {
return "Moin";
},
};
```
You can also use the [method syntax](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).
```js
const greeter = {
german() {
return "Moin";
},
};
```
### Callback syntax
Also, check your syntax when using callbacks.
Braces and commas can quickly get confusing.
```js-nolint example-bad
promise.then(
function () {
console.log("success");
});
function () {
console.log("error");
}
// SyntaxError: function statement requires a name
```
Correct would be:
```js example-good
promise.then(
function () {
console.log("success");
},
function () {
console.log("error");
},
);
```
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function)
- [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function)
- {{Glossary("IIFE")}}
- [Labeled statement](/en-US/docs/Web/JavaScript/Reference/Statements/label)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bigint_negative_exponent/index.md | ---
title: "RangeError: BigInt negative exponent"
slug: Web/JavaScript/Reference/Errors/BigInt_negative_exponent
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "BigInt negative exponent" occurs when a {{jsxref("BigInt")}} is raised to the power of a negative BigInt value.
## Message
```plain
RangeError: Exponent must be positive (V8-based)
RangeError: BigInt negative exponent (Firefox)
RangeError: Negative exponent is not allowed (Safari)
```
## Error type
{{jsxref("RangeError")}}.
## What went wrong?
The exponent of an [exponentiation](/en-US/docs/Web/JavaScript/Reference/Operators/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
### Using a negative BigInt as exponent
```js example-bad
const a = 1n;
const b = -1n;
const c = a ** b;
// RangeError: BigInt negative exponent
```
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`.
```js example-good
const a = 1n;
const b = -1n;
const quotient = b >= 0n ? a ** b : 0n;
```
## See also
- [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/more_arguments_needed/index.md | ---
title: "TypeError: More arguments needed"
slug: Web/JavaScript/Reference/Errors/More_arguments_needed
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "more arguments needed" occurs when there is an error with how
a function is called. More arguments need to be provided.
## Message
```plain
TypeError: Object prototype may only be an Object or null: undefined (V8-based)
TypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox)
TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object prototype may only be an Object or null. (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
There is an error with how a function is called. More arguments need to be provided.
## Examples
### Required arguments not provided
The {{jsxref("Object.create()")}} method requires at least one argument and the
{{jsxref("Object.setPrototypeOf()")}} method requires at least two arguments:
```js example-bad
const obj = Object.create();
// TypeError: Object.create requires at least 1 argument, but only 0 were passed
const obj2 = Object.setPrototypeOf({});
// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed
```
You can fix this by setting [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) as the prototype, for example:
```js example-good
const obj = Object.create(null);
const obj2 = Object.setPrototypeOf({}, null);
```
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/identifier_after_number/index.md | ---
title: "SyntaxError: identifier starts immediately after numeric literal"
slug: Web/JavaScript/Reference/Errors/Identifier_after_number
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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 ($).
## Message
```plain
SyntaxError: Unexpected identifier after numeric literal (Edge)
SyntaxError: identifier starts immediately after numeric literal (Firefox)
SyntaxError: Unexpected number (Chrome)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The names of variables, called [identifiers](/en-US/docs/Glossary/Identifier), 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).
## Examples
### Variable names starting with numeric literals
Variable names can't start with numbers in JavaScript. The following fails:
```js-nolint example-bad
const 1life = "foo";
// SyntaxError: identifier starts immediately after numeric literal
const foo = 1life;
// SyntaxError: identifier starts immediately after numeric literal
alert(1.foo);
// SyntaxError: identifier starts immediately after numeric literal
```
You will need to rename your variable to avoid the leading number.
```js example-good
const life1 = "foo";
const foo = life1;
```
## See also
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
- [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_curly_after_property_list/index.md | ---
title: "SyntaxError: missing } after property list"
slug: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing } after property list" occurs when there is a mistake
in the [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) syntax somewhere.
Might be in fact a missing curly bracket, but could also be a missing comma.
## Message
```plain
SyntaxError: missing } after property list (Firefox)
SyntaxError: Unexpected identifier 'c'. Expected '}' to end an object literal. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
There is a mistake in the [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/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
### Forgotten comma
Oftentimes, there is a missing comma in your object initializer code:
```js-nolint example-bad
const obj = {
a: 1,
b: { myProp: 2 }
c: 3
};
```
Correct would be:
```js example-good
const obj = {
a: 1,
b: { myProp: 2 },
c: 3,
};
```
## See also
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_colon_after_property_id/index.md | ---
title: "SyntaxError: missing : after property id"
slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing : after property id" occurs when objects are created
using the [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) syntax.
A colon (`:`) separates keys and values for the
object's properties. Somehow, this colon is missing or misplaced.
## Message
```plain
SyntaxError: Invalid shorthand property initializer (V8-based)
SyntaxError: missing : after property id (Firefox)
SyntaxError: Unexpected token '='. Expected a ':' following the property name 'x'. (Safari)
SyntaxError: Unexpected token '+'. Expected an identifier as property name. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
When creating objects with the [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) syntax,
a colon (`:`) separates keys and values for the object's properties.
```js
const obj = { propertyKey: "value" };
```
## Examples
### Colons vs. equal signs
This code fails, as the equal sign can't be used this way in this object initializer
syntax.
```js-nolint example-bad
const obj = { propertyKey = "value" };
// SyntaxError: missing : after property id
```
Correct would be to use a colon, or to use square brackets to assign a new property
after the object has been created already.
```js example-good
const obj = { propertyKey: "value" };
```
Or alternatively:
```js
const obj = {};
obj.propertyKey = "value";
```
### Computed properties
If you create a property key from an expression, you need to use square brackets.
Otherwise the property name can't be computed:
```js-nolint example-bad
const obj = { "b"+"ar": "foo" };
// SyntaxError: missing : after property id
```
Put the expression in square brackets `[]`:
```js example-good
const obj = { ["b" + "ar"]: "foo" };
```
## See also
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/label_not_found/index.md | ---
title: "SyntaxError: label not found"
slug: Web/JavaScript/Reference/Errors/Label_not_found
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "label not found" occurs when a {{jsxref("Statements/break", "break")}} or {{jsxref("Statements/continue", "continue")}} statement references a label that does not exist on any statement that contains the `break` or `continue` statement.
## Message
```plain
SyntaxError: Undefined label 'label' (V8-based)
SyntaxError: label not found (Firefox)
SyntaxError: Cannot use the undeclared label 'label'. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
In JavaScript, [labels](/en-US/docs/Web/JavaScript/Reference/Statements/label) are very limited: you can only use them with {{jsxref("Statements/break", "break")}} and {{jsxref("Statements/continue", "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
### Unsyntactic jump
You cannot use labels as if they are `goto`.
```js-nolint example-bad
start: console.log("Hello, world!");
console.log("Do it again");
break start;
```
Instead, you can only use labels to enhance the normal semantics of `break` and `continue` statements.
```js example-good
start: {
console.log("Hello, world!");
if (Math.random() > 0.5) {
break start;
}
console.log("Maybe I'm logged");
}
```
## See also
- [Labeled statement](/en-US/docs/Web/JavaScript/Reference/Statements/label)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_array_length/index.md | ---
title: "RangeError: invalid array length"
slug: Web/JavaScript/Reference/Errors/Invalid_array_length
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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 {{jsxref("Array")}} or {{jsxref("ArrayBuffer")}}, or when setting the {{jsxref("Array/length", "length")}} property).
The maximum allowed array length depends on the platform, browser and browser version.
For {{jsxref("Array")}} the maximum length is 2<sup>32</sup>-1.
For {{jsxref("ArrayBuffer")}} the maximum is 2<sup>31</sup>-1 (2GiB-1) on 32-bit systems.
From Firefox version 89 the maximum value of {{jsxref("ArrayBuffer")}} is 2<sup>33</sup> (8GiB) on 64-bit systems.
> **Note:** `Array` and `ArrayBuffer` are independent data structures (the implementation of one does not affect the other).
## Message
```plain
RangeError: invalid array length (V8-based & Firefox)
RangeError: Array buffer allocation failed (V8-based)
RangeError: Array size is not a small enough positive integer. (Safari)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
An invalid array length might appear in these situations:
- Creating an {{jsxref("Array")}} or {{jsxref("ArrayBuffer")}} with a negative length, or setting a negative value for the {{jsxref("Array/length", "length")}} property.
- Creating an {{jsxref("Array")}} or setting the {{jsxref("Array/length", "length")}} property greater than 2<sup>32</sup>-1.
- Creating an {{jsxref("ArrayBuffer")}} that is bigger than 2<sup>31</sup>-1 (2GiB-1) on a 32-bit system, or 2<sup>33</sup> (8GiB) on a 64-bit system.
- Creating an {{jsxref("Array")}} or setting the {{jsxref("Array/length", "length")}} property to a floating-point number.
- Before Firefox 89: Creating an {{jsxref("ArrayBuffer")}} that is bigger than 2<sup>31</sup>-1 (2GiB-1).
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.
## Examples
### Invalid cases
```js example-bad
new Array(Math.pow(2, 40));
new Array(-1);
new ArrayBuffer(Math.pow(2, 32)); // 32-bit system
new ArrayBuffer(-1);
const a = [];
a.length = a.length - 1; // set the length property to -1
const b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // set the length property to 2^32
b.length = 2.5; // set the length property to a floating-point number
const c = new Array(2.5); // pass a floating-point number
```
### Valid cases
```js example-good
[Math.pow(2, 40)]; // [ 1099511627776 ]
[-1]; // [ -1 ]
new ArrayBuffer(Math.pow(2, 31) - 1);
new ArrayBuffer(Math.pow(2, 33)); // 64-bit systems after Firefox 89
new ArrayBuffer(0);
const a = [];
a.length = Math.max(0, a.length - 1);
const b = new Array(Math.pow(2, 32) - 1);
b.length = Math.min(0xffffffff, b.length + 1);
// 0xffffffff is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)
b.length = 3;
const c = new Array(3);
```
## See also
- {{jsxref("Array")}}
- {{jsxref("Array/length", "length")}}
- {{jsxref("ArrayBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_convert_x_to_bigint/index.md | ---
title: "TypeError: can't convert x to BigInt"
slug: Web/JavaScript/Reference/Errors/Cant_convert_x_to_BigInt
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "x can't be converted to BigInt" occurs when attempting to convert a {{jsxref("Symbol")}}, [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), or {{jsxref("undefined")}} value to a {{jsxref("BigInt")}}, or if an operation expecting a BigInt parameter receives a number.
## Message
```plain
TypeError: Cannot convert null to a BigInt (V8-based)
TypeError: can't convert null to BigInt (Firefox)
TypeError: Invalid argument type in ToBigInt operation (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
When using the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/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`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asIntN), require the parameter to be a BigInt. Passing in a number in this case will also throw this error.
## Examples
### Using BigInt() on invalid values
```js example-bad
const a = BigInt(null);
// TypeError: can't convert null to BigInt
const b = BigInt(undefined);
// TypeError: can't convert undefined to BigInt
const c = BigInt(Symbol("1"));
// TypeError: can't convert Symbol("1") to BigInt
```
```js example-good
const a = BigInt(1);
const b = BigInt(true);
const c = BigInt("1");
const d = BigInt(Symbol("1").description);
```
> **Note:** Simply coercing the value to a string or number using [`String()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String) or [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/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](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_BigInt_syntax) is thrown; if the number is not an integer (most notably, {{jsxref("NaN")}}), a [RangeError](/en-US/docs/Web/JavaScript/Reference/Errors/Cant_be_converted_to_BigInt_because_it_isnt_an_integer) is thrown. If the range of input is unknown, properly validate it before using `BigInt()`.
### Passing a number to a function expecting a BigInt
```js example-bad
const a = BigInt.asIntN(4, 8);
// TypeError: can't convert 8 to BigInt
const b = new BigInt64Array(3).fill(3);
// TypeError: can't convert 3 to BigInt
```
```js example-good
const a = BigInt.asIntN(4, 8n);
const b = new BigInt64Array(3).fill(3n);
```
## See also
- [`BigInt()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_radix/index.md | ---
title: "RangeError: radix must be an integer"
slug: Web/JavaScript/Reference/Errors/Bad_radix
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "radix must be an integer at least 2 and no greater than 36"
occurs when the optional `radix` parameter of the
{{jsxref("Number.prototype.toString()")}} or
the {{jsxref("BigInt.prototype.toString()")}} method was specified and is not between 2
and 36.
## Message
```plain
RangeError: toString() radix argument must be between 2 and 36 (V8-based & Safari)
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
The optional `radix` parameter of the
{{jsxref("Number.prototype.toString()")}} or
the {{jsxref("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:
- 2 for [binary numbers](https://en.wikipedia.org/wiki/Binary_number),
- 8 for [octal numbers](https://en.wikipedia.org/wiki/Octal),
- 10 for [decimal numbers](https://en.wikipedia.org/wiki/Decimal),
- 16 for [hexadecimal numbers](https://en.wikipedia.org/wiki/Hexadecimal).
## Examples
### Invalid cases
```js example-bad
(42).toString(0);
(42).toString(1);
(42).toString(37);
(42).toString(150);
// You cannot use a string like this for formatting:
(12071989).toString("MM-dd-yyyy");
```
### Valid cases
```js example-good
(42).toString(2); // "101010" (binary)
(13).toString(8); // "15" (octal)
(0x42).toString(10); // "66" (decimal)
(100000).toString(16); // "186a0" (hexadecimal)
```
## See also
- {{jsxref("Number.prototype.toString()")}}
- {{jsxref("BigInt.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/undeclared_var/index.md | ---
title: 'ReferenceError: assignment to undeclared variable "x"'
slug: Web/JavaScript/Reference/Errors/Undeclared_var
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)-only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.
## Message
```plain
ReferenceError: x is not defined (V8-based)
ReferenceError: assignment to undeclared variable x (Firefox)
ReferenceError: Can't find variable: x (Safari)
```
## Error type
{{jsxref("ReferenceError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
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:
- Declared variables are constrained in the execution context in which they are declared.
Undeclared variables are always global.
- Declared variables are created before any code is executed.
Undeclared variables do not exist until the code assigning to them is executed.
- Declared variables are a non-configurable property of their execution context (function or global).
Undeclared variables are configurable (e.g. can be deleted).
For more details and examples, see the [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var) reference page.
Errors about undeclared variable assignments occur in [strict mode code](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
In non-strict code, they are silently ignored.
## Examples
### Invalid cases
In this case, the variable "bar" is an undeclared variable.
```js example-bad
function foo() {
"use strict";
bar = true;
}
foo(); // ReferenceError: assignment to undeclared variable bar
```
### Valid cases
To make "bar" a declared variable, you can add a [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/var), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var) keyword in front of it.
```js example-good
function foo() {
"use strict";
const bar = true;
}
foo();
```
## See also
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cyclic_object_value/index.md | ---
title: "TypeError: cyclic object value"
slug: Web/JavaScript/Reference/Errors/Cyclic_object_value
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "cyclic object value" occurs when object references were found
in [JSON](https://www.json.org/). {{jsxref("JSON.stringify()")}} doesn't try
to solve them and fails accordingly.
## Message
```plain
TypeError: Converting circular structure to JSON (V8-based)
TypeError: cyclic object value (Firefox)
TypeError: JSON.stringify cannot serialize cyclic structures. (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
The [JSON format](https://www.json.org/) per se doesn't support object
references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)),
hence {{jsxref("JSON.stringify()")}} doesn't try to solve them and fails accordingly.
## Examples
### Circular references
In a circular structure like the following
```js
const circularReference = { otherData: 123 };
circularReference.myself = circularReference;
```
{{jsxref("JSON.stringify()")}} will fail
```js example-bad
JSON.stringify(circularReference);
// TypeError: cyclic object value
```
To serialize circular references you can use a library that supports them (e.g. [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/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
{{jsxref("JSON.stringify()")}}:
```js
function getCircularReplacer() {
const ancestors = [];
return function (key, value) {
if (typeof value !== "object" || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return "[Circular]";
}
ancestors.push(value);
return value;
};
}
JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123,"myself":"[Circular]"}
const o = {};
const notCircularReference = [o, o];
JSON.stringify(notCircularReference, getCircularReplacer());
// [{},{}]
```
## See also
- {{jsxref("JSON.stringify()")}}
- [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) on GitHub
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/unparenthesized_unary_expr_lhs_exponentiation/index.md | ---
title: "SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'"
slug: Web/JavaScript/Reference/Errors/Unparenthesized_unary_expr_lhs_exponentiation
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) without parentheses.
## Message
```plain
SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence (V8-based)
SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' (Firefox)
SyntaxError: Unexpected token '**'. Ambiguous unary expression in the left hand side of the exponentiation expression; parentheses must be used to disambiguate the expression. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
You likely wrote something like this:
```js-nolint example-bad
-a ** b
```
Whether it should be evaluated as `(-a) ** b` or `-(a ** b)` is ambiguous. In mathematics, -x<sup>2</sup> 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.
```js-nolint example-good
(-a) ** b
-(a ** b)
```
Other unary operators cannot be the left-hand side of exponentiation either.
```js-nolint example-bad
await a ** b
!a ** b
+a ** b
~a ** b
```
## Examples
When writing complex math expressions involving exponentiation, you may write something like this:
```js-nolint example-bad
function taylorSin(x) {
return (n) => (-1 ** n * x ** (2 * n + 1)) / factorial(2 * n + 1);
// SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
}
```
However, the `-1 ** n` part is illegal in JavaScript. Instead, parenthesize the left operand:
```js example-good
function taylorSin(x) {
return (n) => ((-1) ** n * x ** (2 * n + 1)) / factorial(2 * n + 1);
}
```
This also makes the code's intent much clearer to other readers.
## See also
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
- [Operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)
- [Original discussion of exponentiation operator precedence](https://esdiscuss.org/topic/exponentiation-operator-precedence) on esdiscuss.org
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/malformed_uri/index.md | ---
title: "URIError: malformed URI sequence"
slug: Web/JavaScript/Reference/Errors/Malformed_URI
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "malformed URI sequence" occurs when URI encoding or decoding
wasn't successful.
## Message
```plain
URIError: URI malformed (V8-based)
URIError: malformed URI sequence (Firefox)
URIError: String contained an illegal UTF-16 sequence. (Safari)
```
## Error type
{{jsxref("URIError")}}
## What went wrong?
URI encoding or decoding wasn't successful. An argument given to either the
{{jsxref("decodeURI")}}, {{jsxref("encodeURI")}}, {{jsxref("encodeURIComponent")}}, or
{{jsxref("decodeURIComponent")}} function was not valid, so that the function was unable
encode or decode properly.
## Examples
### Encoding
Encoding replaces each instance of certain characters by one, two, three, or four
escape sequences representing the UTF-8 encoding of the character. An
{{jsxref("URIError")}} will be thrown if there is an attempt to encode a surrogate which
is not part of a high-low pair, for example:
```js example-bad
encodeURI("\uD800");
// "URIError: malformed URI sequence"
encodeURI("\uDFFF");
// "URIError: malformed URI sequence"
```
A high-low pair is OK. For example:
```js example-good
encodeURI("\uD800\uDFFF");
// "%F0%90%8F%BF"
```
### Decoding
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:
```js example-bad
decodeURIComponent("%E0%A4%A");
// "URIError: malformed URI sequence"
```
With proper input, this should usually look like something like this:
```js example-good
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_ΡΠ΅Π»Π»Ρ"
```
## See also
- {{jsxref("URIError")}}
- {{jsxref("decodeURI")}}
- {{jsxref("encodeURI")}}
- {{jsxref("encodeURIComponent")}}
- {{jsxref("decodeURIComponent")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/read-only/index.md | ---
title: 'TypeError: "x" is read-only'
slug: Web/JavaScript/Reference/Errors/Read-only
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)-only exception
"is read-only" occurs when a global variable or object
property that was assigned to is a read-only property.
## Message
```plain
TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)
TypeError: "x" is read-only (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```
## Error type
{{jsxref("TypeError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
The global variable or object property that was assigned to is a read-only property.
(Technically, it is a [non-writable data property](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#writable_attribute).)
This error happens only in [strict mode code](/en-US/docs/Web/JavaScript/Reference/Strict_mode). In
non-strict code, the assignment is silently ignored.
## Examples
### Invalid cases
Read-only properties are not super common, but they can be created using
{{jsxref("Object.defineProperty()")}} or {{jsxref("Object.freeze()")}}.
```js example-bad
"use strict";
const obj = Object.freeze({ name: "Elsa", score: 157 });
obj.score = 0; // TypeError
("use strict");
Object.defineProperty(this, "LUNG_COUNT", { value: 2, writable: false });
LUNG_COUNT = 3; // TypeError
("use strict");
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray[0]++; // TypeError
```
There are also a few read-only properties built into JavaScript. Maybe you tried to
redefine a mathematical constant.
```js example-bad
"use strict";
Math.PI = 4; // TypeError
```
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:
```js example-bad
"use strict";
undefined = function () {}; // TypeError: "undefined" is read-only
```
### Valid cases
```js example-good
"use strict";
let obj = Object.freeze({ name: "Score", points: 157 });
obj = { name: obj.name, points: 0 }; // replacing it with a new object works
```
## See also
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.freeze()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/not_a_constructor/index.md | ---
title: 'TypeError: "x" is not a constructor'
slug: Web/JavaScript/Reference/Errors/Not_a_constructor
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
TypeError: x is not a constructor (V8-based & Firefox & Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
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](/en-US/docs/Glossary/Constructor)
or the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new)
for more information on what a constructor is.
There are many global objects, like {{jsxref("String")}} or {{jsxref("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: {{jsxref("Math")}}, {{jsxref("JSON")}}, {{jsxref("Symbol")}},
{{jsxref("Reflect")}}, {{jsxref("Intl")}}, {{jsxref("Atomics")}}.
[Generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*) cannot be used as constructors either.
## Examples
### Invalid cases
```js example-bad
const Car = 1;
new Car();
// TypeError: Car is not a constructor
new Math();
// TypeError: Math is not a constructor
new Symbol();
// TypeError: Symbol is not a constructor
function* f() {}
const obj = new f();
// TypeError: f is not a constructor
```
### A car constructor
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:
```js
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
```
Now you can create an object called `mycar` as follows:
```js
const mycar = new Car("Eagle", "Talon TSi", 1993);
```
### In Promises
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()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) or [`Promise.reject()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject) [static methods](<https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods>).
This is not legal (the [`Promise` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) is not being called correctly) and will throw a `TypeError: this is not a constructor` exception:
```js example-bad
const fn = () => {
return new Promise.resolve(true);
};
```
This is legal, but unnecessarily long:
```js
const fn = () => {
return new Promise((resolve, reject) => {
resolve(true);
});
};
```
Instead, return the static method:
```js example-good
const resolveAlways = () => {
return Promise.resolve(true);
};
const rejectAlways = () => {
return Promise.reject(false);
};
```
## See also
- [constructor](/en-US/docs/Glossary/Constructor)
- [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/too_much_recursion/index.md | ---
title: "InternalError: too much recursion"
slug: Web/JavaScript/Reference/Errors/Too_much_recursion
page-type: javascript-error
---
{{jsSidebar("Errors")}}
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.
## Message
```plain
RangeError: Maximum call stack size exceeded (Chrome)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded. (Safari)
```
## Error type
{{jsxref("InternalError")}} in Firefox; {{jsxref("RangeError")}} in Chrome and Safari.
## What went wrong?
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.
## Examples
This recursive function runs 10 times, as per the exit condition.
```js
function loop(x) {
if (x >= 10)
// "x >= 10" is the exit condition
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
```
Setting this condition to an extremely high value, won't work:
```js example-bad
function loop(x) {
if (x >= 1000000000000) return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
```
This recursive function is missing a base case. As there is no exit condition, the
function will call itself infinitely.
```js example-bad
function loop(x) {
// The base case is missing
loop(x + 1); // Recursive call
}
loop(0);
// InternalError: too much recursion
```
### Class error: too much recursion
```js example-bad
class Person {
constructor() {}
set name(name) {
this.name = name; // Recursive call
}
}
const tony = new Person();
tony.name = "Tonisha"; // InternalError: too much recursion
```
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.
```js example-bad
class Person {
get name() {
return this.name; // Recursive call
}
}
```
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.
```js
class Person {
constructor() {}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const tony = new Person();
tony.name = "Tonisha";
console.log(tony);
```
## See also
- {{Glossary("Recursion")}}
- [Recursive functions](/en-US/docs/Web/JavaScript/Guide/Functions#recursion)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/strict_non_simple_params/index.md | ---
title: 'SyntaxError: "use strict" not allowed in function with non-simple parameters'
slug: Web/JavaScript/Reference/Errors/Strict_non_simple_params
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "`"use strict"` not allowed in function" occurs
when a `"use strict"` directive is used at the top of a function with
{{jsxref("Functions/Default_parameters", "default parameters", "", 1)}},
{{jsxref("Functions/rest_parameters", "rest parameters", "", 1)}}, or
{{jsxref("Operators/Destructuring_assignment", "destructuring parameters", "", 1)}}.
## Message
```plain
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based)
SyntaxError: "use strict" not allowed in function with default parameter (Firefox)
SyntaxError: "use strict" not allowed in function with rest parameter (Firefox)
SyntaxError: "use strict" not allowed in function with destructuring parameter (Firefox)
SyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
A `"use strict"` directive is written at the top of a function that has one
of the following parameters:
- {{jsxref("Functions/Default_parameters", "Default parameters", "", 1)}}
- {{jsxref("Functions/rest_parameters", "Rest parameters", "", 1)}}
- {{jsxref("Operators/Destructuring_assignment", "Destructuring parameters", "", 1)}}
A `"use strict"` directive is not allowed at the top of such functions per
the ECMAScript specification.
## Examples
### Function statement
In this case, the function `sum` has default parameters `a=1` and
`b=2`:
```js-nolint example-bad
function sum(a = 1, b = 2) {
// SyntaxError: "use strict" not allowed in function with default parameter
"use strict";
return a + b;
}
```
If the function should be in [strict mode](/en-US/docs/Web/JavaScript/Reference/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:
```js example-good
"use strict";
function sum(a = 1, b = 2) {
return a + b;
}
```
### Function expression
A function expression can use yet another workaround:
```js-nolint example-bad
const sum = function sum([a, b]) {
// SyntaxError: "use strict" not allowed in function with destructuring parameter
"use strict";
return a + b;
};
```
This can be converted to the following expression:
```js example-good
const sum = (function () {
"use strict";
return function sum([a, b]) {
return a + b;
};
})();
```
### Arrow function
If an arrow function needs to access the `this` variable, you can use the
arrow function as the enclosing function:
```js-nolint example-bad
const callback = (...args) => {
// SyntaxError: "use strict" not allowed in function with rest parameter
"use strict";
return this.run(args);
};
```
This can be converted to the following expression:
```js example-good
const callback = (() => {
"use strict";
return (...args) => {
return this.run(args);
};
})();
```
## See also
- {{jsxref("Strict_mode", "Strict mode", "", 1)}}
- {{jsxref("Statements/function", "function statement", "", 1)}}
- {{jsxref("Operators/function", "function expression", "", 1)}}
- {{jsxref("Functions/Default_parameters", "Default parameters", "", 1)}}
- {{jsxref("Functions/rest_parameters", "Rest parameters", "", 1)}}
- {{jsxref("Operators/Destructuring_assignment", "Destructuring parameters", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/undefined_prop/index.md | ---
title: 'ReferenceError: reference to undefined property "x"'
slug: Web/JavaScript/Reference/Errors/Undefined_prop
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript warning "reference to undefined property" occurs when a script attempted
to access an object property which doesn't exist.
## Message
```plain
ReferenceError: reference to undefined property "x" (Firefox)
```
## Error type
(Firefox only) {{jsxref("ReferenceError")}} warning which is reported only if
`javascript.options.strict` preference is set to `true`.
## What went wrong?
The script attempted to access an object property which doesn't exist. There are two
ways to access properties; see the [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) reference page to learn more about them.
## Examples
### Invalid cases
In this case, the property `bar` is an undefined property, so a
`ReferenceError` will occur.
```js example-bad
const foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"
```
### Valid cases
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 {{jsxref("Operators/in", "in")}} operator,
or the {{jsxref("Object.hasOwn()")}} method, like this:
```js example-good
const foo = {};
// Define the bar property
foo.bar = "moon";
console.log(foo.bar); // "moon"
// Test to be sure bar exists before accessing it
if (Object.hasOwn(foo, "bar")) {
console.log(foo.bar);
}
```
## See also
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.