code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
r None
`grid.place` Place an Object within a Frame
--------------------------------------------
### Description
These functions provide a simpler (and faster) alternative to the `grid.pack()` and `packGrob` functions. They can be used to place objects within the existing rows and columns of a frame layout. They do not provide the ability to add new rows and columns nor do they affect the heights and widths of the rows and columns.
### Usage
```
grid.place(gPath, grob, row = 1, col = 1, redraw = TRUE)
placeGrob(frame, grob, row = NULL, col = NULL)
```
### Arguments
| | |
| --- | --- |
| `gPath` | A gPath object, which specifies a frame on the display list. |
| `frame` | An object of class `frame`, typically the output from a call to `grid.frame`. |
| `grob` | An object of class `grob`. The object to be placed. |
| `row` | Which row to add the object to. Must be between 1 and the-number-of-rows-currently-in-the-frame. |
| `col` | Which col to add the object to. Must be between 1 and the-number-of-cols-currently-in-the-frame. |
| `redraw` | A boolean indicating whether the output should be updated. |
### Details
`placeGrob` modifies the given frame grob and returns the modified frame grob.
`grid.place` destructively modifies a frame grob on the display list (and redraws the display list if `redraw` is `TRUE`).
### Value
`placeGrob` returns a frame grob, but `grid.place` returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`<grid.frame>`, `<grid.pack>`, `<grid.edit>`, and `[gPath](gpath)`.
r None
`unitType` Return the Units of a Unit Object
---------------------------------------------
### Description
This function returns the units of a unit object.
### Usage
```
unitType(x, recurse = FALSE)
```
### Arguments
| | |
| --- | --- |
| `x` | A unit object. |
| `recurse` | Whether to recurse into complex units. |
### Value
For simple units, this will be just a vector of coordinate systems, like `"inches"` or `"npc"`.
More complex units that involve an operation on units return an operator, like `"sum"`, `"min"`, or `"max"`.
When `recurse = TRUE`, the result is always a list and more complex units generate sublists (see the Examples below).
### Author(s)
Thomas Lin Pedersen and Paul Murrell
### See Also
`<unit>`
### Examples
```
u <- unit(1:5, c("cm", "mm", "in", "pt", "null"))
unitType(u)
unitType(unit(1, "npc"))
unitType(unit(1:3/4, "npc"))
unitType(unit(1:3/4, "npc") + unit(1, "inches"))
unitType(min(unit(0.5, "npc"), unit(1, "inches")))
unitType(unit.c(unit(0.5, "npc"), unit(2, "inches") + unit(1:3/4, "npc"),
unit(1, "strwidth", "hi there")))
unitType(min(unit(1, "in"), unit(1, "npc") + unit(1, "mm")))
unitType(u, recurse=TRUE)
unitType(unit(1, "npc"), recurse=TRUE)
unitType(unit(1:3/4, "npc"), recurse=TRUE)
unitType(unit(1:3/4, "npc") + unit(1, "inches"), recurse=TRUE)
unitType(min(unit(0.5, "npc"), unit(1, "inches")), recurse=TRUE)
unitType(unit.c(unit(0.5, "npc"), unit(2, "inches") + unit(1:3/4, "npc"),
unit(1, "strwidth", "hi there")), recurse=TRUE)
unitType(min(unit(1, "in"), unit(1, "npc") + unit(1, "mm")), recurse=TRUE)
unlist(unitType(min(unit(1, "in"), unit(1, "npc") + unit(1, "mm")),
recurse=TRUE))
```
r None
`grid.frame` Create a Frame for Packing Objects
------------------------------------------------
### Description
These functions, together with `grid.pack`, `grid.place`, `packGrob`, and `placeGrob` are part of a GUI-builder-like interface to constructing graphical images. The idea is that you create a frame with this function then use `grid.pack` or whatever to pack/place objects into the frame.
### Usage
```
grid.frame(layout=NULL, name=NULL, gp=gpar(), vp=NULL, draw=TRUE)
frameGrob(layout=NULL, name=NULL, gp=gpar(), vp=NULL)
```
### Arguments
| | |
| --- | --- |
| `layout` | A Grid layout, or NULL. This can be used to initialise the frame with a number of rows and columns, with initial widths and heights, etc. |
| `name` | A character identifier. |
| `vp` | An object of class `viewport`, or NULL. |
| `gp` | An object of class `"gpar"`; typically the output from a call to the function `<gpar>`. |
| `draw` | Should the frame be drawn. |
### Details
Both functions create a frame grob (a graphical object describing a frame), but only `grid.frame()` draws the frame (and then only if `draw` is `TRUE`). Nothing will actually be drawn, but it will put the frame on the display list, which means that the output will be dynamically updated as objects are packed into the frame. Possibly useful for debugging.
### Value
A frame grob. `grid.frame()` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
`<grid.pack>`
### Examples
```
grid.newpage()
grid.frame(name="gf", draw=TRUE)
grid.pack("gf", rectGrob(gp=gpar(fill="grey")), width=unit(1, "null"))
grid.pack("gf", textGrob("hi there"), side="right")
```
r None
`absolute.size` Absolute Size of a Grob
----------------------------------------
### Description
This function converts a unit object into absolute units. Absolute units are unaffected, but non-absolute units are converted into `"null"` units.
### Usage
```
absolute.size(unit)
```
### Arguments
| | |
| --- | --- |
| `unit` | An object of class `"unit"`. |
### Details
Absolute units are things like `"inches"`, `"cm"`, and `"lines"`. Non-absolute units are `"npc"` and `"native"`.
This function is designed to be used in `widthDetails` and `heightDetails` methods.
### Value
An object of class `"unit"`.
### Author(s)
Paul Murrell
### See Also
`[widthDetails](widthdetails)` and `[heightDetails](widthdetails)` methods.
r None
`grid.show.layout` Draw a Diagram of a Grid Layout
---------------------------------------------------
### Description
This function uses Grid graphics to draw a diagram of a Grid layout.
### Usage
```
grid.show.layout(l, newpage=TRUE, vp.ex = 0.8, bg = "light grey",
cell.border = "blue", cell.fill = "light blue",
cell.label = TRUE, label.col = "blue",
unit.col = "red", vp = NULL, ...)
```
### Arguments
| | |
| --- | --- |
| `l` | A Grid layout object. |
| `newpage` | A logical value indicating whether to move on to a new page before drawing the diagram. |
| `vp.ex` | positive number, typically in *(0,1]*, specifying the scaling of the layout. |
| `bg` | The colour used for the background. |
| `cell.border` | The colour used to draw the borders of the cells in the layout. |
| `cell.fill` | The colour used to fill the cells in the layout. |
| `cell.label` | A logical indicating whether the layout cells should be labelled. |
| `label.col` | The colour used for layout cell labels. |
| `unit.col` | The colour used for labelling the widths/heights of columns/rows. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments passed to `format` for formatting the layout width and height annotations. |
### Details
A viewport is created within `vp` to provide a margin for annotation, and the layout is drawn within that new viewport. The margin is filled with light grey, the new viewport is filled with white and framed with a black border, and the layout regions are filled with light blue and framed with a blue border. The diagram is annotated with the widths and heights (including units) of the columns and rows of the layout using red text. (All colours are defaults and may be customised via function arguments.)
### Value
None.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`, `<grid.layout>`
### Examples
```
## Diagram of a simple layout
grid.show.layout(grid.layout(4,2,
heights=unit(rep(1, 4),
c("lines", "lines", "lines", "null")),
widths=unit(c(1, 1), "inches")))
```
r None
`grid.grep` Search for grobs
-----------------------------
### Description
Given a gPath, find all matching grobs on the display list or within a given grob.
### Usage
```
grid.grep(path, x = NULL, grobs = TRUE, viewports = FALSE,
strict = FALSE, grep = FALSE, global = FALSE,
no.match = character())
```
### Arguments
| | |
| --- | --- |
| `path` | a gPath. |
| `x` | a grob or `NULL`. If `NULL`, the display list is searched. |
| `grobs` | A logical value indicating whether to search for grobs. |
| `viewports` | A logical value indicating whether to search for viewports. |
| `strict` | A boolean indicating whether the `path` must be matched exactly. |
| `grep` | Whether the `path` should be treated as a regular expression. |
| `global` | A boolean indicating whether the function should affect just the first match of the `path`, or whether all matches should be affected. |
| `no.match` | The value to return if no matches are found. |
### Value
Either a gPath or, if `global` is `TRUE` a list of gPaths. If there are no matches, `no.match` is returned.
### See Also
grid.ls()
### Examples
```
# A gTree, called "grandparent", with child gTree,
# called "parent", with childrenvp vpStack (vp2 within vp1)
# and child grob, called "child", with vp vpPath (down to vp2)
sampleGTree <- gTree(name="grandparent",
children=gList(gTree(name="parent",
children=gList(grob(name="child", vp="vp1::vp2")),
childrenvp=vpStack(viewport(name="vp1"),
viewport(name="vp2")))))
# Searching for grobs
grid.grep("parent", sampleGTree)
grid.grep("parent", sampleGTree, strict=TRUE)
grid.grep("grandparent", sampleGTree, strict=TRUE)
grid.grep("grandparent::parent", sampleGTree)
grid.grep("parent::child", sampleGTree)
grid.grep("[a-z]", sampleGTree, grep=TRUE)
grid.grep("[a-z]", sampleGTree, grep=TRUE, global=TRUE)
# Searching for viewports
grid.grep("vp1", sampleGTree, viewports=TRUE)
grid.grep("vp2", sampleGTree, viewports=TRUE)
grid.grep("vp", sampleGTree, viewports=TRUE, grep=TRUE)
grid.grep("vp2", sampleGTree, viewports=TRUE, strict=TRUE)
grid.grep("vp1::vp2", sampleGTree, viewports=TRUE)
# Searching for both
grid.grep("[a-z]", sampleGTree, viewports=TRUE, grep=TRUE, global=TRUE)
```
r None
`grid.draw` Draw a grid grob
-----------------------------
### Description
Produces graphical output from a graphical object.
### Usage
```
grid.draw(x, recording=TRUE)
```
### Arguments
| | |
| --- | --- |
| `x` | An object of class `"grob"` or NULL. |
| `recording` | A logical value to indicate whether the drawing operation should be recorded on the Grid display list. |
### Details
This is a generic function with methods for grob and gTree objects.
The grob and gTree methods automatically push any viewports in a `vp` slot and automatically apply any `gpar` settings in a `gp` slot. In addition, the gTree method pushes and ups any viewports in a `childrenvp` slot and automatically calls `grid.draw` for any grobs in a `children` slot.
The methods for grob and gTree call the generic hook functions `preDrawDetails`, `drawDetails`, and `postDrawDetails` to allow classes derived from grob or gTree to perform additional viewport pushing/popping and produce additional output beyond the default behaviour for grobs and gTrees.
### Value
None.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)`.
### Examples
```
grid.newpage()
## Create a graphical object, but don't draw it
l <- linesGrob()
## Draw it
grid.draw(l)
```
r None
`calcStringMetric` Calculate Metric Information for Text
---------------------------------------------------------
### Description
This function returns the ascent, descent, and width metric information for a character or expression vector.
### Usage
```
calcStringMetric(text)
```
### Arguments
| | |
| --- | --- |
| `text` | A character or expression vector. |
### Value
A list with three numeric components named ascent, descent, and width. All values are in inches.
### WARNING
The metric information from this function is based on the font settings that are in effect when this function is called. It will not necessarily correspond to the metric information of any text that is drawn on the page.
### Author(s)
Paul Murrell
### See Also
`[stringAscent](stringwidth)`, `[stringDescent](stringwidth)`, `[grobAscent](grobwidth)`, and `[grobDescent](grobwidth)`.
### Examples
```
grid.newpage()
grid.segments(.01, .5, .99, .5, gp=gpar(col="grey"))
metrics <- calcStringMetric(letters)
grid.rect(x=1:26/27,
width=unit(metrics$width, "inches"),
height=unit(metrics$ascent, "inches"),
just="bottom",
gp=gpar(col="red"))
grid.rect(x=1:26/27,
width=unit(metrics$width, "inches"),
height=unit(metrics$descent, "inches"),
just="top",
gp=gpar(col="red"))
grid.text(letters, x=1:26/27, just="bottom")
test <- function(x) {
grid.text(x, just="bottom")
metric <- calcStringMetric(x)
if (is.character(x)) {
grid.rect(width=unit(metric$width, "inches"),
height=unit(metric$ascent, "inches"),
just="bottom",
gp=gpar(col=rgb(1,0,0,.5)))
grid.rect(width=unit(metric$width, "inches"),
height=unit(metric$descent, "inches"),
just="top",
gp=gpar(col=rgb(1,0,0,.5)))
} else {
grid.rect(width=unit(metric$width, "inches"),
y=unit(.5, "npc") + unit(metric[2], "inches"),
height=unit(metric$ascent, "inches"),
just="bottom",
gp=gpar(col=rgb(1,0,0,.5)))
grid.rect(width=unit(metric$width, "inches"),
height=unit(metric$descent, "inches"),
just="bottom",
gp=gpar(col=rgb(1,0,0,.5)))
}
}
tests <- list("t",
"test",
"testy",
"test\ntwo",
expression(x),
expression(y),
expression(x + y),
expression(a + b),
expression(atop(x + y, 2)))
grid.newpage()
nrowcol <- n2mfrow(length(tests))
pushViewport(viewport(layout=grid.layout(nrowcol[1], nrowcol[2]),
gp=gpar(cex=5, lwd=.5)))
for (i in 1:length(tests)) {
col <- (i - 1) %% nrowcol[2] + 1
row <- (i - 1) %/% nrowcol[2] + 1
pushViewport(viewport(layout.pos.row=row, layout.pos.col=col))
test(tests[[i]])
popViewport()
}
```
r None
`unit` Function to Create a Unit Object
----------------------------------------
### Description
This function creates a unit object — a vector of unit values. A unit value is typically just a single numeric value with an associated unit.
### Usage
```
unit(x, units, data=NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector. |
| `units` | A character vector specifying the units for the corresponding numeric values. |
| `data` | This argument is used to supply extra information for special `unit` types. |
### Details
Unit objects allow the user to specify locations and dimensions in a large number of different coordinate systems. All drawing occurs relative to a viewport and the `units` specifies what coordinate system to use within that viewport.
Possible `units` (coordinate systems) are:
`"npc"`
Normalised Parent Coordinates (the default). The origin of the viewport is (0, 0) and the viewport has a width and height of 1 unit. For example, (0.5, 0.5) is the centre of the viewport.
`"cm"`
Centimetres.
`"inches"`
Inches. 1 in = 2.54 cm.
`"mm"`
Millimetres. 10 mm = 1 cm.
`"points"`
Points. 72.27 pt = 1 in.
`"picas"`
Picas. 1 pc = 12 pt.
`"bigpts"`
Big Points. 72 bp = 1 in.
`"dida"`
Dida. 1157 dd = 1238 pt.
`"cicero"`
Cicero. 1 cc = 12 dd.
`"scaledpts"`
Scaled Points. 65536 sp = 1 pt.
`"lines"`
Lines of text. Locations and dimensions are in terms of multiples of the default text size of the viewport (as specified by the viewport's `fontsize` and `lineheight`).
`"char"`
Multiples of nominal font height of the viewport (as specified by the viewport's `fontsize`).
`"native"`
Locations and dimensions are relative to the viewport's `xscale` and `yscale`.
`"snpc"`
Square Normalised Parent Coordinates. Same as Normalised Parent Coordinates, except gives the same answer for horizontal and vertical locations/dimensions. It uses the *lesser* of npc-width and npc-height. This is useful for making things which are a proportion of the viewport, but have to be square (or have a fixed aspect ratio).
`"strwidth"`
Multiples of the width of the string specified in the `data` argument. The font size is determined by the pointsize of the viewport.
`"strheight"`
Multiples of the height of the string specified in the `data` argument. The font size is determined by the pointsize of the viewport.
`"grobwidth"`
Multiples of the width of the grob specified in the `data` argument.
`"grobheight"`
Multiples of the height of the grob specified in the `data` argument.
A number of variations are also allowed for the most common units. For example, it is possible to use `"in"` or `"inch"` instead of `"inches"` and `"centimetre"` or `"centimeter"` instead of `"cm"`.
A special `units` value of `"null"` is also allowed, but only makes sense when used in specifying widths of columns or heights of rows in grid layouts (see `<grid.layout>`).
The `data` argument must be a list when the `unit.length()` is greater than 1. For example,
```
unit(rep(1, 3), c("npc", "strwidth", "inches"),
data = list(NULL, "my string", NULL))
```
.
It is possible to subset unit objects in the normal way and to perform subassignment (see the examples), but a special function `unit.c` is provided for combining unit objects.
Certain arithmetic and summary operations are defined for unit objects. In particular, it is possible to add and subtract unit objects (e.g., `unit(1, "npc") - unit(1, "inches")`), and to specify the minimum or maximum of a list of unit objects (e.g., `min(unit(0.5, "npc"), unit(1,
"inches"))`).
There is a `format` method for units, which should respond to the arguments for the default `format` method, e.g., `digits` to control the number of significant digits printed for numeric values.
### Value
An object of class `"unit"`.
### WARNING
There is a special function `unit.c` for concatenating several unit objects.
The `c` function will not give the right answer.
There used to be `"mylines"`, `"mychar"`, `"mystrwidth"`, `"mystrheight"` units. These will still be accepted, but work exactly the same as `"lines"`, `"char"`, `"strwidth"`, `"strheight"`.
### Author(s)
Paul Murrell
### See Also
`<unit.c>`
### Examples
```
unit(1, "npc")
unit(1:3/4, "npc")
unit(1:3/4, "npc") + unit(1, "inches")
min(unit(0.5, "npc"), unit(1, "inches"))
unit.c(unit(0.5, "npc"), unit(2, "inches") + unit(1:3/4, "npc"),
unit(1, "strwidth", "hi there"))
x <- unit(1:5, "npc")
x[2:4]
x[2:4] <- unit(1, "mm")
x
```
r None
`grid.rect` Draw rectangles
----------------------------
### Description
These functions create and draw rectangles.
### Usage
```
grid.rect(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = unit(1, "npc"), height = unit(1, "npc"),
just = "centre", hjust = NULL, vjust = NULL,
default.units = "npc", name = NULL,
gp=gpar(), draw = TRUE, vp = NULL)
rectGrob(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = unit(1, "npc"), height = unit(1, "npc"),
just = "centre", hjust = NULL, vjust = NULL,
default.units = "npc", name = NULL,
gp=gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-location. |
| `y` | A numeric vector or unit object specifying y-location. |
| `width` | A numeric vector or unit object specifying width. |
| `height` | A numeric vector or unit object specifying height. |
| `just` | The justification of the rectangle relative to its (x, y) location. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left alignment and 1 means right alignment. |
| `hjust` | A numeric vector specifying horizontal justification. If specified, overrides the `just` setting. |
| `vjust` | A numeric vector specifying vertical justification. If specified, overrides the `just` setting. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a rect grob (a graphical object describing rectangles), but only `grid.rect` draws the rectangles (and then only if `draw` is `TRUE`).
### Value
A rect grob. `grid.rect` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
| programming_docs |
r None
`grobCoords` Calculate Points on the Perimeter of a Grob
---------------------------------------------------------
### Description
These functions calculate points along the perimeter (or length) of a grob.
### Usage
```
grobCoords(x, closed, ...)
grobPoints(x, closed, ...)
emptyCoords
isEmptyCoords(coords)
```
### Arguments
| | |
| --- | --- |
| `x` | A grob object. |
| `closed` | Whether we are asking for points along the perimeter of a closed object or points along the length of an open object. Some grobs (e.g., X-splines) can do both. |
| `...` | Arguments to be used by methods. |
| `coords` | A set of grob coordinates (as generated by `grobCoords`). |
### Details
Custom grobs can write their own methods for `grobPoints`.
The `emptyCoords` object can be used to return a "null" result (e.g., when asking for `closed` coordinates on an open line) and the `isEmptyCoords` function can be used to check for "null" results.
### Value
A list of lists with components `x` and `y`. All locations are in inches relative to the current grid viewport.
### Author(s)
Paul Murrell
r None
`valid.just` Validate a Justification
--------------------------------------
### Description
Utility functions for determining whether a justification specification is valid and for resolving a single justification value from a combination of character and numeric values.
### Usage
```
valid.just(just)
resolveHJust(just, hjust)
resolveVJust(just, vjust)
```
### Arguments
| | |
| --- | --- |
| `just` | A justification either as a character value, e.g., `"left"`, or as a numeric value, e.g., 0. |
| `hjust` | A numeric horizontal justification |
| `vjust` | A numeric vertical justification |
### Details
These functions may be useful within a `validDetails` method when writing a new grob class.
### Value
A numeric representation of the justification (e.g., `"left"` becomes 0, `"right"` becomes 1, etc, ...). An error is given if the justification is not valid.
### Author(s)
Paul Murrell
r None
`grid.bezier` Draw a Bezier Curve
----------------------------------
### Description
These functions create and draw Bezier Curves (a curve drawn relative to 4 control points).
### Usage
```
grid.bezier(...)
bezierGrob(x = c(0, 0.5, 1, 0.5), y = c(0.5, 1, 0.5, 0),
id = NULL, id.lengths = NULL,
default.units = "npc", arrow = NULL,
name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-locations of spline control points. |
| `y` | A numeric vector or unit object specifying y-locations of spline control points. |
| `id` | A numeric vector used to separate locations in `x` and `y` into multiple beziers. All locations with the same `id` belong to the same bezier. |
| `id.lengths` | A numeric vector used to separate locations in `x` and `y` into multiple bezier. Specifies consecutive blocks of locations which make up separate beziers. |
| `default.units` | A string indicating the default units to use if `x` or `y` are only given as numeric vectors. |
| `arrow` | A list describing arrow heads to place at either end of the bezier, as produced by the `arrow` function. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments to be passed to `bezierGrob`. |
### Details
Both functions create a beziergrob (a graphical object describing a Bezier curve), but only `grid.bezier` draws the Bezier curve.
A Bezier curve is a line drawn relative to 4 control points.
Missing values are not allowed for `x` and `y` (i.e., it is not valid for a control point to be missing).
The curve is currently drawn using an approximation based on X-splines.
### Value
A grob object.
### See Also
[Grid](grid), `<viewport>`, `<arrow>`.
`<grid.xspline>`.
### Examples
```
x <- c(0.2, 0.2, 0.4, 0.4)
y <- c(0.2, 0.4, 0.4, 0.2)
grid.newpage()
grid.bezier(x, y)
grid.bezier(c(x, x + .4), c(y + .4, y + .4),
id=rep(1:2, each=4))
grid.segments(.4, .6, .6, .6)
grid.bezier(x, y,
gp=gpar(lwd=3, fill="black"),
arrow=arrow(type="closed"),
vp=viewport(x=.9))
```
r None
`grobX` Create a Unit Describing a Grob Boundary Location
----------------------------------------------------------
### Description
These functions create a unit object describing a location somewhere on the boundary of a grob. They are generic.
### Usage
```
grobX(x, theta)
grobY(x, theta)
```
### Arguments
| | |
| --- | --- |
| `x` | A grob, or gList, or gTree, or gPath. |
| `theta` | An angle indicating where the location is on the grob boundary. Can be one of `"east"`, `"north"`, `"west"`, or `"south"`, which correspond to angles 0, 90, 180, and 270, respectively. |
### Details
The angle is anti-clockwise with zero corresponding to a line with an origin centred between the extreme points of the shape, and pointing at 3 o'clock.
If the grob describes a single shape, the boundary value should correspond to the exact edge of the shape.
If the grob describes multiple shapes, the boundary value will either correspond to the edge of a bounding box around all of the shapes described by the grob (for multiple rectangles, circles, xsplines, or text), or to a convex hull around all vertices of all shapes described by the grob (for multiple polygons, points, lines, polylines, and segments).
Points grobs are currently a special case because the convex hull is based on the data symbol *locations* and does not take into account the extent of the data symbols themselves.
The extents of any arrow heads are currently *not* taken into account.
### Value
A unit object.
### Author(s)
Paul Murrell
### See Also
`<unit>` and `[grobWidth](grobwidth)`
r None
`grid.clip` Set the Clipping Region
------------------------------------
### Description
These functions set the clipping region within the current viewport *without* altering the current coordinate system.
### Usage
```
grid.clip(...)
clipGrob(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = unit(1, "npc"), height = unit(1, "npc"),
just = "centre", hjust = NULL, vjust = NULL,
default.units = "npc", name = NULL, vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-location. |
| `y` | A numeric vector or unit object specifying y-location. |
| `width` | A numeric vector or unit object specifying width. |
| `height` | A numeric vector or unit object specifying height. |
| `just` | The justification of the clip rectangle relative to its (x, y) location. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left alignment and 1 means right alignment. |
| `hjust` | A numeric vector specifying horizontal justification. If specified, overrides the `just` setting. |
| `vjust` | A numeric vector specifying vertical justification. If specified, overrides the `just` setting. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments passed to `clipGrob`. |
### Details
Both functions create a clip rectangle (a graphical object describing a clip rectangle), but only `grid.clip` enforces the clipping.
Pushing or popping a viewport *always* overrides the clip region set by a clip grob, regardless of whether that viewport explicitly enforces a clipping region.
### Value
`clipGrob` returns a clip grob.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
# draw across entire viewport, but clipped
grid.clip(x = 0.3, width = 0.1)
grid.lines(gp=gpar(col="green", lwd=5))
# draw across entire viewport, but clipped (in different place)
grid.clip(x = 0.7, width = 0.1)
grid.lines(gp=gpar(col="red", lwd=5))
# Viewport sets new clip region
pushViewport(viewport(width=0.5, height=0.5, clip=TRUE))
grid.lines(gp=gpar(col="grey", lwd=3))
# Return to original viewport; get
# clip region from previous grid.clip()
# (NOT from previous viewport clip region)
popViewport()
grid.lines(gp=gpar(col="black"))
```
r None
`grid.copy` Make a Copy of a Grid Graphical Object
---------------------------------------------------
### Description
This function is redundant and will disappear in future versions.
### Usage
```
grid.copy(grob)
```
### Arguments
| | |
| --- | --- |
| `grob` | A grob object. |
### Value
A copy of the grob object.
### Author(s)
Paul Murrell
### See Also
`[grid.grob](grid-defunct)`.
r None
`unit.rep` Replicate Elements of Unit Objects
----------------------------------------------
### Description
Replicates the units according to the values given in `times` and `length.out`.
This function has been deprecated in favour of a unit method for the generic `rep` function.
### Usage
```
unit.rep(x, ...)
```
### Arguments
| | |
| --- | --- |
| `x` | An object of class `"unit"`. |
| `...` | arguments to be passed to `[rep](../../base/html/rep)` such as `times` and `length.out`. |
### Value
An object of class `"unit"`.
### Author(s)
Paul Murrell
### See Also
`[rep](../../base/html/rep)`
### Examples
```
rep(unit(1:3, "npc"), 3)
rep(unit(1:3, "npc"), 1:3)
rep(unit(1:3, "npc") + unit(1, "inches"), 3)
rep(max(unit(1:3, "npc") + unit(1, "inches")), 3)
rep(max(unit(1:3, "npc") + unit(1, "strwidth", "a"))*4, 3)
rep(unit(1:3, "npc") + unit(1, "strwidth", "a")*4, 3)
```
r None
`explode` Explode a path into its components.
----------------------------------------------
### Description
Explode a viewport path or grob path into its components.
### Usage
```
explode(x)
## S3 method for class 'character'
explode(x)
## S3 method for class 'path'
explode(x)
```
### Arguments
| | |
| --- | --- |
| `x` | Typically a viewport path or a grob path, but a character vector containing zero or more path separators may also be given. |
### Value
A character vector.
### See Also
`[vpPath](vppath)`, `[gPath](gpath)`.
### Examples
```
explode("vp1::vp2")
explode(vpPath("vp1", "vp2"))
```
r None
`grid.circle` Draw a Circle
----------------------------
### Description
Functions to create and draw a circle.
### Usage
```
grid.circle(x=0.5, y=0.5, r=0.5, default.units="npc", name=NULL,
gp=gpar(), draw=TRUE, vp=NULL)
circleGrob(x=0.5, y=0.5, r=0.5, default.units="npc", name=NULL,
gp=gpar(), vp=NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-locations. |
| `y` | A numeric vector or unit object specifying y-locations. |
| `r` | A numeric vector or unit object specifying radii. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a circle grob (a graphical object describing a circle), but only `grid.circle()` draws the circle (and then only if `draw` is `TRUE`).
The radius may be given in any units; if the units are *relative* (e.g., `"npc"` or `"native"`) then the radius will be different depending on whether it is interpreted as a width or as a height. In such cases, the smaller of these two values will be the result. To see the effect, type `grid.circle()` and adjust the size of the window.
What happens for very small radii is device-dependent: the circle may become invisible or be shown at a fixed minimum size. Circles of zero radius will not be plotted.
### Value
A circle grob. `grid.circle()` returns the value invisibly.
### Warning
Negative values for the radius are silently converted to their absolute value.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
r None
`resolveRasterSize` Utility function to resolve the size of a raster grob
--------------------------------------------------------------------------
### Description
Determine the width and height of a raster grob when one or both are not given explicitly.
The result depends on both the aspect ratio of the raster image and the aspect ratio of the physical drawing context, so the result is only valid for the drawing context in which this function is called.
### Usage
```
resolveRasterSize(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A raster grob |
### Details
A raster grob can be specified with width and/or height of `NULL`, which means that the size at which the raster is drawn will be decided at drawing time.
### Value
A raster grob, with explicit width and height.
### See Also
`<grid.raster>`
### Examples
```
# Square raster
rg <- rasterGrob(matrix(0))
# Fill the complete page (if page is square)
grid.newpage()
resolveRasterSize(rg)$height
grid.draw(rg)
# Forced to fit tall thin region
grid.newpage()
pushViewport(viewport(width=.1))
resolveRasterSize(rg)$height
grid.draw(rg)
```
r None
`depth` Determine the number of levels in an object.
-----------------------------------------------------
### Description
Determine the number of levels in a viewport stack or tree, in a viewport path, or in a grob path.
### Usage
```
depth(x, ...)
## S3 method for class 'viewport'
depth(x, ...)
## S3 method for class 'path'
depth(x, ...)
```
### Arguments
| | |
| --- | --- |
| `x` | Typically a viewport or viewport stack or viewport tree or viewport list, or a viewport path, or a grob path. |
| `...` | Arguments used by other methods. |
### Details
Depths of paths are pretty straightforward because they contain no branchings. The depth of a viewport stack is the sum of the depths of the components of the stack. The depth of a viewport tree is the depth of the parent plus the depth of the children. The depth of a viewport list is the depth of the last component of the list.
### Value
An integer value.
### See Also
`<viewport>`, `[vpPath](vppath)`, `[gPath](gpath)`.
### Examples
```
vp <- viewport()
depth(vp)
depth(vpStack(vp, vp))
depth(vpList(vpStack(vp, vp), vp))
depth(vpPath("vp"))
depth(vpPath("vp1", "vp2"))
```
r None
`Grid` Grid Graphics
---------------------
### Description
General information about the grid graphics package.
### Details
Grid graphics provides an alternative to the standard R graphics. The user is able to define arbitrary rectangular regions (called *viewports*) on the graphics device and define a number of coordinate systems for each region. Drawing can be specified to occur in any viewport using any of the available coordinate systems.
Grid graphics and standard R graphics do not mix!
Type `library(help = grid)` to see a list of (public) Grid graphics functions.
### Author(s)
Paul Murrell
### See Also
`<viewport>`, `<grid.layout>`, and `<unit>`.
### Examples
```
## Diagram of a simple layout
grid.show.layout(grid.layout(4,2,
heights=unit(rep(1, 4),
c("lines", "lines", "lines", "null")),
widths=unit(c(1, 1), "inches")))
## Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
width=unit(1, "inches"), height=unit(1, "inches")))
## A flash plotting example
grid.multipanel(vp=viewport(0.5, 0.5, 0.8, 0.8))
```
r None
`grid.set` Set a Grid Graphical Object
---------------------------------------
### Description
Replace a grob or a descendant of a grob.
### Usage
```
grid.set(gPath, newGrob, strict = FALSE, grep = FALSE,
redraw = TRUE)
setGrob(gTree, gPath, newGrob, strict = FALSE, grep = FALSE)
```
### Arguments
| | |
| --- | --- |
| `gTree` | A gTree object. |
| `gPath` | A gPath object. For `grid.set` this specifies a grob on the display list. For `setGrob` this specifies a descendant of the specified gTree. |
| `newGrob` | A grob object. |
| `strict` | A boolean indicating whether the gPath must be matched exactly. |
| `grep` | A boolean indicating whether the `gPath` should be treated as a regular expression. Values are recycled across elements of the `gPath` (e.g., `c(TRUE, FALSE)` means that every odd element of the `gPath` will be treated as a regular expression). |
| `redraw` | A logical value to indicate whether to redraw the grob. |
### Details
`setGrob` copies the specified grob and returns a modified grob.
`grid.set` destructively replaces a grob on the display list. If `redraw` is `TRUE` it then redraws everything to reflect the change.
These functions should not normally be called by the user.
### Value
`setGrob` returns a grob object; `grid.set` returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`[grid.grob](grid-defunct)`.
r None
`xDetails` Boundary of a grid grob
-----------------------------------
### Description
These generic functions are used to determine a location on the boundary of a grid grob.
### Usage
```
xDetails(x, theta)
yDetails(x, theta)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
| `theta` | A numeric angle, in degrees, measured anti-clockwise from the 3 o'clock *or* one of the following character strings: `"north"`, `"east"`, `"west"`, `"south"`. |
### Details
The location on the grob boundary is determined by taking a line from the centre of the grob at the angle `theta` and intersecting it with the convex hull of the grob (for the basic grob primitives, the centre is determined as half way between the minimum and maximum values in x and y directions).
These functions are called in the calculation of `"grobx"` and `"groby"` units as produced by the `grobX` and `grobY` functions. Methods should be written for classes derived from grob or gTree where the boundary of the grob can be determined.
### Value
A unit object.
### Author(s)
Paul Murrell
### See Also
`[grobX](grobx)`, `[grobY](grobx)`.
r None
`current.viewport` Get the Current Grid Viewport (Tree)
--------------------------------------------------------
### Description
`current.viewport()` returns the viewport that Grid is going to draw into.
`current.parent` returns the parent of the current viewport.
`current.vpTree` returns the entire Grid viewport tree.
`current.vpPath` returns the viewport path to the current viewport.
`current.transform` returns the transformation matrix for the current viewport.
`current.rotation` returns the (total) rotation for the current viewport.
### Usage
```
current.viewport()
current.parent(n=1)
current.vpTree(all=TRUE)
current.vpPath()
current.transform()
```
### Arguments
| | |
| --- | --- |
| `n` | The number of generations to go up. |
| `all` | A logical value indicating whether the entire viewport tree should be returned. |
### Details
It is possible to get the grandparent of the current viewport (or higher) using the `n` argument to `current.parent()`.
The parent of the ROOT viewport is `NULL`. It is an error to request the grandparent of the ROOT viewport.
If `all` is `FALSE` then `current.vpTree` only returns the subtree below the current viewport.
### Value
A Grid viewport object from `current.viewport` or `current.vpTree`.
`current.transform` returns a 4x4 transformation matrix.
The viewport path returned by `current.vpPath` is `NULL` if the current viewport is the `ROOT` viewport
### Author(s)
Paul Murrell
### See Also
`<viewport>`
### Examples
```
grid.newpage()
pushViewport(viewport(width=0.8, height=0.8, name="A"))
pushViewport(viewport(x=0.1, width=0.3, height=0.6,
just="left", name="B"))
upViewport(1)
pushViewport(viewport(x=0.5, width=0.4, height=0.8,
just="left", name="C"))
pushViewport(viewport(width=0.8, height=0.8, name="D"))
current.vpPath()
upViewport(1)
current.vpPath()
current.vpTree()
current.viewport()
current.vpTree(all=FALSE)
popViewport(0)
```
| programming_docs |
r None
`unit.c` Combine Unit Objects
------------------------------
### Description
This function produces a new unit object by combining the unit objects specified as arguments.
### Usage
```
unit.c(..., check = TRUE)
```
### Arguments
| | |
| --- | --- |
| `...` | An arbitrary number of unit objects. |
| `check` | Should input be checked? If you are certain all arguments are unit objects this can be set to `FALSE` |
### Value
An object of class `unit`.
### Author(s)
Paul Murrell
### See Also
`<unit>`.
r None
`gpar` Handling Grid Graphical Parameters
------------------------------------------
### Description
`gpar()` should be used to create a set of graphical parameter settings. It returns an object of class `"gpar"`. This is basically a list of name-value pairs.
`get.gpar()` can be used to query the current graphical parameter settings.
### Usage
```
gpar(...)
get.gpar(names = NULL)
```
### Arguments
| | |
| --- | --- |
| `...` | Any number of named arguments. |
| `names` | A character vector of valid graphical parameter names. |
### Details
All grid viewports and (predefined) graphical objects have a slot called `gp`, which contains a `"gpar"` object. When a viewport is pushed onto the viewport stack and when a graphical object is drawn, the settings in the `"gpar"` object are enforced. In this way, the graphical output is modified by the `gp` settings until the graphical object has finished drawing, or until the viewport is popped off the viewport stack, or until some other viewport or graphical object is pushed or begins drawing.
The default parameter settings are defined by the ROOT viewport, which takes its settings from the graphics device. These defaults may differ between devices (e.g., the default `fill` setting is different for a PNG device compared to a PDF device).
Valid parameter names are:
| | |
| --- | --- |
| col | Colour for lines and borders. |
| fill | Colour for filling rectangles, polygons, ... |
| alpha | Alpha channel for transparency |
| lty | Line type |
| lwd | Line width |
| lex | Multiplier applied to line width |
| lineend | Line end style (round, butt, square) |
| linejoin | Line join style (round, mitre, bevel) |
| linemitre | Line mitre limit (number greater than 1) |
| fontsize | The size of text (in points) |
| cex | Multiplier applied to fontsize |
| fontfamily | The font family |
| fontface | The font face (bold, italic, ...) |
| lineheight | The height of a line as a multiple of the size of text |
| font | Font face (alias for fontface; for backward compatibility) |
| |
For more details of many of these, see the help for the corresponding graphical parameter `[par](../../graphics/html/par)` in base graphics. (This may have a slightly different name, e.g. `lend`, `ljoin`, `lmitre`, `family`.)
Colours can be specified in one of the forms returned by `[rgb](../../grdevices/html/rgb)`, as a name (see `[colors](../../grdevices/html/colors)`) or as a non-negative integer index into the current [palette](../../grdevices/html/palette) (with zero being taken as transparent). (Negative integer values are now an error.)
The `alpha` setting is combined with the alpha channel for individual colours by multiplying (with both alpha settings normalised to the range 0 to 1).
The `fill` setting can also be a linear gradient or a radial gradient or a pattern (see <patterns>).
The size of text is `fontsize`\*`cex`. The size of a line is `fontsize`\*`cex`\*`lineheight`.
The `cex` setting is cumulative; if a viewport is pushed with a `cex` of 0.5 then another viewport is pushed with a `cex` of 0.5, the effective `cex` is 0.25.
The `alpha` and `lex` settings are also cumulative.
Changes to the `fontfamily` may be ignored by some devices, but is supported by PostScript, PDF, X11, Windows, and Quartz. The `fontfamily` may be used to specify one of the Hershey Font families (e.g., `HersheySerif`) and this specification will be honoured on all devices.
The specification of `fontface` can be an integer or a string. If an integer, then it follows the R base graphics standard: 1 = plain, 2 = bold, 3 = italic, 4 = bold italic. If a string, then valid values are: `"plain"`, `"bold"`, `"italic"`, `"oblique"`, and `"bold.italic"`. For the special case of the HersheySerif font family, `"cyrillic"`, `"cyrillic.oblique"`, and `"EUC"` are also available.
All parameter values can be vectors of multiple values. (This will not always make sense – for example, viewports will only take notice of the first parameter value.)
`get.gpar()` returns all current graphical parameter settings.
### Value
An object of class `"gpar"`.
### Author(s)
Paul Murrell
### See Also
`[Hershey](../../grdevices/html/hershey)`.
### Examples
```
gp <- get.gpar()
utils::str(gp)
## These *do* nothing but produce a "gpar" object:
gpar(col = "red")
gpar(col = "blue", lty = "solid", lwd = 3, fontsize = 16)
get.gpar(c("col", "lty"))
grid.newpage()
vp <- viewport(width = .8, height = .8, gp = gpar(col="blue"))
grid.draw(gTree(children=gList(rectGrob(gp = gpar(col="red")),
textGrob(paste("The rect is its own colour (red)",
"but this text is the colour",
"set by the gTree (green)",
sep = "\n"))),
gp = gpar(col="green"), vp = vp))
grid.text("This text is the colour set by the viewport (blue)",
y = 1, just = c("center", "bottom"),
gp = gpar(fontsize=20), vp = vp)
grid.newpage()
## example with multiple values for a parameter
pushViewport(viewport())
grid.points(1:10/11, 1:10/11, gp = gpar(col=1:10))
popViewport()
```
r None
`drawDetails` Customising grid Drawing
---------------------------------------
### Description
These generic hook functions are called whenever a grid grob is drawn. They provide an opportunity for customising the drawing of a new class derived from grob (or gTree).
### Usage
```
drawDetails(x, recording)
preDrawDetails(x)
postDrawDetails(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
| `recording` | A logical value indicating whether a grob is being added to the display list or redrawn from the display list. |
### Details
These functions are called by the `grid.draw` methods for grobs and gTrees.
`preDrawDetails` is called first during the drawing of a grob. This is where any additional viewports should be pushed (see, for example, `grid:::preDrawDetails.frame`). Note that the default behaviour for grobs is to push any viewports in the `vp` slot, and for gTrees is to also push and up any viewports in the `childrenvp` slot so there is typically nothing to do here.
`drawDetails` is called next and is where any additional calculations and graphical output should occur (see, for example, `grid:::drawDetails.xaxis`). Note that the default behaviour for gTrees is to draw all grobs in the `children` slot so there is typically nothing to do here.
`postDrawDetails` is called last and should reverse anything done in `preDrawDetails` (i.e., pop or up any viewports that were pushed; again, see, for example, `grid:::postDrawDetails.frame`). Note that the default behaviour for grobs is to pop any viewports that were pushed so there is typically nothing to do here.
Note that `preDrawDetails` and `postDrawDetails` are also called in the calculation of `"grobwidth"` and `"grobheight"` units.
### Value
None of these functions are expected to return a value.
### Author(s)
Paul Murrell
### See Also
`<grid.draw>`
r None
`grid.get` Get a Grid Graphical Object
---------------------------------------
### Description
Retrieve a grob or a descendant of a grob.
### Usage
```
grid.get(gPath, strict = FALSE, grep = FALSE, global = FALSE,
allDevices = FALSE)
grid.gget(..., grep = TRUE, global = TRUE)
getGrob(gTree, gPath, strict = FALSE, grep = FALSE, global = FALSE)
```
### Arguments
| | |
| --- | --- |
| `gTree` | A gTree object. |
| `gPath` | A gPath object. For `grid.get` this specifies a grob on the display list. For `getGrob` this specifies a descendant of the specified gTree. |
| `strict` | A boolean indicating whether the gPath must be matched exactly. |
| `grep` | A boolean indicating whether the `gPath` should be treated as a regular expression. Values are recycled across elements of the `gPath` (e.g., `c(TRUE, FALSE)` means that every odd element of the `gPath` will be treated as a regular expression). |
| `global` | A boolean indicating whether the function should affect just the first match of the `gPath`, or whether all matches should be affected. |
| `allDevices` | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED. |
| `...` | Arguments that are passed to `grid.get`. |
### Details
`grid.gget` (`g` for global) is just a convenience wrapper for `grid.get` with different defaults.
### Value
A grob object.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)`, `[getGrob](grid.get)`, `[addGrob](grid.add)`, `[removeGrob](grid.remove)`.
### Examples
```
grid.xaxis(name="xa")
grid.get("xa")
grid.get(gPath("xa", "ticks"))
grid.draw(gTree(name="gt", children=gList(xaxisGrob(name="axis"))))
grid.get(gPath("gt", "axis", "ticks"))
```
r None
`grid.pack` Pack an Object within a Frame
------------------------------------------
### Description
these functions, together with `grid.frame` and `frameGrob` are part of a GUI-builder-like interface to constructing graphical images. The idea is that you create a frame with `grid.frame` or `frameGrob` then use these functions to pack objects into the frame.
### Usage
```
grid.pack(gPath, grob, redraw = TRUE, side = NULL,
row = NULL, row.before = NULL, row.after = NULL,
col = NULL, col.before = NULL, col.after = NULL,
width = NULL, height = NULL,
force.width = FALSE, force.height = FALSE, border = NULL,
dynamic = FALSE)
packGrob(frame, grob, side = NULL,
row = NULL, row.before = NULL, row.after = NULL,
col = NULL, col.before = NULL, col.after = NULL,
width = NULL, height = NULL,
force.width = FALSE, force.height = FALSE, border = NULL,
dynamic = FALSE)
```
### Arguments
| | |
| --- | --- |
| `gPath` | A gPath object, which specifies a frame on the display list. |
| `frame` | An object of class `frame`, typically the output from a call to `grid.frame`. |
| `grob` | An object of class `grob`. The object to be packed. |
| `redraw` | A boolean indicating whether the output should be updated. |
| `side` | One of `"left"`, `"top"`, `"right"`, `"bottom"` to indicate which side to pack the object on. |
| `row` | Which row to add the object to. Must be between 1 and the-number-of-rows-currently-in-the-frame + 1, or `NULL` in which case the object occupies all rows. |
| `row.before` | Add the object to a new row just before this row. |
| `row.after` | Add the object to a new row just after this row. |
| `col` | Which col to add the object to. Must be between 1 and the-number-of-cols-currently-in-the-frame + 1, or `NULL` in which case the object occupies all cols. |
| `col.before` | Add the object to a new col just before this col. |
| `col.after` | Add the object to a new col just after this col. |
| `width` | Specifies the width of the column that the object is added to (rather than allowing the width to be taken from the object). |
| `height` | Specifies the height of the row that the object is added to (rather than allowing the height to be taken from the object). |
| `force.width` | A logical value indicating whether the width of the column that the grob is being packed into should be EITHER the width specified in the call to `grid.pack` OR the maximum of that width and the pre-existing width. |
| `force.height` | A logical value indicating whether the height of the column that the grob is being packed into should be EITHER the height specified in the call to `grid.pack` OR the maximum of that height and the pre-existing height. |
| `border` | A `unit` object of length 4 indicating the borders around the object. |
| `dynamic` | If the width/height is taken from the grob being packed, this boolean flag indicates whether the grobwidth/height unit refers directly to the grob, or uses a gPath to the grob. In the latter case, changes to the grob will trigger a recalculation of the width/height. |
### Details
`packGrob` modifies the given frame grob and returns the modified frame grob.
`grid.pack` destructively modifies a frame grob on the display list (and redraws the display list if `redraw` is `TRUE`).
These are (meant to be) very flexible functions. There are many different ways to specify where the new object is to be added relative to the objects already in the frame. The function checks that the specification is not self-contradictory.
NOTE that the width/height of the row/col that the object is added to is taken from the object itself unless the `width`/`height` is specified.
### Value
`packGrob` returns a frame grob, but `grid.pack` returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`<grid.frame>`, `<grid.place>`, `<grid.edit>`, and `[gPath](gpath)`.
r None
`grid.move.to` Move or Draw to a Specified Position
----------------------------------------------------
### Description
Grid has the notion of a current location. These functions sets that location.
### Usage
```
grid.move.to(x = 0, y = 0, default.units = "npc", name = NULL,
draw = TRUE, vp = NULL)
moveToGrob(x = 0, y = 0, default.units = "npc", name = NULL,
vp = NULL)
grid.line.to(x = 1, y = 1, default.units = "npc",
arrow = NULL, name = NULL,
gp = gpar(), draw = TRUE, vp = NULL)
lineToGrob(x = 1, y = 1, default.units = "npc", arrow = NULL,
name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric value or a unit object specifying an x-value. |
| `y` | A numeric value or a unit object specifying a y-value. |
| `default.units` | A string indicating the default units to use if `x` or `y` are only given as numeric values. |
| `arrow` | A list describing arrow heads to place at either end of the line, as produced by the `arrow` function. |
| `name` | A character identifier. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a move.to/line.to grob (a graphical object describing a move-to/line-to), but only `grid.move.to/line.to()` draws the move.to/line.to (and then only if `draw` is `TRUE`).
### Value
A move.to/line.to grob. `grid.move.to/line.to()` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`, `<arrow>`
### Examples
```
grid.newpage()
grid.move.to(0.5, 0.5)
grid.line.to(1, 1)
grid.line.to(0.5, 0)
pushViewport(viewport(x=0, y=0, width=0.25, height=0.25, just=c("left", "bottom")))
grid.rect()
grid.grill()
grid.line.to(0.5, 0.5)
popViewport()
```
r None
`editViewport` Modify a Viewport
---------------------------------
### Description
This is a convenience function for producing a new viewport from a copy of an existing viewport (by default the current viewport), with specified modifications.
### Usage
```
editViewport(vp=current.viewport(), ...)
```
### Arguments
| | |
| --- | --- |
| `vp` | A viewport object. |
| `...` | Modification of the viewport (should all be valid arguments to the `viewport()` function. |
### Value
A grid viewport object.
### Author(s)
Paul Murrell
### See Also
`<viewport>`.
r None
`grid.grab` Grab the current grid output
-----------------------------------------
### Description
Creates a gTree object from the current grid display list or from a scene generated by user-specified code.
### Usage
```
grid.grab(warn = 2, wrap = wrap.grobs, wrap.grobs = FALSE, ...)
grid.grabExpr(expr, warn = 2, wrap = wrap.grobs, wrap.grobs = FALSE,
width = 7, height = 7, device = offscreen, ...)
```
### Arguments
| | |
| --- | --- |
| `expr` | An expression to be evaluated. Typically, some calls to grid drawing functions. |
| `warn` | An integer specifying the amount of warnings to emit. 0 means no warnings, 1 means warn when it is certain that the grab will not faithfully represent the original scene. 2 means warn if there's any possibility that the grab will not faithfully represent the original scene. |
| `wrap` | A logical indicating how the output should be captured. If `TRUE`, each non-grob element on the display list is captured by wrapping it in a grob. |
| `wrap.grobs` | A logical indicating whether, if we are wrapping elements (`wrap=TRUE`), we should wrap grobs (or just wrap viewports). |
| `width, height` | Size of the device used for temporary rendering. |
| `device` | A function that opens a graphics device for temporary rendering. By default this is an off-screen, in-memory device based on the `pdf` device, but this default device may not be satisfactory when using custom fonts. |
| `...` | arguments passed to gTree, for example, a name and/or class for the gTree that is created. |
### Details
There are four ways to capture grid output as a gTree.
There are two functions for capturing output: use `grid.grab` to capture an existing drawing and `grid.grabExpr` to capture the output from an expression (without drawing anything).
For each of these functions, the output can be captured in two ways. One way tries to be clever and make a gTree with a childrenvp slot containing all viewports on the display list (including those that are popped) and every grob on the display list as a child of the new gTree; each child has a vpPath in the vp slot so that it is drawn in the appropriate viewport. In other words, the gTree contains all elements on the display list, but in a slightly altered form.
The other way, `wrap=TRUE`, is to create a grob for every element on the display list (and make all of those grobs children of the gTree). Only viewports are wrapped unless `wrap.grobs` is also `TRUE`.
The first approach creates a more compact and elegant gTree, which is more flexible to work with, but is not guaranteed to faithfully replicate all possible grid output. The second approach is more brute force, and harder to work with, but is more likely to replicate the original output.
An example of a case that will NOT be replicated by wrapping, with `wrap.grobs=TRUE`, is a scene where the placement of one grob is dependent on another grob (e.g., via `grobX` or `grobWidth`).
### Value
A gTree object.
### See Also
`[gTree](grid.grob)`
### Examples
```
pushViewport(viewport(width=.5, height=.5))
grid.rect()
grid.points(stats::runif(10), stats::runif(10))
popViewport()
grab <- grid.grab()
grid.newpage()
grid.draw(grab)
```
r None
`getNames` List the names of grobs on the display list
-------------------------------------------------------
### Description
Returns a character vector containing the names of all top-level grobs on the display list.
### Usage
```
getNames()
```
### Value
A character vector.
### Author(s)
Paul Murrell
### Examples
```
grid.grill()
getNames()
```
r None
`unit.length` Length of a Unit Object
--------------------------------------
### Description
The length of a unit object is defined as the number of unit values in the unit object.
This function has been deprecated in favour of a unit method for the generic `length` function.
### Usage
```
unit.length(unit)
```
### Arguments
| | |
| --- | --- |
| `unit` | A unit object. |
### Value
An integer value.
### Author(s)
Paul Murrell
### See Also
`<unit>`
### Examples
```
length(unit(1:3, "npc"))
length(unit(1:3, "npc") + unit(1, "inches"))
length(max(unit(1:3, "npc") + unit(1, "inches")))
length(max(unit(1:3, "npc") + unit(1, "strwidth", "a"))*4)
length(unit(1:3, "npc") + unit(1, "strwidth", "a")*4)
```
| programming_docs |
r None
`gEdit` Create and Apply Edit Objects
--------------------------------------
### Description
The functions `gEdit` and `gEditList` create objects representing an edit operation (essentially a list of arguments to `editGrob`).
The functions `applyEdit` and `applyEdits` apply one or more edit operations to a graphical object.
These functions are most useful for developers creating new graphical functions and objects.
### Usage
```
gEdit(...)
gEditList(...)
applyEdit(x, edit)
applyEdits(x, edits)
```
### Arguments
| | |
| --- | --- |
| `...` | one or more arguments to the `editGrob` function (for `gEdit`) or one or more `"gEdit"` objects (for `gEditList`). |
| `x` | a grob (grid graphical object). |
| `edit` | a `"gEdit"` object. |
| `edits` | either a `"gEdit"` object or a `"gEditList"` object. |
### Value
`gEdit` returns an object of class `"gEdit"`.
`gEditList` returns an object of class `"gEditList"`.
`applyEdit` and `applyEditList` return the modified grob.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)` `[editGrob](grid.edit)`
### Examples
```
grid.rect(gp=gpar(col="red"))
# same thing, but more verbose
grid.draw(applyEdit(rectGrob(), gEdit(gp=gpar(col="red"))))
```
r None
`grid.path` Draw a Path
------------------------
### Description
These functions create and draw one or more paths. The final point of a path will automatically be connected to the initial point.
### Usage
```
pathGrob(x, y,
id=NULL, id.lengths=NULL,
pathId=NULL, pathId.lengths=NULL,
rule="winding",
default.units="npc",
name=NULL, gp=gpar(), vp=NULL)
grid.path(...)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-locations. |
| `y` | A numeric vector or unit object specifying y-locations. |
| `id` | A numeric vector used to separate locations in `x` and `y` into sub-paths. All locations with the same `id` belong to the same sub-path. |
| `id.lengths` | A numeric vector used to separate locations in `x` and `y` into sub-paths. Specifies consecutive blocks of locations which make up separate sub-paths. |
| `pathId` | A numeric vector used to separate locations in `x` and `y` into distinct paths. All locations with the same `pathId` belong to the same path. |
| `pathId.lengths` | A numeric vector used to separate locations in `x` and `y` into paths. Specifies consecutive blocks of locations which make up separate paths. |
| `rule` | A character value specifying the fill rule: either `"winding"` or `"evenodd"`. |
| `default.units` | A string indicating the default units to use if `x` or `y` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments passed to `pathGrob()`. |
### Details
Both functions create a path grob (a graphical object describing a path), but only `grid.path` draws the path (and then only if `draw` is `TRUE`).
A path is like a polygon except that the former can contain holes, as interpreted by the fill rule; these fill a region if the path border encircles it an odd or non-zero number of times, respectively.
Not all graphics devices support this function: for example `xfig` and `pictex` do not.
### Value
A grob object.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
pathSample <- function(x, y, rule, gp = gpar()) {
if (is.na(rule))
grid.path(x, y, id = rep(1:2, each = 4), gp = gp)
else
grid.path(x, y, id = rep(1:2, each = 4), rule = rule, gp = gp)
if (!is.na(rule))
grid.text(paste("Rule:", rule), y = 0, just = "bottom")
}
pathTriplet <- function(x, y, title) {
pushViewport(viewport(height = 0.9, layout = grid.layout(1, 3),
gp = gpar(cex = .7)))
grid.rect(y = 1, height = unit(1, "char"), just = "top",
gp = gpar(col = NA, fill = "grey"))
grid.text(title, y = 1, just = "top")
pushViewport(viewport(layout.pos.col = 1))
pathSample(x, y, rule = "winding",
gp = gpar(fill = "grey"))
popViewport()
pushViewport(viewport(layout.pos.col = 2))
pathSample(x, y, rule = "evenodd",
gp = gpar(fill = "grey"))
popViewport()
pushViewport(viewport(layout.pos.col = 3))
pathSample(x, y, rule = NA)
popViewport()
popViewport()
}
pathTest <- function() {
grid.newpage()
pushViewport(viewport(layout = grid.layout(5, 1)))
pushViewport(viewport(layout.pos.row = 1))
pathTriplet(c(.1, .1, .9, .9, .2, .2, .8, .8),
c(.1, .9, .9, .1, .2, .8, .8, .2),
"Nested rectangles, both clockwise")
popViewport()
pushViewport(viewport(layout.pos.row = 2))
pathTriplet(c(.1, .1, .9, .9, .2, .8, .8, .2),
c(.1, .9, .9, .1, .2, .2, .8, .8),
"Nested rectangles, outer clockwise, inner anti-clockwise")
popViewport()
pushViewport(viewport(layout.pos.row = 3))
pathTriplet(c(.1, .1, .4, .4, .6, .9, .9, .6),
c(.1, .4, .4, .1, .6, .6, .9, .9),
"Disjoint rectangles")
popViewport()
pushViewport(viewport(layout.pos.row = 4))
pathTriplet(c(.1, .1, .6, .6, .4, .4, .9, .9),
c(.1, .6, .6, .1, .4, .9, .9, .4),
"Overlapping rectangles, both clockwise")
popViewport()
pushViewport(viewport(layout.pos.row = 5))
pathTriplet(c(.1, .1, .6, .6, .4, .9, .9, .4),
c(.1, .6, .6, .1, .4, .4, .9, .9),
"Overlapping rectangles, one clockwise, other anti-clockwise")
popViewport()
popViewport()
}
pathTest()
# Drawing multiple paths at once
holed_rect <- cbind(c(.15, .15, -.15, -.15, .1, .1, -.1, -.1),
c(.15, -.15, -.15, .15, .1, -.1, -.1, .1))
holed_rects <- rbind(
holed_rect + matrix(c(.7, .2), nrow = 8, ncol = 2, byrow = TRUE),
holed_rect + matrix(c(.7, .8), nrow = 8, ncol = 2, byrow = TRUE),
holed_rect + matrix(c(.2, .5), nrow = 8, ncol = 2, byrow = TRUE)
)
grid.newpage()
grid.path(x = holed_rects[, 1], y = holed_rects[, 2],
id = rep(1:6, each = 4), pathId = rep(1:3, each = 8),
gp = gpar(fill = c('red', 'blue', 'green')),
rule = 'evenodd')
# Not specifying pathId will treat all points as part of the same path, thus
# having same fill
grid.newpage()
grid.path(x = holed_rects[, 1], y = holed_rects[, 2],
id = rep(1:6, each = 4),
gp = gpar(fill = c('red', 'blue', 'green')),
rule = 'evenodd')
```
r None
`grid.newpage` Move to a New Page on a Grid Device
---------------------------------------------------
### Description
This function erases the current device or moves to a new page.
### Usage
```
grid.newpage(recording = TRUE)
```
### Arguments
| | |
| --- | --- |
| `recording` | A logical value to indicate whether the new-page operation should be saved onto the Grid display list. |
### Details
The new page is painted with the fill colour (`<gpar>("fill")`), which is often transparent. For devices with a *canvas* colour (the on-screen devices `X11`, `windows` and `quartz`), the page is first painted with the canvas colour and then the background colour.
There are two hooks called `"before.grid.newpage"` and `"grid.newpage"` (see `[setHook](../../base/html/userhooks)`). The latter is used in the testing code to annotate the new page. The hook function(s) are called with no argument. (If the value is a character string, `get` is called on it from within the grid namespace.)
### Value
None.
### Author(s)
Paul Murrell
### See Also
[Grid](grid)
r None
`stringWidth` Create a Unit Describing the Width and Height of a String or Math Expression
-------------------------------------------------------------------------------------------
### Description
These functions create a unit object describing the width or height of a string.
### Usage
```
stringWidth(string)
stringHeight(string)
stringAscent(string)
stringDescent(string)
```
### Arguments
| | |
| --- | --- |
| `string` | A character vector or a language object (as used for ‘[plotmath](../../grdevices/html/plotmath)’ calls). |
### Value
A `<unit>` object.
### Author(s)
Paul Murrell
### See Also
`<unit>` and `[grobWidth](grobwidth)`
`strwidth` in the graphics package for more details of the typographic concepts behind the computations.
r None
`viewports` Maintaining and Navigating the Grid Viewport Tree
--------------------------------------------------------------
### Description
Grid maintains a tree of viewports — nested drawing contexts.
These functions provide ways to add or remove viewports and to navigate amongst viewports in the tree.
### Usage
```
pushViewport(..., recording=TRUE)
popViewport(n = 1, recording=TRUE)
downViewport(name, strict=FALSE, recording=TRUE)
seekViewport(name, recording=TRUE)
upViewport(n = 1, recording=TRUE)
```
### Arguments
| | |
| --- | --- |
| `...` | One or more objects of class `"viewport"`. |
| `n` | An integer value indicating how many viewports to pop or navigate up. The special value `0` indicates to pop or navigate viewports right up to the root viewport. |
| `name` | A character value to identify a viewport in the tree. |
| `strict` | A boolean indicating whether the vpPath must be matched exactly. |
| `recording` | A logical value to indicate whether the viewport operation should be recorded on the Grid display list. |
### Details
Objects created by the `viewport()` function are only descriptions of a drawing context. A viewport object must be pushed onto the viewport tree before it has any effect on drawing.
The viewport tree always has a single root viewport (created by the system) which corresponds to the entire device (and default graphical parameter settings). Viewports may be added to the tree using `pushViewport()` and removed from the tree using `popViewport()`.
There is only ever one current viewport, which is the current position within the viewport tree. All drawing and viewport operations are relative to the current viewport. When a viewport is pushed it becomes the current viewport. When a viewport is popped, the parent viewport becomes the current viewport. Use `upViewport` to navigate to the parent of the current viewport, without removing the current viewport from the viewport tree. Use `downViewport` to navigate to a viewport further down the viewport tree and `seekViewport` to navigate to a viewport anywhere else in the tree.
If a viewport is pushed and it has the same `name` as a viewport at the same level in the tree, then it replaces the existing viewport in the tree.
### Value
`downViewport` returns the number of viewports it went down.
This can be useful for returning to your starting point by doing something like `depth <- downViewport()` then `upViewport(depth)`.
### Author(s)
Paul Murrell
### See Also
`<viewport>` and `[vpPath](vppath)`.
### Examples
```
# push the same viewport several times
grid.newpage()
vp <- viewport(width=0.5, height=0.5)
pushViewport(vp)
grid.rect(gp=gpar(col="blue"))
grid.text("Quarter of the device",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="blue"))
pushViewport(vp)
grid.rect(gp=gpar(col="red"))
grid.text("Quarter of the parent viewport",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="red"))
popViewport(2)
# push several viewports then navigate amongst them
grid.newpage()
grid.rect(gp=gpar(col="grey"))
grid.text("Top-level viewport",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="grey"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(width=0.8, height=0.7, name="A"))
grid.rect(gp=gpar(col="blue"))
grid.text("1. Push Viewport A",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(x=0.1, width=0.3, height=0.6,
just="left", name="B"))
grid.rect(gp=gpar(col="red"))
grid.text("2. Push Viewport B (in A)",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="red"))
if (interactive()) Sys.sleep(1.0)
upViewport(1)
grid.text("3. Up from B to A",
y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(x=0.5, width=0.4, height=0.8,
just="left", name="C"))
grid.rect(gp=gpar(col="green"))
grid.text("4. Push Viewport C (in A)",
y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="green"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(width=0.8, height=0.6, name="D"))
grid.rect()
grid.text("5. Push Viewport D (in C)",
y=unit(1, "npc") - unit(1, "lines"))
if (interactive()) Sys.sleep(1.0)
upViewport(0)
grid.text("6. Up from D to top-level",
y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="grey"))
if (interactive()) Sys.sleep(1.0)
downViewport("D")
grid.text("7. Down from top-level to D",
y=unit(1, "npc") - unit(2, "lines"))
if (interactive()) Sys.sleep(1.0)
seekViewport("B")
grid.text("8. Seek from D to B",
y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="red"))
pushViewport(viewport(width=0.9, height=0.5, name="A"))
grid.rect()
grid.text("9. Push Viewport A (in B)",
y=unit(1, "npc") - unit(1, "lines"))
if (interactive()) Sys.sleep(1.0)
seekViewport("A")
grid.text("10. Seek from B to A (in ROOT)",
y=unit(1, "npc") - unit(3, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
seekViewport(vpPath("B", "A"))
grid.text("11. Seek from\nA (in ROOT)\nto A (in B)")
popViewport(0)
```
r None
`grid-defunct` Defunct Functions in Package grid
-------------------------------------------------
### Description
The functions or variables listed here are no longer part of grid.
### Usage
```
grid.grob(list.struct, cl = NULL, draw = TRUE)
grid.arrows(x = c(0.25, 0.75), y = 0.5, default.units = "npc",
grob = NULL,
angle = 30, length = unit(0.25, "inches"),
ends = "last", type = "open", name = NULL,
gp = gpar(), draw = TRUE, vp = NULL)
arrowsGrob(x = c(0.25, 0.75), y = 0.5, default.units = "npc",
grob = NULL,
angle = 30, length = unit(0.25, "inches"),
ends = "last", type = "open", name = NULL,
gp = gpar(), vp = NULL)
grid.convertX(x, unitTo, valueOnly = FALSE)
grid.convertY(x, unitTo, valueOnly = FALSE)
grid.convertWidth(x, unitTo, valueOnly = FALSE)
grid.convertHeight(x, unitTo, valueOnly = FALSE)
grid.convert(x, unitTo,
axisFrom = "x", typeFrom = "location",
axisTo = axisFrom, typeTo = typeFrom,
valueOnly = FALSE)
grid.collection(..., gp=gpar(), draw=TRUE, vp=NULL)
push.viewport(..., recording=TRUE)
pop.viewport(n=1, recording=TRUE)
viewport.transform(vp)
draw.details(x, recording)
convertNative(unit, dimension="x", type="location")
```
r None
`grid.remove` Remove a Grid Graphical Object
---------------------------------------------
### Description
Remove a grob from a gTree or a descendant of a gTree.
### Usage
```
grid.remove(gPath, warn = TRUE, strict = FALSE, grep = FALSE,
global = FALSE, allDevices = FALSE, redraw = TRUE)
grid.gremove(..., grep = TRUE, global = TRUE)
removeGrob(gTree, gPath, strict = FALSE, grep = FALSE,
global = FALSE, warn = TRUE)
```
### Arguments
| | |
| --- | --- |
| `gTree` | A gTree object. |
| `gPath` | a gPath object. For `grid.remove` this specifies a gTree on the display list. For `removeGrob` this specifies a descendant of the specified `gTree`. |
| `strict` | a `[logical](../../base/html/logical)` indicating whether the `gPath` must be matched exactly. |
| `grep` | a `[logical](../../base/html/logical)` indicating whether the `gPath` should be treated as a regular expression. Values are recycled across elements of the `gPath` (e.g., `c(TRUE, FALSE)` means that every odd element of the `gPath` will be treated as a regular expression). |
| `global` | a `[logical](../../base/html/logical)` indicating whether the function should affect just the first match of the `gPath`, or whether all matches should be affected. |
| `allDevices` | a `[logical](../../base/html/logical)` indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED. |
| `warn` | A logical to indicate whether failing to find the specified grob should trigger an error. |
| `redraw` | A logical value to indicate whether to redraw the grob. |
| `...` | arguments passed to `<grid.get>`. |
### Details
`removeGrob` copies the specified grob and returns a modified grob.
`grid.remove` destructively modifies a grob on the display list. If `redraw` is `TRUE` it then redraws everything to reflect the change.
`grid.gremove` (`g` for global) is just a convenience wrapper for `grid.remove` with different defaults.
### Value
`removeGrob` returns a grob object; `grid.remove` returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)`, `[getGrob](grid.get)`.
r None
`grid.raster` Render a raster object
-------------------------------------
### Description
Render a raster object (bitmap image) at the given location, size, and orientation.
### Usage
```
grid.raster(image,
x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = NULL, height = NULL,
just = "centre", hjust = NULL, vjust = NULL,
interpolate = TRUE, default.units = "npc",
name = NULL, gp = gpar(), vp = NULL)
rasterGrob(image,
x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = NULL, height = NULL,
just = "centre", hjust = NULL, vjust = NULL,
interpolate = TRUE, default.units = "npc",
name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `image` | Any R object that can be coerced to a raster object. |
| `x` | A numeric vector or unit object specifying x-location. |
| `y` | A numeric vector or unit object specifying y-location. |
| `width` | A numeric vector or unit object specifying width. |
| `height` | A numeric vector or unit object specifying height. |
| `just` | The justification of the rectangle relative to its (x, y) location. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left alignment and 1 means right alignment. |
| `hjust` | A numeric vector specifying horizontal justification. If specified, overrides the `just` setting. |
| `vjust` | A numeric vector specifying vertical justification. If specified, overrides the `just` setting. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
| `interpolate` | A logical value indicating whether to linearly interpolate the image (the alternative is to use nearest-neighbour interpolation, which gives a more blocky result). |
### Details
Neither `width` nor `height` needs to be specified, in which case, the aspect ratio of the image is preserved. If both `width` and `height` are specified, it is likely that the image will be distorted.
Not all graphics devices are capable of rendering raster images and some may not be able to produce rotated images (i.e., if a raster object is rendered within a rotated viewport). See also the comments under `[rasterImage](../../graphics/html/rasterimage)`.
All graphical parameter settings in `gp` will be ignored, including `alpha`.
### Value
A rastergrob grob.
### Author(s)
Paul Murrell
### See Also
`[as.raster](../../grdevices/html/as.raster)`.
`[dev.capabilities](../../grdevices/html/dev.capabilities)` to see if it is supported.
### Examples
```
redGradient <- matrix(hcl(0, 80, seq(50, 80, 10)),
nrow=4, ncol=5)
# interpolated
grid.newpage()
grid.raster(redGradient)
# blocky
grid.newpage()
grid.raster(redGradient, interpolate=FALSE)
# blocky and stretched
grid.newpage()
grid.raster(redGradient, interpolate=FALSE, height=unit(1, "npc"))
# The same raster drawn several times
grid.newpage()
grid.raster(0, x=1:3/4, y=1:3/4, width=.1, interpolate=FALSE)
```
| programming_docs |
r None
`grid.grob` Create Grid Graphical Objects, aka "Grob"s
-------------------------------------------------------
### Description
Creating grid graphical objects, short (“grob”s).
`grob()` and `gTree()` are the basic creators, `grobTree()` and `gList()` take several grobs to build a new one.
### Usage
```
## Grob Creation:
grob (..., name = NULL, gp = NULL, vp = NULL, cl = NULL)
gTree(..., name = NULL, gp = NULL, vp = NULL, children = NULL,
childrenvp = NULL, cl = NULL)
grobTree(..., name = NULL, gp = NULL, vp = NULL,
childrenvp = NULL, cl = NULL)
gList(...)
## Grob Properties:
childNames(gTree)
is.grob(x)
```
### Arguments
| | |
| --- | --- |
| `...` | For `grob` and `gTree`, the named slots describing important features of the graphical object. For `gList` and `grobTree`, a series of grob objects. |
| `name` | a character identifier for the grob. Used to find the grob on the display list and/or as a child of another grob. |
| `children` | a `"gList"` object. |
| `childrenvp` | a `<viewport>` object (or `NULL`). |
| `gp` | A `"gpar"` object, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | a `<viewport>` object (or `NULL`). |
| `cl` | string giving the class attribute for the new class. |
| `gTree` | a `"gTree"` object. |
| `x` | An **R** object. |
### Details
These functions can be used to create a basic `"grob"`, `"gTree"`, or `"gList"` object, or a new class derived from one of these.
A grid graphical object (“grob”) is a description of a graphical item. These basic classes provide default behaviour for validating, drawing, and modifying graphical objects. Both `grob()` and `gTree()` call the function `[validDetails](validdetails)` to check that the object returned is internally coherent.
A `"gTree"` can have other grobs as children; when a gTree is drawn, it draws all of its children. Before drawing its children, a gTree pushes its `childrenvp` slot and then navigates back up (calls `[upViewport](viewports)`) so that the children can specify their location within the `childrenvp` via a `[vpPath](vppath)`.
Grob names need not be unique in general, but all children of a gTree must have different names. A grob name can be any string, though it is not advisable to use the `[gPath](gpath)` separator (currently `::`) in grob names.
The function `childNames` returns the names of the grobs which are children of a gTree.
All grid primitives (`<grid.lines>`, `grid.rect`, ...) and some higher-level grid components (e.g., `<grid.xaxis>` and `grid.yaxis`) are derived from these classes.
`grobTree` is just a convenient wrapper for `gTree` when the only components of the gTree are grobs (so all unnamed arguments become children of the gTree).
The `grid.grob` function is defunct.
### Value
An **R** object of class `"grob"`, a **gr**aphical **ob**ject.
### Author(s)
Paul Murrell
### See Also
`<grid.draw>`, `<grid.edit>`, `<grid.get>`.
r None
`arrow` Describe arrows to add to a line.
------------------------------------------
### Description
Produces a description of what arrows to add to a line. The result can be passed to a function that draws a line, e.g., `grid.lines`.
### Usage
```
arrow(angle = 30, length = unit(0.25, "inches"),
ends = "last", type = "open")
```
### Arguments
| | |
| --- | --- |
| `angle` | The angle of the arrow head in degrees (smaller numbers produce narrower, pointier arrows). Essentially describes the width of the arrow head. |
| `length` | A unit specifying the length of the arrow head (from tip to base). |
| `ends` | One of `"last"`, `"first"`, or `"both"`, indicating which ends of the line to draw arrow heads. |
| `type` | One of `"open"` or `"closed"` indicating whether the arrow head should be a closed triangle. |
### Examples
```
arrow()
```
r None
`grid.text` Draw Text
----------------------
### Description
These functions create and draw text and [plotmath](../../grdevices/html/plotmath) expressions.
### Usage
```
grid.text(label, x = unit(0.5, "npc"), y = unit(0.5, "npc"),
just = "centre", hjust = NULL, vjust = NULL, rot = 0,
check.overlap = FALSE, default.units = "npc",
name = NULL, gp = gpar(), draw = TRUE, vp = NULL)
textGrob(label, x = unit(0.5, "npc"), y = unit(0.5, "npc"),
just = "centre", hjust = NULL, vjust = NULL, rot = 0,
check.overlap = FALSE, default.units = "npc",
name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `label` | A character or [expression](../../base/html/expression) vector. Other objects are coerced by `[as.graphicsAnnot](../../grdevices/html/as.graphicsannot)`. |
| `x` | A numeric vector or unit object specifying x-values. |
| `y` | A numeric vector or unit object specifying y-values. |
| `just` | The justification of the text relative to its (x, y) location. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left (bottom) alignment and 1 means right (top) alignment. |
| `hjust` | A numeric vector specifying horizontal justification. If specified, overrides the `just` setting. |
| `vjust` | A numeric vector specifying vertical justification. If specified, overrides the `just` setting. |
| `rot` | The angle to rotate the text. |
| `check.overlap` | A logical value to indicate whether to check for and omit overlapping text. |
| `default.units` | A string indicating the default units to use if `x` or `y` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a text grob (a graphical object describing text), but only `grid.text` draws the text (and then only if `draw` is `TRUE`).
If the `label` argument is an expression, the output is formatted as a mathematical annotation, as for base graphics text.
### Value
A text grob. `grid.text()` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
grid.newpage()
x <- stats::runif(20)
y <- stats::runif(20)
rot <- stats::runif(20, 0, 360)
grid.text("SOMETHING NICE AND BIG", x=x, y=y, rot=rot,
gp=gpar(fontsize=20, col="grey"))
grid.text("SOMETHING NICE AND BIG", x=x, y=y, rot=rot,
gp=gpar(fontsize=20), check.overlap=TRUE)
grid.newpage()
draw.text <- function(just, i, j) {
grid.text("ABCD", x=x[j], y=y[i], just=just)
grid.text(deparse(substitute(just)), x=x[j], y=y[i] + unit(2, "lines"),
gp=gpar(col="grey", fontsize=8))
}
x <- unit(1:4/5, "npc")
y <- unit(1:4/5, "npc")
grid.grill(h=y, v=x, gp=gpar(col="grey"))
draw.text(c("bottom"), 1, 1)
draw.text(c("left", "bottom"), 2, 1)
draw.text(c("right", "bottom"), 3, 1)
draw.text(c("centre", "bottom"), 4, 1)
draw.text(c("centre"), 1, 2)
draw.text(c("left", "centre"), 2, 2)
draw.text(c("right", "centre"), 3, 2)
draw.text(c("centre", "centre"), 4, 2)
draw.text(c("top"), 1, 3)
draw.text(c("left", "top"), 2, 3)
draw.text(c("right", "top"), 3, 3)
draw.text(c("centre", "top"), 4, 3)
draw.text(c(), 1, 4)
draw.text(c("left"), 2, 4)
draw.text(c("right"), 3, 4)
draw.text(c("centre"), 4, 4)
```
r None
`showViewport` Display grid viewports.
---------------------------------------
### Description
Produces a graphical display of (by default) the current grid viewport tree. It is also possible to display only specific viewports. Each viewport is drawn as a rectangle and the leaf viewports are labelled with the viewport name.
### Usage
```
showViewport(vp = NULL, recurse = TRUE, depth = NULL,
newpage = FALSE, leaves = FALSE,
col = rgb(0, 0, 1, 0.2), fill = rgb(0, 0, 1, 0.1),
label = TRUE, nrow = 3, ncol = nrow)
```
### Arguments
| | |
| --- | --- |
| `vp` | If `NULL`, the current viewport tree is displayed. Otherwise, a viewport (or vpList, or vpStack, or vpTree) or a vpPath that specifies which viewport to display. |
| `recurse` | Should the children of the specified viewport also be displayed? |
| `depth` | Only display viewports at the specified depth (may be a vector of depths). |
| `newpage` | Start a new page for the display? Otherwise, the viewports are displayed on top of the current plot. |
| `leaves` | Produce a matrix of smaller displays, with each leaf viewport in its own display. |
| `col` | The colour used to draw the border of the rectangle for each viewport *and* to draw the label for each viewport. If a vector, then the first colour is used for the top-level viewport, the second colour is used for its children, the third colour for their children, and so on. |
| `fill` | The colour used to fill each viewport. May be a vector as per `col`. |
| `label` | Should the viewports be labelled (with the viewport name)? |
| `nrow, ncol` | The number of rows and columns when `leaves` is `TRUE`. Otherwise ignored. |
### See Also
`<viewport>` and `<grid.show.viewport>`
### Examples
```
showViewport(viewport(width=.5, height=.5, name="vp"))
grid.newpage()
pushViewport(viewport(width=.5, height=.5, name="vp"))
upViewport()
showViewport(vpPath("vp"))
showViewport(vpStack(viewport(width=.5, height=.5, name="vp1"),
viewport(width=.5, height=.5, name="vp2")),
newpage=TRUE)
showViewport(vpStack(viewport(width=.5, height=.5, name="vp1"),
viewport(width=.5, height=.5, name="vp2")),
fill=rgb(1:0, 0:1, 0, .1),
newpage=TRUE)
```
r None
`grid.layout` Create a Grid Layout
-----------------------------------
### Description
This function returns a Grid layout, which describes a subdivision of a rectangular region.
### Usage
```
grid.layout(nrow = 1, ncol = 1,
widths = unit(rep_len(1, ncol), "null"),
heights = unit(rep_len(1, nrow), "null"),
default.units = "null", respect = FALSE,
just="centre")
```
### Arguments
| | |
| --- | --- |
| `nrow` | An integer describing the number of rows in the layout. |
| `ncol` | An integer describing the number of columns in the layout. |
| `widths` | A numeric vector or unit object describing the widths of the columns in the layout. |
| `heights` | A numeric vector or unit object describing the heights of the rows in the layout. |
| `default.units` | A string indicating the default units to use if `widths` or `heights` are only given as numeric vectors. |
| `respect` | A logical value or a numeric matrix. If a logical, this indicates whether row heights and column widths should respect each other. If a matrix, non-zero values indicate that the corresponding row and column should be respected (see examples below). |
| `just` | A string or numeric vector specifying how the layout should be justified if it is not the same size as its parent viewport. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left alignment and 1 means right alignment. NOTE that in this context, `"left"`, for example, means align the left edge of the left-most layout column with the left edge of the parent viewport. |
### Details
The unit objects given for the `widths` and `heights` of a layout may use a special `units` that only has meaning for layouts. This is the `"null"` unit, which indicates what relative fraction of the available width/height the column/row occupies. See the reference for a better description of relative widths and heights in layouts.
### Value
A Grid layout object.
### WARNING
This function must NOT be confused with the base R graphics function `layout`. In particular, do not use `layout` in combination with Grid graphics. The documentation for `layout` may provide some useful information and this function should behave identically in comparable situations. The `grid.layout` function has *added* the ability to specify a broader range of units for row heights and column widths, and allows for nested layouts (see `viewport`).
### Author(s)
Paul Murrell
### References
Murrell, P. R. (1999). Layouts: A Mechanism for Arranging Plots on a Page. *Journal of Computational and Graphical Statistics*, **8**, 121–134. doi: [10.2307/1390924](https://doi.org/10.2307/1390924).
### See Also
[Grid](grid), `<grid.show.layout>`, `<viewport>`, `[layout](../../graphics/html/layout)`
### Examples
```
## A variety of layouts (some a bit mid-bending ...)
layout.torture()
## Demonstration of layout justification
grid.newpage()
testlay <- function(just="centre") {
pushViewport(viewport(layout=grid.layout(1, 1, widths=unit(1, "inches"),
heights=unit(0.25, "npc"),
just=just)))
pushViewport(viewport(layout.pos.col=1, layout.pos.row=1))
grid.rect()
grid.text(paste(just, collapse="-"))
popViewport(2)
}
testlay()
testlay(c("left", "top"))
testlay(c("right", "top"))
testlay(c("right", "bottom"))
testlay(c("left", "bottom"))
testlay(c("left"))
testlay(c("right"))
testlay(c("bottom"))
testlay(c("top"))
```
r None
`editDetails` Customising grid Editing
---------------------------------------
### Description
This generic hook function is called whenever a grid grob is edited via `grid.edit` or `editGrob`. This provides an opportunity for customising the editing of a new class derived from grob (or gTree).
### Usage
```
editDetails(x, specs)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
| `specs` | A list of named elements. The names indicate the grob slots to modify and the values are the new values for the slots. |
### Details
This function is called by `grid.edit` and `editGrob`. A method should be written for classes derived from grob or gTree if a change in a slot has an effect on other slots in the grob or children of a gTree (e.g., see `grid:::editDetails.xaxis`).
Note that the slot already has the new value.
### Value
The function MUST return the modified grob.
### Author(s)
Paul Murrell
### See Also
`<grid.edit>`
r None
`grid.grill` Draw a Grill
--------------------------
### Description
This function draws a grill within a Grid viewport.
### Usage
```
grid.grill(h = unit(seq(0.25, 0.75, 0.25), "npc"),
v = unit(seq(0.25, 0.75, 0.25), "npc"),
default.units = "npc", gp=gpar(col = "grey"), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `h` | A numeric vector or unit object indicating the horizontal location of the vertical grill lines. |
| `v` | A numeric vector or unit object indicating the vertical location of the horizontal grill lines. |
| `default.units` | A string indicating the default units to use if `h` or `v` are only given as numeric vectors. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object. |
### Value
None.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`.
r None
`grid.pretty` Generate a Sensible Set of Breakpoints
-----------------------------------------------------
### Description
Produces a pretty set of breakpoints within the range given.
### Usage
```
grid.pretty(range)
```
### Arguments
| | |
| --- | --- |
| `range` | A numeric vector |
### Value
A numeric vector of breakpoints.
### Author(s)
Paul Murrell
r None
`dataViewport` Create a Viewport with Scales based on Data
-----------------------------------------------------------
### Description
This is a convenience function for producing a viewport with x- and/or y-scales based on numeric values passed to the function.
### Usage
```
dataViewport(xData = NULL, yData = NULL, xscale = NULL,
yscale = NULL, extension = 0.05, ...)
```
### Arguments
| | |
| --- | --- |
| `xData` | A numeric vector of data. |
| `yData` | A numeric vector of data. |
| `xscale` | A numeric vector (length 2). |
| `yscale` | A numeric vector (length 2). |
| `extension` | A numeric. If length greater than 1, then first value is used to extend the xscale and second value is used to extend the yscale. |
| `...` | All other arguments will be passed to a call to the `viewport()` function. |
### Details
If `xscale` is not specified then the values in `x` are used to generate an x-scale based on the range of `x`, extended by the proportion specified in `extension`. Similarly for the y-scale.
### Value
A grid viewport object.
### Author(s)
Paul Murrell
### See Also
`<viewport>` and `[plotViewport](plotviewport)`.
r None
`plotViewport` Create a Viewport with a Standard Plot Layout
-------------------------------------------------------------
### Description
This is a convenience function for producing a viewport with the common S-style plot layout – i.e., a central plot region surrounded by margins given in terms of a number of lines of text.
### Usage
```
plotViewport(margins=c(5.1, 4.1, 4.1, 2.1), ...)
```
### Arguments
| | |
| --- | --- |
| `margins` | A numeric vector interpreted in the same way as `par(mar)` in base graphics. |
| `...` | All other arguments will be passed to a call to the `viewport()` function. |
### Value
A grid viewport object.
### Author(s)
Paul Murrell
### See Also
`<viewport>` and `[dataViewport](dataviewport)`.
r None
`grid.cap` Capture a raster image
----------------------------------
### Description
Capture the current contents of a graphics device as a raster (bitmap) image.
### Usage
```
grid.cap()
```
### Details
This function is only implemented for on-screen graphics devices.
### Value
A matrix of R colour names, or `NULL` if not available.
### Author(s)
Paul Murrell
### See Also
`<grid.raster>`
`[dev.capabilities](../../grdevices/html/dev.capabilities)` to see if it is supported.
### Examples
```
dev.new(width=0.5, height=0.5)
grid.rect()
grid.text("hi")
cap <- grid.cap()
dev.off()
if(!is.null(cap))
grid.raster(cap, width=0.5, height=0.5, interpolate=FALSE)
```
r None
`grid.refresh` Refresh the current grid scene
----------------------------------------------
### Description
Replays the current grid display list.
### Usage
```
grid.refresh()
```
### Author(s)
Paul Murrell
r None
`grid.curve` Draw a Curve Between Locations
--------------------------------------------
### Description
These functions create and draw a curve from one location to another.
### Usage
```
grid.curve(...)
curveGrob(x1, y1, x2, y2, default.units = "npc",
curvature = 1, angle = 90, ncp = 1, shape = 0.5,
square = TRUE, squareShape = 1,
inflect = FALSE, arrow = NULL, open = TRUE,
debug = FALSE,
name = NULL, gp = gpar(), vp = NULL)
arcCurvature(theta)
```
### Arguments
| | |
| --- | --- |
| `x1` | A numeric vector or unit object specifying the x-location of the start point. |
| `y1` | A numeric vector or unit object specifying the y-location of the start point. |
| `x2` | A numeric vector or unit object specifying the x-location of the end point. |
| `y2` | A numeric vector or unit object specifying the y-location of the end point. |
| `default.units` | A string indicating the default units to use if `x1`, `y1`, `x2` or `y2` are only given as numeric values. |
| `curvature` | A numeric value giving the amount of curvature. Negative values produce left-hand curves, positive values produce right-hand curves, and zero produces a straight line. |
| `angle` | A numeric value between 0 and 180, giving an amount to skew the control points of the curve. Values less than 90 skew the curve towards the start point and values greater than 90 skew the curve towards the end point. |
| `ncp` | The number of control points used to draw the curve. More control points creates a smoother curve. |
| `shape` | A numeric vector of values between -1 and 1, which control the shape of the curve relative to its control points. See `grid.xspline` for more details. |
| `square` | A logical value that controls whether control points for the curve are created city-block fashion or obliquely. When `ncp` is 1 and `angle` is 90, this is typically `TRUE`, otherwise this should probably be set to `FALSE` (see Examples below). |
| `squareShape` | A `shape` value to control the behaviour of the curve relative to any additional control point that is inserted if `square` is `TRUE`. |
| `inflect` | A logical value specifying whether the curve should be cut in half and inverted (see Examples below). |
| `arrow` | A list describing arrow heads to place at either end of the curve, as produced by the `arrow` function. |
| `open` | A logical value indicating whether to close the curve (connect the start and end points). |
| `debug` | A logical value indicating whether debugging information should be drawn. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments to be passed to `curveGrob`. |
| `theta` | An angle (in degrees). |
### Details
Both functions create a curve grob (a graphical object describing an curve), but only `grid.curve` draws the curve.
The `arcCurvature` function can be used to calculate a `curvature` such that control points are generated on an arc corresponding to angle `theta`. This is typically used in conjunction with a large `ncp` to produce a curve corresponding to the desired arc.
### Value
A grob object.
### See Also
[Grid](grid), `<viewport>`, `<grid.xspline>`, `<arrow>`
### Examples
```
curveTest <- function(i, j, ...) {
pushViewport(viewport(layout.pos.col=j, layout.pos.row=i))
do.call("grid.curve", c(list(x1=.25, y1=.25, x2=.75, y2=.75), list(...)))
grid.text(sub("list\\((.*)\\)", "\\1",
deparse(substitute(list(...)))),
y=unit(1, "npc"))
popViewport()
}
# grid.newpage()
pushViewport(plotViewport(c(0, 0, 1, 0),
layout=grid.layout(2, 1, heights=c(2, 1))))
pushViewport(viewport(layout.pos.row=1,
layout=grid.layout(3, 3, respect=TRUE)))
curveTest(1, 1)
curveTest(1, 2, inflect=TRUE)
curveTest(1, 3, angle=135)
curveTest(2, 1, arrow=arrow())
curveTest(2, 2, ncp=8)
curveTest(2, 3, shape=0)
curveTest(3, 1, curvature=-1)
curveTest(3, 2, square=FALSE)
curveTest(3, 3, debug=TRUE)
popViewport()
pushViewport(viewport(layout.pos.row=2,
layout=grid.layout(3, 3)))
curveTest(1, 1)
curveTest(1, 2, inflect=TRUE)
curveTest(1, 3, angle=135)
curveTest(2, 1, arrow=arrow())
curveTest(2, 2, ncp=8)
curveTest(2, 3, shape=0)
curveTest(3, 1, curvature=-1)
curveTest(3, 2, square=FALSE)
curveTest(3, 3, debug=TRUE)
popViewport(2)
```
| programming_docs |
r None
`grid.segments` Draw Line Segments
-----------------------------------
### Description
These functions create and draw line segments.
### Usage
```
grid.segments(x0 = unit(0, "npc"), y0 = unit(0, "npc"),
x1 = unit(1, "npc"), y1 = unit(1, "npc"),
default.units = "npc",
arrow = NULL,
name = NULL, gp = gpar(), draw = TRUE, vp = NULL)
segmentsGrob(x0 = unit(0, "npc"), y0 = unit(0, "npc"),
x1 = unit(1, "npc"), y1 = unit(1, "npc"),
default.units = "npc",
arrow = NULL, name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x0` | Numeric indicating the starting x-values of the line segments. |
| `y0` | Numeric indicating the starting y-values of the line segments. |
| `x1` | Numeric indicating the stopping x-values of the line segments. |
| `y1` | Numeric indicating the stopping y-values of the line segments. |
| `default.units` | A string. |
| `arrow` | A list describing arrow heads to place at either end of the line segments, as produced by the `arrow` function. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a segments grob (a graphical object describing segments), but only `grid.segments` draws the segments (and then only if `draw` is `TRUE`).
### Value
A segments grob. `grid.segments` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`, `<arrow>`
r None
`grid.plot.and.legend` A Simple Plot and Legend Demo
-----------------------------------------------------
### Description
This function is just a wrapper for a simple demonstration of how a basic plot and legend can be drawn from scratch using grid.
### Usage
```
grid.plot.and.legend()
```
### Author(s)
Paul Murrell
### Examples
```
grid.plot.and.legend()
```
r None
`viewport` Create a Grid Viewport
----------------------------------
### Description
These functions create viewports, which describe rectangular regions on a graphics device and define a number of coordinate systems within those regions.
### Usage
```
viewport(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
width = unit(1, "npc"), height = unit(1, "npc"),
default.units = "npc", just = "centre",
gp = gpar(), clip = "inherit", mask = "inherit",
xscale = c(0, 1), yscale = c(0, 1),
angle = 0,
layout = NULL,
layout.pos.row = NULL, layout.pos.col = NULL,
name = NULL)
vpList(...)
vpStack(...)
vpTree(parent, children)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-location. |
| `y` | A numeric vector or unit object specifying y-location. |
| `width` | A numeric vector or unit object specifying width. |
| `height` | A numeric vector or unit object specifying height. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `just` | A string or numeric vector specifying the justification of the viewport relative to its (x, y) location. If there are two values, the first value specifies horizontal justification and the second value specifies vertical justification. Possible string values are: `"left"`, `"right"`, `"centre"`, `"center"`, `"bottom"`, and `"top"`. For numeric values, 0 means left alignment and 1 means right alignment. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `clip` | One of `"on"`, `"inherit"`, or `"off"`, indicating whether to clip to the extent of this viewport, inherit the clipping region from the parent viewport, or turn clipping off altogether. For back-compatibility, a logical value of `TRUE` corresponds to `"on"` and `FALSE` corresponds to `"inherit"`. May also be a grob (or a gTree) that describes a clipping path. |
| `mask` | One of `"none"` (or `FALSE`) or `"inherit"` (or `TRUE`) or a grob (or a gTree). This specifies that the viewport should have no mask, or it should inherit the mask of its parent, or it should have its own mask, as described by the grob. |
| `xscale` | A numeric vector of length two indicating the minimum and maximum on the x-scale. The limits may not be identical. |
| `yscale` | A numeric vector of length two indicating the minimum and maximum on the y-scale. The limits may not be identical. |
| `angle` | A numeric value indicating the angle of rotation of the viewport. Positive values indicate the amount of rotation, in degrees, anticlockwise from the positive x-axis. |
| `layout` | A Grid layout object which splits the viewport into subregions. |
| `layout.pos.row` | A numeric vector giving the rows occupied by this viewport in its parent's layout. |
| `layout.pos.col` | A numeric vector giving the columns occupied by this viewport in its parent's layout. |
| `name` | A character value to uniquely identify the viewport once it has been pushed onto the viewport tree. |
| `...` | Any number of grid viewport objects. |
| `parent` | A grid viewport object. |
| `children` | A vpList object. |
### Details
The location and size of a viewport are relative to the coordinate systems defined by the viewport's parent (either a graphical device or another viewport). The location and size can be specified in a very flexible way by specifying them with unit objects. When specifying the location of a viewport, specifying both `layout.pos.row` and `layout.pos.col` as `NULL` indicates that the viewport ignores its parent's layout and specifies its own location and size (via its `locn`). If only one of `layout.pos.row` and `layout.pos.col` is `NULL`, this means occupy ALL of the appropriate row(s)/column(s). For example, `layout.pos.row = 1` and `layout.pos.col = NULL` means occupy all of row 1. Specifying non-`NULL` values for both `layout.pos.row` and `layout.pos.col` means occupy the intersection of the appropriate rows and columns. If a vector of length two is specified for `layout.pos.row` or `layout.pos.col`, this indicates a range of rows or columns to occupy. For example, `layout.pos.row = c(1, 3)` and `layout.pos.col = c(2, 4)` means occupy cells in the intersection of rows 1, 2, and 3, and columns, 2, 3, and 4.
Clipping obeys only the most recent viewport clip setting. For example, if you clip to viewport1, then clip to viewport2, the clipping region is determined wholly by viewport2, the size and shape of viewport1 is irrelevant (until viewport2 is popped of course).
If a viewport is rotated (because of its own `angle` setting or because it is within another viewport which is rotated) then the `clip` flag is ignored.
Viewport names need not be unique. When pushed, viewports sharing the same parent must have unique names, which means that if you push a viewport with the same name as an existing viewport, the existing viewport will be replaced in the viewport tree. A viewport name can be any string, but grid uses the reserved name `"ROOT"` for the top-level viewport. Also, when specifying a viewport name in `downViewport` and `seekViewport`, it is possible to provide a viewport path, which consists of several names concatenated using the separator (currently `::`). Consequently, it is not advisable to use this separator in viewport names.
The viewports in a `vpList` are pushed in parallel. The viewports in a `vpStack` are pushed in series. When a `vpTree` is pushed, the parent is pushed first, then the children are pushed in parallel.
### Value
An R object of class `viewport`.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `[pushViewport](viewports)`, `[popViewport](viewports)`, `[downViewport](viewports)`, `[seekViewport](viewports)`, `[upViewport](viewports)`, `<unit>`, `<grid.layout>`, `<grid.show.layout>`.
### Examples
```
# Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
width=unit(1, "inches"), height=unit(1, "inches")))
# Demonstrate viewport clipping
clip.demo <- function(i, j, clip1, clip2) {
pushViewport(viewport(layout.pos.col=i,
layout.pos.row=j))
pushViewport(viewport(width=0.6, height=0.6, clip=clip1))
grid.rect(gp=gpar(fill="white"))
grid.circle(r=0.55, gp=gpar(col="red", fill="pink"))
popViewport()
pushViewport(viewport(width=0.6, height=0.6, clip=clip2))
grid.polygon(x=c(0.5, 1.1, 0.6, 1.1, 0.5, -0.1, 0.4, -0.1),
y=c(0.6, 1.1, 0.5, -0.1, 0.4, -0.1, 0.5, 1.1),
gp=gpar(col="blue", fill="light blue"))
popViewport(2)
}
grid.newpage()
grid.rect(gp=gpar(fill="grey"))
pushViewport(viewport(layout=grid.layout(2, 2)))
clip.demo(1, 1, FALSE, FALSE)
clip.demo(1, 2, TRUE, FALSE)
clip.demo(2, 1, FALSE, TRUE)
clip.demo(2, 2, TRUE, TRUE)
popViewport()
# Demonstrate turning clipping off
grid.newpage()
pushViewport(viewport(width=.5, height=.5, clip="on"))
grid.rect()
grid.circle(r=.6, gp=gpar(lwd=10))
pushViewport(viewport(clip="inherit"))
grid.circle(r=.6, gp=gpar(lwd=5, col="grey"))
pushViewport(viewport(clip="off"))
grid.circle(r=.6)
popViewport(3)
# Demonstrate vpList, vpStack, and vpTree
grid.newpage()
tree <- vpTree(viewport(width=0.8, height=0.8, name="A"),
vpList(vpStack(viewport(x=0.1, y=0.1, width=0.5, height=0.5,
just=c("left", "bottom"), name="B"),
viewport(x=0.1, y=0.1, width=0.5, height=0.5,
just=c("left", "bottom"), name="C"),
viewport(x=0.1, y=0.1, width=0.5, height=0.5,
just=c("left", "bottom"), name="D")),
viewport(x=0.5, width=0.4, height=0.9,
just="left", name="E")))
pushViewport(tree)
for (i in LETTERS[1:5]) {
seekViewport(i)
grid.rect()
grid.text(current.vpTree(FALSE),
x=unit(1, "mm"), y=unit(1, "npc") - unit(1, "mm"),
just=c("left", "top"),
gp=gpar(fontsize=8))
}
```
r None
`grid.points` Draw Data Symbols
--------------------------------
### Description
These functions create and draw data symbols.
### Usage
```
grid.points(x = stats::runif(10),
y = stats::runif(10),
pch = 1, size = unit(1, "char"),
default.units = "native", name = NULL,
gp = gpar(), draw = TRUE, vp = NULL)
pointsGrob(x = stats::runif(10),
y = stats::runif(10),
pch = 1, size = unit(1, "char"),
default.units = "native", name = NULL,
gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | numeric vector or unit object specifying x-values. |
| `y` | numeric vector or unit object specifying y-values. |
| `pch` | numeric or character vector indicating what sort of plotting symbol to use. See `[points](../../graphics/html/points)` for the interpretation of these values, and note `fill` below. |
| `size` | unit object specifying the size of the plotting symbols. |
| `default.units` | string indicating the default units to use if `x` or `y` are only given as numeric vectors. |
| `name` | character identifier. |
| `gp` | an **R** object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings; note that `fill` (and not `bg` as in package graphics `[points](../../graphics/html/points)`) is used to “fill”, i.e., color the background of symbols with `pch = 21:25`. |
| `draw` | logical indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a points grob (a graphical object describing points), but only `grid.points` draws the points (and then only if `draw` is `TRUE`).
### Value
A points `[grob](grid.grob)`. `grid.points` returns the value invisibly.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
r None
`grid.locator` Capture a Mouse Click
-------------------------------------
### Description
Allows the user to click the mouse once within the current graphics device and returns the location of the mouse click within the current viewport, in the specified coordinate system.
### Usage
```
grid.locator(unit = "native")
```
### Arguments
| | |
| --- | --- |
| `unit` | The coordinate system in which to return the location of the mouse click. See the `<unit>` function for valid coordinate systems. |
### Details
This function is modal (like the graphics package function `locator`) so the command line and graphics drawing is blocked until the use has clicked the mouse in the current device.
### Value
A unit object representing the location of the mouse click within the current viewport, in the specified coordinate system.
If the user did not click mouse button 1, the function (invisibly) returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`<viewport>`, `<unit>`, `[locator](../../graphics/html/locator)` in package graphics, and for an application see `[trellis.focus](../../lattice/html/interaction)` and `[panel.identify](../../lattice/html/interaction)` in package [lattice](https://CRAN.R-project.org/package=lattice).
### Examples
```
if (dev.interactive()) {
## Need to write a more sophisticated unit as.character method
unittrim <- function(unit) {
sub("^([0-9]+|[0-9]+[.][0-9])[0-9]*", "\\1", as.character(unit))
}
do.click <- function(unit) {
click.locn <- grid.locator(unit)
grid.segments(unit.c(click.locn$x, unit(0, "npc")),
unit.c(unit(0, "npc"), click.locn$y),
click.locn$x, click.locn$y,
gp=gpar(lty="dashed", col="grey"))
grid.points(click.locn$x, click.locn$y, pch=16, size=unit(1, "mm"))
clickx <- unittrim(click.locn$x)
clicky <- unittrim(click.locn$y)
grid.text(paste0("(", clickx, ", ", clicky, ")"),
click.locn$x + unit(2, "mm"), click.locn$y,
just="left")
}
grid.newpage() # (empty slate)
## device
do.click("inches")
Sys.sleep(1)
pushViewport(viewport(width=0.5, height=0.5,
xscale=c(0, 100), yscale=c(0, 10)))
grid.rect()
grid.xaxis()
grid.yaxis()
do.click("native")
popViewport()
}
```
r None
`grid.function` Draw a curve representing a function
-----------------------------------------------------
### Description
Draw a curve representing a function.
### Usage
```
grid.function(...)
functionGrob(f, n = 101, range = "x", units = "native",
name = NULL, gp=gpar(), vp = NULL)
grid.abline(intercept, slope, ...)
```
### Arguments
| | |
| --- | --- |
| `f` | A function that must take a single argument and return a list with two numeric components named `x` and `y`. |
| `n` | The number values that will be generated as input to the function `f`. |
| `range` | Either `"x"`, `"y"`, or a numeric vector. See the ‘Details’ section. |
| `units` | A string indicating the units to use for the `x` and `y` values generated by the function. |
| `intercept` | Numeric. |
| `slope` | Numeric. |
| `...` | Arguments passed to `grid.function()` |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
### Details
`n` values are generated and passed to the function `f` and a series of lines are drawn through the resulting `x` and `y` values.
The generation of the `n` values depends on the value of `range`. In the default case, `dim` is `"x"`, which means that a set of `x` values are generated covering the range of the current viewport scale in the x-dimension. If `dim` is `"y"` then values are generated from the current y-scale instead. If `range` is a numeric vector, then values are generated from that range.
`grid.abline()` provides a simple front-end for a straight line parameterized by `intercept` and `slope`.
### Value
A functiongrob grob.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
# abline
# NOTE: in ROOT viewport on screen, (0, 0) at top-left
# and "native" is pixels!
grid.function(function(x) list(x=x, y=0 + 1*x))
# a more "normal" viewport with default normalized "native" coords
grid.newpage()
pushViewport(viewport())
grid.function(function(x) list(x=x, y=0 + 1*x))
# slightly simpler
grid.newpage()
pushViewport(viewport())
grid.abline()
# sine curve
grid.newpage()
pushViewport(viewport(xscale=c(0, 2*pi), yscale=c(-1, 1)))
grid.function(function(x) list(x=x, y=sin(x)))
# constrained sine curve
grid.newpage()
pushViewport(viewport(xscale=c(0, 2*pi), yscale=c(-1, 1)))
grid.function(function(x) list(x=x, y=sin(x)),
range=0:1)
# inverse sine curve
grid.newpage()
pushViewport(viewport(xscale=c(-1, 1), yscale=c(0, 2*pi)))
grid.function(function(y) list(x=sin(y), y=y),
range="y")
# parametric function
grid.newpage()
pushViewport(viewport(xscale=c(-1, 1), yscale=c(-1, 1)))
grid.function(function(t) list(x=cos(t), y=sin(t)),
range=c(0, 9*pi/5))
# physical abline
grid.newpage()
grid.function(function(x) list(x=x, y=0 + 1*x),
units="in")
```
r None
`grid.add` Add a Grid Graphical Object
---------------------------------------
### Description
Add a grob to a gTree or a descendant of a gTree.
### Usage
```
grid.add(gPath, child, strict = FALSE, grep = FALSE,
global = FALSE, allDevices = FALSE, redraw = TRUE)
addGrob(gTree, child, gPath = NULL, strict = FALSE, grep = FALSE,
global = FALSE, warn = TRUE)
setChildren(x, children)
```
### Arguments
| | |
| --- | --- |
| `gTree, x` | A gTree object. |
| `gPath` | A gPath object. For `grid.add` this specifies a gTree on the display list. For `addGrob` this specifies a descendant of the specified gTree. |
| `child` | A grob object. |
| `children` | A gList object. |
| `strict` | A boolean indicating whether the gPath must be matched exactly. |
| `grep` | A boolean indicating whether the `gPath` should be treated as a regular expression. Values are recycled across elements of the `gPath` (e.g., `c(TRUE, FALSE)` means that every odd element of the `gPath` will be treated as a regular expression). |
| `global` | A boolean indicating whether the function should affect just the first match of the `gPath`, or whether all matches should be affected. |
| `warn` | A logical to indicate whether failing to find the specified gPath should trigger an error. |
| `allDevices` | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED. |
| `redraw` | A logical value to indicate whether to redraw the grob. |
### Details
`addGrob` copies the specified grob and returns a modified grob.
`grid.add` destructively modifies a grob on the display list. If `redraw` is `TRUE` it then redraws everything to reflect the change.
`setChildren` is a basic function for setting all children of a gTree at once (instead of repeated calls to `addGrob`).
### Value
`addGrob` returns a grob object; `grid.add` returns `NULL`.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)`, `[getGrob](grid.get)`, `[addGrob](grid.add)`, `[removeGrob](grid.remove)`.
| programming_docs |
r None
`legendGrob` Constructing a Legend Grob
----------------------------------------
### Description
Constructing a legend grob (in progress)
### Usage
```
legendGrob(labels, nrow, ncol, byrow = FALSE,
do.lines = has.lty || has.lwd, lines.first = TRUE,
hgap = unit(1, "lines"), vgap = unit(1, "lines"),
default.units = "lines", pch, gp = gpar(), vp = NULL)
grid.legend(..., draw=TRUE)
```
### Arguments
| | |
| --- | --- |
| `labels` | legend labels (expressions) |
| `nrow, ncol` | integer; the number of rows or columns, respectively of the legend “layout”. `nrow` is optional and typically computed from the number of labels and `ncol`. |
| `byrow` | logical indicating whether rows of the legend are filled first. |
| `do.lines` | logical indicating whether legend lines are drawn. |
| `lines.first` | logical indicating whether legend lines are drawn first and hence in a plain “below” legend symbols. |
| `hgap` | horizontal space between the legend entries |
| `vgap` | vertical space between the legend entries |
| `default.units` | default units, see `<unit>`. |
| `pch` | legend symbol, numeric or character, passed to `[pointsGrob](grid.points)()`; see also `[points](../../graphics/html/points)` for interpretation of the numeric codes. |
| `gp` | an **R** object of class `"gpar"`, typically the output from a call to the function `<gpar>`, is basically a list of graphical parameter settings. |
| `vp` | a Grid `<viewport>` object (or `NULL`). |
| `...` | for `grid.legend()`: all the arguments above are passed to `legendGrob()`. |
| `draw` | logical indicating whether graphics output should be produced. |
### Value
Both functions create a legend `[grob](grid.grob)` (a graphical object describing a plot legend), but only `grid.legend` draws it (only if `draw` is `TRUE`).
### See Also
[Grid](grid), `<viewport>`; `[pointsGrob](grid.points)`, `[linesGrob](grid.lines)`.
`<grid.plot.and.legend>` contains a simple example.
### Examples
```
## Data:
n <- 10
x <- stats::runif(n) ; y1 <- stats::runif(n) ; y2 <- stats::runif(n)
## Construct the grobs :
plot <- gTree(children=gList(rectGrob(),
pointsGrob(x, y1, pch=21, gp=gpar(col=2, fill="gray")),
pointsGrob(x, y2, pch=22, gp=gpar(col=3, fill="gray")),
xaxisGrob(),
yaxisGrob()))
legd <- legendGrob(c("Girls", "Boys", "Other"), pch=21:23,
gp=gpar(col = 2:4, fill = "gray"))
gg <- packGrob(packGrob(frameGrob(), plot),
legd, height=unit(1,"null"), side="right")
## Now draw it on a new device page:
grid.newpage()
pushViewport(viewport(width=0.8, height=0.8))
grid.draw(gg)
```
r None
`grid.reorder` Reorder the children of a gTree
-----------------------------------------------
### Description
Change the order in which the children of a gTree get drawn.
### Usage
```
grid.reorder(gPath, order, back=TRUE, grep=FALSE, redraw=TRUE)
reorderGrob(x, order, back=TRUE)
```
### Arguments
| | |
| --- | --- |
| `gPath` | A gPath object specifying a gTree within the current scene. |
| `x` | A gTree object to be modified. |
| `order` | A character vector or a numeric vector that specifies the new drawing order for the children of the gTree. May not refer to all children of the gTree (see Details). |
| `back` | Controls what happens when the `order` does not specify all children of the gTree (see Details). |
| `grep` | Should the `gPath` be treated as a regular expression? |
| `redraw` | Should the modified scene be redrawn? |
### Details
In the simplest case, `order` specifies a new ordering for all of the children of the gTree. The children may be specified either by name or by existing numerical order.
If the `order` does not specify all children of the gTree then, by default, the children specified by `order` are drawn first and then all remaining children are drawn. If `back=FALSE` then the children not specified in `order` are drawn first, followed by the specified children. This makes it easy to specify a send-to-back or bring-to-front reordering. The `order` argument is *always* in back-to-front order.
It is not possible to reorder the grid display list (the top-level grobs in the current scene) because the display list is a mixture of grobs and viewports (so it is not clear what reordering even means and it would be too easy to end up with a scene that would not draw). If you want to reorder the grid display list, try `grid.grab()` to create a gTree and then reorder (and redraw) that gTree.
### Value
`grid.reorder()` is called for its side-effect of modifying the current scene. `reorderGrob()` returns the modified gTree.
### Warning
This function may return a gTree that will not draw. For example, a gTree has two children, A and B (in that order), and the width of child B depends on the width of child A (e.g., a box around a piece of text). Switching the order so that B is drawn before A will not allow B to be drawn. If this happens with `grid.reorder()`, the modification will not be performed. If this happens with `reorderGrob()` it should be possible simply to restore the original order.
### Author(s)
Paul Murrell
### Examples
```
# gTree with two children, "red-rect" and "blue-rect" (in that order)
gt <- gTree(children=gList(
rectGrob(gp=gpar(col=NA, fill="red"),
width=.8, height=.2, name="red-rect"),
rectGrob(gp=gpar(col=NA, fill="blue"),
width=.2, height=.8, name="blue-rect")),
name="gt")
grid.newpage()
grid.draw(gt)
# Spec entire order as numeric (blue-rect, red-rect)
grid.reorder("gt", 2:1)
# Spec entire order as character
grid.reorder("gt", c("red-rect", "blue-rect"))
# Only spec the one I want behind as character
grid.reorder("gt", "blue-rect")
# Only spec the one I want in front as character
grid.reorder("gt", "blue-rect", back=FALSE)
```
r None
`grid.null` Null Graphical Object
----------------------------------
### Description
These functions create a NULL graphical object, which has zero width, zero height, and draw nothing. It can be used as a place-holder or as an invisible reference point for other drawing.
### Usage
```
nullGrob(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
default.units = "npc",
name = NULL, vp = NULL)
grid.null(...)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-location. |
| `y` | A numeric vector or unit object specifying y-location. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments passed to `nullGrob()`. |
### Value
A null grob.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
grid.newpage()
grid.null(name="ref")
grid.rect(height=grobHeight("ref"))
grid.segments(0, 0, grobX("ref", 0), grobY("ref", 0))
```
r None
`grid.roundrect` Draw a rectangle with rounded corners
-------------------------------------------------------
### Description
Draw a *single* rectangle with rounded corners.
### Usage
```
roundrectGrob(x=0.5, y=0.5, width=1, height=1,
default.units="npc",
r=unit(0.1, "snpc"),
just="centre",
name=NULL, gp=NULL, vp=NULL)
grid.roundrect(...)
```
### Arguments
| | |
| --- | --- |
| `x, y, width, height` | The location and size of the rectangle. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `r` | The radius of the rounded corners. |
| `just` | The justification of the rectangle relative to its location. |
| `name` | A name to identify the grob. |
| `gp` | Graphical parameters to apply to the grob. |
| `vp` | A viewport object or `NULL`. |
| `...` | Arguments to be passed to `roundrectGrob()`. |
### Details
At present, this function can only be used to draw *one* rounded rectangle.
### Examples
```
grid.roundrect(width=.5, height=.5, name="rr")
theta <- seq(0, 360, length.out=50)
for (i in 1:50)
grid.circle(x=grobX("rr", theta[i]),
y=grobY("rr", theta[i]),
r=unit(1, "mm"),
gp=gpar(fill="black"))
```
r None
`grobName` Generate a Name for a Grob
--------------------------------------
### Description
This function generates a unique (within-session) name for a grob, based on the grob's class.
### Usage
```
grobName(grob = NULL, prefix = "GRID")
```
### Arguments
| | |
| --- | --- |
| `grob` | A grob object or `NULL`. |
| `prefix` | The prefix part of the name. |
### Value
A character string of the form `prefix.class(grob).index`
### Author(s)
Paul Murrell
r None
`makeContent` Customised grid Grobs
------------------------------------
### Description
These generic hook functions are called whenever a grid grob is drawn. They provide an opportunity for customising the drawing context and drawing content of a new class derived from grob (or gTree).
### Usage
```
makeContext(x)
makeContent(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
### Details
These functions are called by the `grid.draw` methods for grobs and gTrees.
`makeContext` is called first during the drawing of a grob. This function should be used to *modify* the `vp` slot of `x` (and/or the `childrenvp` slot if `x` is a gTree). The function *must* return the modified `x`. Note that the default behaviour for grobs is to push any viewports in the `vp` slot, and for gTrees is to also push and up any viewports in the `childrenvp` slot, so this function is used to customise the drawing context for a grob or gTree.
`makeContent` is called next and is where any additional calculations should occur and graphical content should be generated (see, for example, `grid:::makeContent.xaxis`). This function should be used to *modify* the `children` of a gTree. The function *must* return the modified `x`. Note that the default behaviour for gTrees is to draw all grobs in the `children` slot, so this function is used to customise the drawing content for a gTree. It is also possible to customise the drawing content for a simple grob, but more care needs to be taken; for example, the function should return a standard grid primitive with a `drawDetails()` method in this case.
Note that these functions should be *cumulative* in their effects, so that the `x` returned by `makeContent()` *includes* any changes made by `makeContext()`.
Note that `makeContext` is also called in the calculation of `"grobwidth"` and `"grobheight"` units.
### Value
Both functions are expected to return a grob or gTree (a modified version of `x`).
### Author(s)
Paul Murrell
### See Also
`<grid.draw>`
r None
`grid.xspline` Draw an Xspline
-------------------------------
### Description
These functions create and draw an xspline, a curve drawn relative to control points.
### Usage
```
grid.xspline(...)
xsplineGrob(x = c(0, 0.5, 1, 0.5), y = c(0.5, 1, 0.5, 0),
id = NULL, id.lengths = NULL,
default.units = "npc",
shape = 0, open = TRUE, arrow = NULL, repEnds = TRUE,
name = NULL, gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-locations of spline control points. |
| `y` | A numeric vector or unit object specifying y-locations of spline control points. |
| `id` | A numeric vector used to separate locations in `x` and `y` into multiple xsplines. All locations with the same `id` belong to the same xspline. |
| `id.lengths` | A numeric vector used to separate locations in `x` and `y` into multiple xspline. Specifies consecutive blocks of locations which make up separate xsplines. |
| `default.units` | A string indicating the default units to use if `x` or `y` are only given as numeric vectors. |
| `shape` | A numeric vector of values between -1 and 1, which control the shape of the spline relative to the control points. |
| `open` | A logical value indicating whether the spline is a line or a closed shape. |
| `arrow` | A list describing arrow heads to place at either end of the xspline, as produced by the `arrow` function. |
| `repEnds` | A logical value indicating whether the first and last control points should be replicated for drawing the curve (see Details below). |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `vp` | A Grid viewport object (or NULL). |
| `...` | Arguments to be passed to `xsplineGrob`. |
### Details
Both functions create an xspline grob (a graphical object describing an xspline), but only `grid.xspline` draws the xspline.
An xspline is a line drawn relative to control points. For each control point, the line may pass through (interpolate) the control point or it may only approach (approximate) the control point; the behaviour is determined by a shape parameter for each control point.
If the shape parameter is greater than zero, the spline approximates the control points (and is very similar to a cubic B-spline when the shape is 1). If the shape parameter is less than zero, the spline interpolates the control points (and is very similar to a Catmull-Rom spline when the shape is -1). If the shape parameter is 0, the spline forms a sharp corner at that control point.
For open xsplines, the start and end control points must have a shape of 0 (and non-zero values are silently converted to zero without warning).
For open xsplines, by default the start and end control points are actually replicated before the curve is drawn. A curve is drawn between (interpolating or approximating) the second and third of each set of four control points, so this default behaviour ensures that the resulting curve starts at the first control point you have specified and ends at the last control point. The default behaviour can be turned off via the `repEnds` argument, in which case the curve that is drawn starts (approximately) at the second control point and ends (approximately) at the first and second-to-last control point.
The `repEnds` argument is ignored for closed xsplines.
Missing values are not allowed for `x` and `y` (i.e., it is not valid for a control point to be missing).
For closed xsplines, a curve is automatically drawn between the final control point and the initial control point.
### Value
A grob object.
### References
Blanc, C. and Schlick, C. (1995), "X-splines : A Spline Model Designed for the End User", in *Proceedings of SIGGRAPH 95*, pp. 377–386. <https://dept-info.labri.fr/~schlick/DOC/sig1.html>
### See Also
[Grid](grid), `<viewport>`, `<arrow>`.
`[xspline](../../graphics/html/xspline)`.
### Examples
```
x <- c(0.25, 0.25, 0.75, 0.75)
y <- c(0.25, 0.75, 0.75, 0.25)
xsplineTest <- function(s, i, j, open) {
pushViewport(viewport(layout.pos.col=j, layout.pos.row=i))
grid.points(x, y, default.units="npc", pch=16, size=unit(2, "mm"))
grid.xspline(x, y, shape=s, open=open, gp=gpar(fill="grey"))
grid.text(s, gp=gpar(col="grey"),
x=unit(x, "npc") + unit(c(-1, -1, 1, 1), "mm"),
y=unit(y, "npc") + unit(c(-1, 1, 1, -1), "mm"),
hjust=c(1, 1, 0, 0),
vjust=c(1, 0, 0, 1))
popViewport()
}
pushViewport(viewport(width=.5, x=0, just="left",
layout=grid.layout(3, 3, respect=TRUE)))
pushViewport(viewport(layout.pos.row=1))
grid.text("Open Splines", y=1, just="bottom")
popViewport()
xsplineTest(c(0, -1, -1, 0), 1, 1, TRUE)
xsplineTest(c(0, -1, 0, 0), 1, 2, TRUE)
xsplineTest(c(0, -1, 1, 0), 1, 3, TRUE)
xsplineTest(c(0, 0, -1, 0), 2, 1, TRUE)
xsplineTest(c(0, 0, 0, 0), 2, 2, TRUE)
xsplineTest(c(0, 0, 1, 0), 2, 3, TRUE)
xsplineTest(c(0, 1, -1, 0), 3, 1, TRUE)
xsplineTest(c(0, 1, 0, 0), 3, 2, TRUE)
xsplineTest(c(0, 1, 1, 0), 3, 3, TRUE)
popViewport()
pushViewport(viewport(width=.5, x=1, just="right",
layout=grid.layout(3, 3, respect=TRUE)))
pushViewport(viewport(layout.pos.row=1))
grid.text("Closed Splines", y=1, just="bottom")
popViewport()
xsplineTest(c(-1, -1, -1, -1), 1, 1, FALSE)
xsplineTest(c(-1, -1, 0, -1), 1, 2, FALSE)
xsplineTest(c(-1, -1, 1, -1), 1, 3, FALSE)
xsplineTest(c( 0, 0, -1, 0), 2, 1, FALSE)
xsplineTest(c( 0, 0, 0, 0), 2, 2, FALSE)
xsplineTest(c( 0, 0, 1, 0), 2, 3, FALSE)
xsplineTest(c( 1, 1, -1, 1), 3, 1, FALSE)
xsplineTest(c( 1, 1, 0, 1), 3, 2, FALSE)
xsplineTest(c( 1, 1, 1, 1), 3, 3, FALSE)
popViewport()
```
r None
`widthDetails` Width and Height of a grid grob
-----------------------------------------------
### Description
These generic functions are used to determine the size of grid grobs.
### Usage
```
widthDetails(x)
heightDetails(x)
ascentDetails(x)
descentDetails(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
### Details
These functions are called in the calculation of `"grobwidth"` and `"grobheight"` units. Methods should be written for classes derived from grob or gTree where the size of the grob can be determined (see, for example `grid:::widthDetails.frame`).
The ascent of a grob is the height of the grob by default and the descent of a grob is zero by default, except for text grobs where the label is a single character value or expression.
### Value
A unit object.
### Author(s)
Paul Murrell
### See Also
`<absolute.size>`.
r None
`grobWidth` Create a Unit Describing the Width of a Grob
---------------------------------------------------------
### Description
These functions create a unit object describing the width or height of a grob. They are generic.
### Usage
```
grobWidth(x)
grobHeight(x)
grobAscent(x)
grobDescent(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A grob object. |
### Value
A unit object.
### Author(s)
Paul Murrell
### See Also
`<unit>` and `[stringWidth](stringwidth)`
r None
`grid.polygon` Draw a Polygon
------------------------------
### Description
These functions create and draw a polygon. The final point will automatically be connected to the initial point.
### Usage
```
grid.polygon(x=c(0, 0.5, 1, 0.5), y=c(0.5, 1, 0.5, 0),
id=NULL, id.lengths=NULL,
default.units="npc", name=NULL,
gp=gpar(), draw=TRUE, vp=NULL)
polygonGrob(x=c(0, 0.5, 1, 0.5), y=c(0.5, 1, 0.5, 0),
id=NULL, id.lengths=NULL,
default.units="npc", name=NULL,
gp=gpar(), vp=NULL)
```
### Arguments
| | |
| --- | --- |
| `x` | A numeric vector or unit object specifying x-locations. |
| `y` | A numeric vector or unit object specifying y-locations. |
| `id` | A numeric vector used to separate locations in `x` and `y` into multiple polygons. All locations with the same `id` belong to the same polygon. |
| `id.lengths` | A numeric vector used to separate locations in `x` and `y` into multiple polygons. Specifies consecutive blocks of locations which make up separate polygons. |
| `default.units` | A string indicating the default units to use if `x`, `y`, `width`, or `height` are only given as numeric vectors. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or NULL). |
### Details
Both functions create a polygon grob (a graphical object describing a polygon), but only `grid.polygon` draws the polygon (and then only if `draw` is `TRUE`).
### Value
A grob object.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
grid.polygon()
# Using id (NOTE: locations are not in consecutive blocks)
grid.newpage()
grid.polygon(x=c((0:4)/10, rep(.5, 5), (10:6)/10, rep(.5, 5)),
y=c(rep(.5, 5), (10:6/10), rep(.5, 5), (0:4)/10),
id=rep(1:5, 4),
gp=gpar(fill=1:5))
# Using id.lengths
grid.newpage()
grid.polygon(x=outer(c(0, .5, 1, .5), 5:1/5),
y=outer(c(.5, 1, .5, 0), 5:1/5),
id.lengths=rep(4, 5),
gp=gpar(fill=1:5))
```
| programming_docs |
r None
`grid.yaxis` Draw a Y-Axis
---------------------------
### Description
These functions create and draw a y-axis.
### Usage
```
grid.yaxis(at = NULL, label = TRUE, main = TRUE,
edits = NULL, name = NULL,
gp = gpar(), draw = TRUE, vp = NULL)
yaxisGrob(at = NULL, label = TRUE, main = TRUE,
edits = NULL, name = NULL,
gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `at` | A numeric vector of y-value locations for the tick marks. |
| `label` | A logical value indicating whether to draw the labels on the tick marks, or an expression or character vector which specify the labels to use. If not logical, must be the same length as the `at` argument. |
| `main` | A logical value indicating whether to draw the axis at the left (`TRUE`) or at the right (`FALSE`) of the viewport. |
| `edits` | A gEdit or gEditList containing edit operations to apply (to the children of the axis) when the axis is first created and during redrawing whenever `at` is `NULL`. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or `NULL`). |
### Details
Both functions create a yaxis grob (a graphical object describing a yaxis), but only `grid.yaxis` draws the yaxis (and then only if `draw` is `TRUE`).
### Value
A yaxis grob. `grid.yaxis` returns the value invisibly.
### Children
If the `at` slot of an xaxis grob is not `NULL` then the xaxis will have the following children:
major
representing the line at the base of the tick marks.
ticks
representing the tick marks.
labels
representing the tick labels.
If the `at` slot is `NULL` then there are no children and ticks are drawn based on the current viewport scale.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`, `<grid.xaxis>`
r None
`grid.xaxis` Draw an X-Axis
----------------------------
### Description
These functions create and draw an x-axis.
### Usage
```
grid.xaxis(at = NULL, label = TRUE, main = TRUE,
edits = NULL, name = NULL,
gp = gpar(), draw = TRUE, vp = NULL)
xaxisGrob(at = NULL, label = TRUE, main = TRUE,
edits = NULL, name = NULL,
gp = gpar(), vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `at` | A numeric vector of x-value locations for the tick marks. |
| `label` | A logical value indicating whether to draw the labels on the tick marks, or an expression or character vector which specify the labels to use. If not logical, must be the same length as the `at` argument. |
| `main` | A logical value indicating whether to draw the axis at the bottom (`TRUE`) or at the top (`FALSE`) of the viewport. |
| `edits` | A gEdit or gEditList containing edit operations to apply (to the children of the axis) when the axis is first created and during redrawing whenever `at` is `NULL`. |
| `name` | A character identifier. |
| `gp` | An object of class `"gpar"`, typically the output from a call to the function `<gpar>`. This is basically a list of graphical parameter settings. |
| `draw` | A logical value indicating whether graphics output should be produced. |
| `vp` | A Grid viewport object (or `NULL`). |
### Details
Both functions create an xaxis grob (a graphical object describing an xaxis), but only `grid.xaxis` draws the xaxis (and then only if `draw` is `TRUE`).
### Value
An xaxis grob. `grid.xaxis` returns the value invisibly.
### Children
If the `at` slot of an xaxis grob is not `NULL` then the xaxis will have the following children:
major
representing the line at the base of the tick marks.
ticks
representing the tick marks.
labels
representing the tick labels.
If the `at` slot is `NULL` then there are no children and ticks are drawn based on the current viewport scale.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`, `<grid.yaxis>`
r None
`vpPath` Concatenate Viewport Names
------------------------------------
### Description
This function can be used to generate a viewport path for use in `downViewport` or `seekViewport`.
A viewport path is a list of nested viewport names.
### Usage
```
vpPath(...)
```
### Arguments
| | |
| --- | --- |
| `...` | Character values which are viewport names. |
### Details
Viewport names must only be unique amongst viewports which share the same parent in the viewport tree.
This function can be used to generate a specification for a viewport that includes the viewport's parent's name (and the name of its parent and so on).
For interactive use, it is possible to directly specify a path, but it is strongly recommended that this function is used otherwise in case the path separator is changed in future versions of grid.
### Value
A `vpPath` object.
### See Also
`<viewport>`, `[pushViewport](viewports)`, `[popViewport](viewports)`, `[downViewport](viewports)`, `[seekViewport](viewports)`, `[upViewport](viewports)`
### Examples
```
vpPath("vp1", "vp2")
```
r None
`grid.ls` List the names of grobs or viewports
-----------------------------------------------
### Description
Return a listing of the names of grobs or viewports.
This is a generic function with methods for grobs (including gTrees) and viewports (including vpTrees).
### Usage
```
grid.ls(x=NULL, grobs=TRUE, viewports=FALSE, fullNames=FALSE,
recursive=TRUE, print=TRUE, flatten=TRUE, ...)
nestedListing(x, gindent=" ", vpindent=gindent)
pathListing(x, gvpSep=" | ", gAlign=TRUE)
grobPathListing(x, ...)
```
### Arguments
| | |
| --- | --- |
| `x` | A grob or viewport or `NULL`. If `NULL`, the current grid display list is listed. For print functions, this should be the result of a call to `grid.ls`. |
| `grobs` | A logical value indicating whether to list grobs. |
| `viewports` | A logical value indicating whether to list viewports. |
| `fullNames` | A logical value indicating whether to embellish object names with information about the object type. |
| `recursive` | A logical value indicating whether recursive structures should also list their children. |
| `print` | A logical indicating whether to print the listing or a function that will print the listing. |
| `flatten` | A logical value indicating whether to flatten the listing. Otherwise a more complex hierarchical object is produced. |
| `gindent` | The indent used to show nesting in the output for grobs. |
| `vpindent` | The indent used to show nesting in the output for viewports. |
| `gvpSep` | The string used to separate viewport paths from grob paths. |
| `gAlign` | Logical indicating whether to align the left hand edge of all grob paths. |
| `...` | Arguments passed to the `print` function. |
### Details
If the argument `x` is `NULL`, the current contents of the grid display list are listed (both viewports and grobs). In other words, all objects representing the current scene are listed.
Otherwise, `x` should be a grob or a viewport.
The default behaviour of this function is to print information about the grobs in the current scene. It is also possible to add information about the viewports in the scene. By default, the listing is recursive, so all children of gTrees and all nested viewports are reported.
The format of the information can be controlled via the `print` argument, which can be given a function to perform the formatting. The `nestedListing` function produces a line per grob or viewport, with indenting used to show nesting. The `pathListing` function produces a line per grob or viewport, with viewport paths and grob paths used to show nesting. The `grobPathListing` is a simple derivation that only shows lines for grobs. The user can define new functions.
### Value
The result of this function is either a `"gridFlatListing"` object (if `flatten` is `TRUE`) or a `"gridListing"` object.
The former is a simple (flat) list of vectors. This is convenient, for example, for working programmatically with the list of grob and viewport names, or for writing a new display function for the listing.
The latter is a more complex hierarchical object (list of lists), but it does contain more detailed information so may be of use for more advanced customisations.
### Author(s)
Paul Murrell
### See Also
`[grob](grid.grob)` `<viewport>`
### Examples
```
# A gTree, called "parent", with childrenvp vpTree (vp2 within vp1)
# and child grob, called "child", with vp vpPath (down to vp2)
sampleGTree <- gTree(name="parent",
children=gList(grob(name="child", vp="vp1::vp2")),
childrenvp=vpTree(parent=viewport(name="vp1"),
children=vpList(viewport(name="vp2"))))
grid.ls(sampleGTree)
# Show viewports too
grid.ls(sampleGTree, viewports=TRUE)
# Only show viewports
grid.ls(sampleGTree, viewports=TRUE, grobs=FALSE)
# Alternate displays
# nested listing, custom indent
grid.ls(sampleGTree, viewports=TRUE, print=nestedListing, gindent="--")
# path listing
grid.ls(sampleGTree, viewports=TRUE, print=pathListing)
# path listing, without grobs aligned
grid.ls(sampleGTree, viewports=TRUE, print=pathListing, gAlign=FALSE)
# grob path listing
grid.ls(sampleGTree, viewports=TRUE, print=grobPathListing)
# path listing, grobs only
grid.ls(sampleGTree, print=pathListing)
# path listing, viewports only
grid.ls(sampleGTree, viewports=TRUE, grobs=FALSE, print=pathListing)
# raw flat listing
str(grid.ls(sampleGTree, viewports=TRUE, print=FALSE))
```
r None
`grid-package` The Grid Graphics Package
-----------------------------------------
### Description
A rewrite of the graphics layout capabilities, plus some support for interaction.
### Details
This package contains a graphics system which supplements S-style graphics (see the graphics package).
Further information is available in the following [vignettes](../../utils/html/vignette):
| | |
| --- | --- |
| `grid` | Introduction to `grid` (../doc/grid.pdf) |
| `displaylist` | Display Lists in `grid` (../doc/displaylist.pdf) |
| `frame` | Frames and packing grobs (../doc/frame.pdf) |
| `grobs` | Working with `grid` grobs (../doc/grobs.pdf) |
| `interactive` | Editing `grid` Graphics (../doc/interactive.pdf) |
| `locndimn` | Locations versus Dimensions (../doc/locndimn.pdf) |
| `moveline` | Demonstrating move-to and line-to (../doc/moveline.pdf) |
| `nonfinite` | How `grid` responds to non-finite values (../doc/nonfinite.pdf) |
| `plotexample` | Writing `grid` Code (../doc/plotexample.pdf) |
| `rotated` | Rotated Viewports (../doc/rotated.pdf) |
| `saveload` | Persistent representations (../doc/saveload.pdf) |
| `sharing` | Modifying multiple grobs simultaneously (../doc/sharing.pdf) |
| `viewports` | Working with `grid` viewports (../doc/viewports.pdf) |
| |
For a complete list of functions with individual help pages, use `library(help="grid")`.
### Author(s)
Paul Murrell [[email protected]](mailto:[email protected])
Maintainer: R Core Team [[email protected]](mailto:[email protected])
### References
Murrell, P. (2005). *R Graphics*. Chapman & Hall/CRC Press.
r None
`validDetails` Customising grid grob Validation
------------------------------------------------
### Description
This generic hook function is called whenever a grid grob is created or edited via `grob`, `gTree`, `grid.edit` or `editGrob`. This provides an opportunity for customising the validation of a new class derived from grob (or gTree).
### Usage
```
validDetails(x)
```
### Arguments
| | |
| --- | --- |
| `x` | A grid grob. |
### Details
This function is called by `grob`, `gTree`, `grid.edit` and `editGrob`. A method should be written for classes derived from grob or gTree to validate the values of slots specific to the new class. (e.g., see `grid:::validDetails.axis`).
Note that the standard slots for grobs and gTrees are automatically validated (e.g., `vp`, `gp` slots for grobs and, in addition, `children`, and `childrenvp` slots for gTrees) so only slots specific to a new class need to be addressed.
### Value
The function MUST return the validated grob.
### Author(s)
Paul Murrell
### See Also
`<grid.edit>`
r None
`unit.pmin` Parallel Unit Minima and Maxima
--------------------------------------------
### Description
Returns a unit object whose i'th value is the minimum (or maximum) of the i'th values of the arguments.
### Usage
```
unit.pmin(...)
unit.pmax(...)
unit.psum(...)
```
### Arguments
| | |
| --- | --- |
| `...` | One or more unit objects. |
### Details
The length of the result is the maximum of the lengths of the arguments; shorter arguments are recycled in the usual manner.
### Value
A unit object.
### Author(s)
Paul Murrell
### Examples
```
max(unit(1:3, "cm"), unit(0.5, "npc"))
unit.pmax(unit(1:3, "cm"), unit(0.5, "npc"))
```
r None
`grid.show.viewport` Draw a Diagram of a Grid Viewport
-------------------------------------------------------
### Description
This function uses Grid graphics to draw a diagram of a Grid viewport.
### Usage
```
grid.show.viewport(v, parent.layout = NULL, newpage = TRUE,
vp.ex = 0.8, border.fill="light grey",
vp.col="blue", vp.fill="light blue",
scale.col="red",
vp = NULL)
```
### Arguments
| | |
| --- | --- |
| `v` | A Grid viewport object. |
| `parent.layout` | A grid layout object. If this is not NULL and the viewport given in `v` has its location specified relative to the layout, then the diagram shows the layout and which cells `v` occupies within the layout. |
| `newpage` | A logical value to indicate whether to move to a new page before drawing the diagram. |
| `vp.ex` | positive number, typically in *(0,1]*, specifying the scaling of the layout. |
| `border.fill` | Colour to fill the border margin. |
| `vp.col` | Colour for the border of the viewport region. |
| `vp.fill` | Colour to fill the viewport region. |
| `scale.col` | Colour to draw the viewport axes. |
| `vp` | A Grid viewport object (or NULL). |
### Details
A viewport is created within `vp` to provide a margin for annotation, and the diagram is drawn within that new viewport. By default, the margin is filled with light grey, the new viewport is filled with white and framed with a black border, and the viewport region is filled with light blue and framed with a blue border. The diagram is annotated with the width and height (including units) of the viewport, the (x, y) location of the viewport, and the x- and y-scales of the viewport, using red lines and text.
### Value
None.
### Author(s)
Paul Murrell
### See Also
[Grid](grid), `<viewport>`
### Examples
```
## Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
width=unit(1, "inches"), height=unit(1, "inches")))
grid.show.viewport(viewport(layout.pos.row=2, layout.pos.col=2:3),
grid.layout(3, 4))
```
r An Introduction to R An Introduction to R
====================
This is an introduction to R (“GNU S”), a language and environment for statistical computing and graphics. R is similar to the award-winning[1](#FOOT1) S system, which was developed at Bell Laboratories by John Chambers et al. It provides a wide variety of statistical and graphical techniques (linear and nonlinear modelling, statistical tests, time series analysis, classification, clustering, ...).
This manual provides information on data types, programming elements, statistical modelling and graphics.
This manual is for R, version 4.1.0 (2021-05-18).
Copyright © 1990 W. N. Venables
Copyright © 1992 W. N. Venables & D. M. Smith
Copyright © 1997 R. Gentleman & R. Ihaka
Copyright © 1997, 1998 M. Maechler
Copyright © 1999–2021 R Core Team
> Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
>
> Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
>
> Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team.
>
>
>
Preface
-------
This introduction to R is derived from an original set of notes describing the S and S-PLUS environments written in 1990–2 by Bill Venables and David M. Smith when at the University of Adelaide. We have made a number of small changes to reflect differences between the R and S programs, and expanded some of the material.
We would like to extend warm thanks to Bill Venables (and David Smith) for granting permission to distribute this modified version of the notes in this way, and for being a supporter of R from way back.
Comments and corrections are always welcome. Please address email correspondence to [[email protected]](mailto:[email protected]).
#### Suggestions to the reader
Most R novices will start with the introductory session in Appendix A. This should give some familiarity with the style of R sessions and more importantly some instant feedback on what actually happens.
Many users will come to R mainly for its graphical facilities. See [Graphics](#Graphics), which can be read at almost any time and need not wait until all the preceding sections have been digested.
1 Introduction and preliminaries
--------------------------------
### 1.1 The R environment
R is an integrated suite of software facilities for data manipulation, calculation and graphical display. Among other things it has
* an effective data handling and storage facility,
* a suite of operators for calculations on arrays, in particular matrices,
* a large, coherent, integrated collection of intermediate tools for data analysis,
* graphical facilities for data analysis and display either directly at the computer or on hardcopy, and
* a well developed, simple and effective programming language (called ‘S’) which includes conditionals, loops, user defined recursive functions and input and output facilities. (Indeed most of the system supplied functions are themselves written in the S language.)
The term “environment” is intended to characterize it as a fully planned and coherent system, rather than an incremental accretion of very specific and inflexible tools, as is frequently the case with other data analysis software.
R is very much a vehicle for newly developing methods of interactive data analysis. It has developed rapidly, and has been extended by a large collection of *packages*. However, most programs written in R are essentially ephemeral, written for a single piece of data analysis.
### 1.2 Related software and documentation
R can be regarded as an implementation of the S language which was developed at Bell Laboratories by Rick Becker, John Chambers and Allan Wilks, and also forms the basis of the S-PLUS systems.
The evolution of the S language is characterized by four books by John Chambers and coauthors. For R, the basic reference is *The New S Language: A Programming Environment for Data Analysis and Graphics* by Richard A. Becker, John M. Chambers and Allan R. Wilks. The new features of the 1991 release of S are covered in *Statistical Models in S* edited by John M. Chambers and Trevor J. Hastie. The formal methods and classes of the **methods** package are based on those described in *Programming with Data* by John M. Chambers. See [References](#References), for precise references.
There are now a number of books which describe how to use R for data analysis and statistics, and documentation for S/S-PLUS can typically be used with R, keeping the differences between the S implementations in mind. See What documentation exists for R? in The R statistical system FAQ.
### 1.3 R and statistics
Our introduction to the R environment did not mention *statistics*, yet many people use R as a statistics system. We prefer to think of it of an environment within which many classical and modern statistical techniques have been implemented. A few of these are built into the base R environment, but many are supplied as *packages*. There are about 25 packages supplied with R (called “standard” and “recommended” packages) and many more are available through the CRAN family of Internet sites (via <https://CRAN.R-project.org>) and elsewhere. More details on packages are given later (see [Packages](#Packages)).
Most classical statistics and much of the latest methodology is available for use with R, but users may need to be prepared to do a little work to find it.
There is an important difference in philosophy between S (and hence R) and the other main statistical systems. In S a statistical analysis is normally done as a series of steps, with intermediate results being stored in objects. Thus whereas SAS and SPSS will give copious output from a regression or discriminant analysis, R will give minimal output and store the results in a fit object for subsequent interrogation by further R functions.
### 1.4 R and the window system
The most convenient way to use R is at a graphics workstation running a windowing system. This guide is aimed at users who have this facility. In particular we will occasionally refer to the use of R on an X window system although the vast bulk of what is said applies generally to any implementation of the R environment.
Most users will find it necessary to interact directly with the operating system on their computer from time to time. In this guide, we mainly discuss interaction with the operating system on UNIX machines. If you are running R under Windows or macOS you will need to make some small adjustments.
Setting up a workstation to take full advantage of the customizable features of R is a straightforward if somewhat tedious procedure, and will not be considered further here. Users in difficulty should seek local expert help.
### 1.5 Using R interactively
When you use the R program it issues a prompt when it expects input commands. The default prompt is ‘``>``’, which on UNIX might be the same as the shell prompt, and so it may appear that nothing is happening. However, as we shall see, it is easy to change to a different R prompt if you wish. We will assume that the UNIX shell prompt is ‘``$``’.
In using R under UNIX the suggested procedure for the first occasion is as follows:
1. Create a separate sub-directory, say `work`, to hold data files on which you will use R for this problem. This will be the working directory whenever you use R for this particular problem.
```
$ mkdir work
$ cd work
```
2. Start the R program with the command
```
$ R
```
3. At this point R commands may be issued (see later).
4. To quit the R program the command is
```
> q()
```
At this point you will be asked whether you want to save the data from your R session. On some systems this will bring up a dialog box, and on others you will receive a text prompt to which you can respond `yes`, `no` or `cancel` (a single letter abbreviation will do) to save the data before quitting, quit without saving, or return to the R session. Data which is saved will be available in future R sessions.
Further R sessions are simple.
1. Make `work` the working directory and start the program as before:
```
$ cd work
$ R
```
2. Use the R program, terminating with the `q()` command at the end of the session.
To use R under Windows the procedure to follow is basically the same. Create a folder as the working directory, and set that in the `Start In` field in your R shortcut. Then launch R by double clicking on the icon.
### 1.6 An introductory session
Readers wishing to get a feel for R at a computer before proceeding are strongly advised to work through the introductory session given in [A sample session](#A-sample-session).
### 1.7 Getting help with functions and features
R has an inbuilt help facility similar to the `man` facility of UNIX. To get more information on any specific named function, for example `solve`, the command is
```
> help(solve)
```
An alternative is
```
> ?solve
```
For a feature specified by special characters, the argument must be enclosed in double or single quotes, making it a “character string”: This is also necessary for a few words with syntactic meaning including `if`, `for` and `function`.
```
> help("[[")
```
Either form of quote mark may be used to escape the other, as in the string `"It's important"`. Our convention is to use double quote marks for preference.
On most R installations help is available in HTML format by running
```
> help.start()
```
which will launch a Web browser that allows the help pages to be browsed with hyperlinks. On UNIX, subsequent help requests are sent to the HTML-based help system. The ‘Search Engine and Keywords’ link in the page loaded by `help.start()` is particularly useful as it is contains a high-level concept list which searches though available functions. It can be a great way to get your bearings quickly and to understand the breadth of what R has to offer.
The `help.search` command (alternatively `??`) allows searching for help in various ways. For example,
```
> ??solve
```
Try `?help.search` for details and more examples.
The examples on a help topic can normally be run by
```
> example(topic)
```
Windows versions of R have other optional help systems: use
```
> ?help
```
for further details.
### 1.8 R commands, case sensitivity, etc.
Technically R is an *expression language* with a very simple syntax. It is *case sensitive* as are most UNIX based packages, so `A` and `a` are different symbols and would refer to different variables. The set of symbols which can be used in R names depends on the operating system and country within which R is being run (technically on the *locale* in use). Normally all alphanumeric symbols are allowed[2](#FOOT2) (and in some countries this includes accented letters) plus ‘``.``’ and ‘``_``’, with the restriction that a name must start with ‘``.``’ or a letter, and if it starts with ‘``.``’ the second character must not be a digit. Names are effectively unlimited in length.
Elementary commands consist of either *expressions* or *assignments*. If an expression is given as a command, it is evaluated, printed (unless specifically made invisible), and the value is lost. An assignment also evaluates an expression and passes the value to a variable but the result is not automatically printed.
Commands are separated either by a semi-colon (‘``;``’), or by a newline. Elementary commands can be grouped together into one compound expression by braces (‘``{``’ and ‘``}``’). *Comments* can be put almost[3](#FOOT3) anywhere, starting with a hashmark (‘``#``’), everything to the end of the line is a comment.
If a command is not complete at the end of a line, R will give a different prompt, by default
```
+
```
on second and subsequent lines and continue to read input until the command is syntactically complete. This prompt may be changed by the user. We will generally omit the continuation prompt and indicate continuation by simple indenting.
Command lines entered at the console are limited[4](#FOOT4) to about 4095 bytes (not characters).
### 1.9 Recall and correction of previous commands
Under many versions of UNIX and on Windows, R provides a mechanism for recalling and re-executing previous commands. The vertical arrow keys on the keyboard can be used to scroll forward and backward through a *command history*. Once a command is located in this way, the cursor can be moved within the command using the horizontal arrow keys, and characters can be removed with the DEL key or added with the other keys. More details are provided later: see [The command-line editor](#The-command_002dline-editor).
The recall and editing capabilities under UNIX are highly customizable. You can find out how to do this by reading the manual entry for the **readline** library.
Alternatively, the Emacs text editor provides more general support mechanisms (via ESS, *Emacs Speaks Statistics*) for working interactively with R. See R and Emacs in The R statistical system FAQ.
### 1.10 Executing commands from or diverting output to a file
If commands[5](#FOOT5) are stored in an external file, say `commands.R` in the working directory `work`, they may be executed at any time in an R session with the command
```
> source("commands.R")
```
For Windows **Source** is also available on the **File** menu. The function `sink`,
```
> sink("record.lis")
```
will divert all subsequent output from the console to an external file, `record.lis`. The command
```
> sink()
```
restores it to the console once again.
### 1.11 Data permanency and removing objects
The entities that R creates and manipulates are known as *objects*. These may be variables, arrays of numbers, character strings, functions, or more general structures built from such components.
During an R session, objects are created and stored by name (we discuss this process in the next section). The R command
```
> objects()
```
(alternatively, `ls()`) can be used to display the names of (most of) the objects which are currently stored within R. The collection of objects currently stored is called the *workspace*.
To remove objects the function `rm` is available:
```
> rm(x, y, z, ink, junk, temp, foo, bar)
```
All objects created during an R session can be stored permanently in a file for use in future R sessions. At the end of each R session you are given the opportunity to save all the currently available objects. If you indicate that you want to do this, the objects are written to a file called `.RData`[6](#FOOT6) in the current directory, and the command lines used in the session are saved to a file called `.Rhistory`.
When R is started at later time from the same directory it reloads the workspace from this file. At the same time the associated commands history is reloaded.
It is recommended that you should use separate working directories for analyses conducted with R. It is quite common for objects with names `x` and `y` to be created during an analysis. Names like this are often meaningful in the context of a single analysis, but it can be quite hard to decide what they might be when the several analyses have been conducted in the same directory.
2 Simple manipulations; numbers and vectors
-------------------------------------------
### 2.1 Vectors and assignment
R operates on named *data structures*. The simplest such structure is the numeric *vector*, which is a single entity consisting of an ordered collection of numbers. To set up a vector named `x`, say, consisting of five numbers, namely 10.4, 5.6, 3.1, 6.4 and 21.7, use the R command
```
> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
```
This is an *assignment* statement using the *function* `c()` which in this context can take an arbitrary number of vector *arguments* and whose value is a vector got by concatenating its arguments end to end.[7](#FOOT7)
A number occurring by itself in an expression is taken as a vector of length one.
Notice that the assignment operator (‘``<-``’), which consists of the two characters ‘``<``’ (“less than”) and ‘``-``’ (“minus”) occurring strictly side-by-side and it ‘points’ to the object receiving the value of the expression. In most contexts the ‘``=``’ operator can be used as an alternative.
Assignment can also be made using the function `assign()`. An equivalent way of making the same assignment as above is with:
```
> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7))
```
The usual operator, `<-`, can be thought of as a syntactic short-cut to this.
Assignments can also be made in the other direction, using the obvious change in the assignment operator. So the same assignment could be made using
```
> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x
```
If an expression is used as a complete command, the value is printed *and lost*[8](#FOOT8). So now if we were to use the command
```
> 1/x
```
the reciprocals of the five values would be printed at the terminal (and the value of `x`, of course, unchanged).
The further assignment
```
> y <- c(x, 0, x)
```
would create a vector `y` with 11 entries consisting of two copies of `x` with a zero in the middle place.
### 2.2 Vector arithmetic
Vectors can be used in arithmetic expressions, in which case the operations are performed element by element. Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are *recycled* as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated. So with the above assignments the command
```
> v <- 2*x + y + 1
```
generates a new vector `v` of length 11 constructed by adding together, element by element, `2*x` repeated 2.2 times, `y` repeated just once, and `1` repeated 11 times.
The elementary arithmetic operators are the usual `+`, `-`, `*`, `/` and `^` for raising to a power. In addition all of the common arithmetic functions are available. `log`, `exp`, `sin`, `cos`, `tan`, `sqrt`, and so on, all have their usual meaning. `max` and `min` select the largest and smallest elements of a vector respectively. `range` is a function whose value is a vector of length two, namely `c(min(x), max(x))`. `length(x)` is the number of elements in `x`, `sum(x)` gives the total of the elements in `x`, and `prod(x)` their product.
Two statistical functions are `mean(x)` which calculates the sample mean, which is the same as `sum(x)/length(x)`, and `var(x)` which gives
```
sum((x-mean(x))^2)/(length(x)-1)
```
or sample variance. If the argument to `var()` is an *n*-by-*p* matrix the value is a *p*-by-*p* sample covariance matrix got by regarding the rows as independent *p*-variate sample vectors.
`sort(x)` returns a vector of the same size as `x` with the elements arranged in increasing order; however there are other more flexible sorting facilities available (see `order()` or `sort.list()` which produce a permutation to do the sorting).
Note that `max` and `min` select the largest and smallest values in their arguments, even if they are given several vectors. The *parallel* maximum and minimum functions `pmax` and `pmin` return a vector (of length equal to their longest argument) that contains in each element the largest (smallest) element in that position in any of the input vectors.
For most purposes the user will not be concerned if the “numbers” in a numeric vector are integers, reals or even complex. Internally calculations are done as double precision real numbers, or double precision complex numbers if the input data are complex.
To work with complex numbers, supply an explicit complex part. Thus
```
sqrt(-17)
```
will give `NaN` and a warning, but
```
sqrt(-17+0i)
```
will do the computations as complex numbers.
### 2.3 Generating regular sequences
R has a number of facilities for generating commonly used sequences of numbers. For example `1:30` is the vector `c(1, 2,
…, 29, 30)`. The colon operator has high priority within an expression, so, for example `2*1:15` is the vector `c(2, 4, …, 28, 30)`. Put `n <- 10` and compare the sequences `1:n-1` and `1:(n-1)`.
The construction `30:1` may be used to generate a sequence backwards.
The function `seq()` is a more general facility for generating sequences. It has five arguments, only some of which may be specified in any one call. The first two arguments, if given, specify the beginning and end of the sequence, and if these are the only two arguments given the result is the same as the colon operator. That is `seq(2,10)` is the same vector as `2:10`.
Arguments to `seq()`, and to many other R functions, can also be given in named form, in which case the order in which they appear is irrelevant. The first two arguments may be named `from=value` and `to=value`; thus `seq(1,30)`, `seq(from=1, to=30)` and `seq(to=30,
from=1)` are all the same as `1:30`. The next two arguments to `seq()` may be named `by=value` and `length=value`, which specify a step size and a length for the sequence respectively. If neither of these is given, the default `by=1` is assumed.
For example
```
> seq(-5, 5, by=.2) -> s3
```
generates in `s3` the vector `c(-5.0, -4.8, -4.6, …,
4.6, 4.8, 5.0)`. Similarly
```
> s4 <- seq(length=51, from=-5, by=.2)
```
generates the same vector in `s4`.
The fifth argument may be named `along=vector`, which is normally used as the only argument to create the sequence `1, 2,
…, length(vector)`, or the empty sequence if the vector is empty (as it can be).
A related function is `rep()` which can be used for replicating an object in various complicated ways. The simplest form is
```
> s5 <- rep(x, times=5)
```
which will put five copies of `x` end-to-end in `s5`. Another useful version is
```
> s6 <- rep(x, each=5)
```
which repeats each element of `x` five times before moving on to the next.
### 2.4 Logical vectors
As well as numerical vectors, R allows manipulation of logical quantities. The elements of a logical vector can have the values `TRUE`, `FALSE`, and `NA` (for “not available”, see below). The first two are often abbreviated as `T` and `F`, respectively. Note however that `T` and `F` are just variables which are set to `TRUE` and `FALSE` by default, but are not reserved words and hence can be overwritten by the user. Hence, you should always use `TRUE` and `FALSE`.
Logical vectors are generated by *conditions*. For example
```
> temp <- x > 13
```
sets `temp` as a vector of the same length as `x` with values `FALSE` corresponding to elements of `x` where the condition is *not* met and `TRUE` where it is.
The logical operators are `<`, `<=`, `>`, `>=`, `==` for exact equality and `!=` for inequality. In addition if `c1` and `c2` are logical expressions, then `c1 & c2` is their intersection (*“and”*), `c1 | c2` is their union (*“or”*), and `!c1` is the negation of `c1`.
Logical vectors may be used in ordinary arithmetic, in which case they are *coerced* into numeric vectors, `FALSE` becoming `0` and `TRUE` becoming `1`. However there are situations where logical vectors and their coerced numeric counterparts are not equivalent, for example see the next subsection.
### 2.5 Missing values
In some cases the components of a vector may not be completely known. When an element or value is “not available” or a “missing value” in the statistical sense, a place within a vector may be reserved for it by assigning it the special value `NA`. In general any operation on an `NA` becomes an `NA`. The motivation for this rule is simply that if the specification of an operation is incomplete, the result cannot be known and hence is not available.
The function `is.na(x)` gives a logical vector of the same size as `x` with value `TRUE` if and only if the corresponding element in `x` is `NA`.
```
> z <- c(1:3,NA); ind <- is.na(z)
```
Notice that the logical expression `x == NA` is quite different from `is.na(x)` since `NA` is not really a value but a marker for a quantity that is not available. Thus `x == NA` is a vector of the same length as `x` *all* of whose values are `NA` as the logical expression itself is incomplete and hence undecidable.
Note that there is a second kind of “missing” values which are produced by numerical computation, the so-called *Not a Number*, `NaN`, values. Examples are
```
> 0/0
```
or
```
> Inf - Inf
```
which both give `NaN` since the result cannot be defined sensibly.
In summary, `is.na(xx)` is `TRUE` *both* for `NA` and `NaN` values. To differentiate these, `is.nan(xx)` is only `TRUE` for `NaN`s.
Missing values are sometimes printed as `<NA>` when character vectors are printed without quotes.
### 2.6 Character vectors
Character quantities and character vectors are used frequently in R, for example as plot labels. Where needed they are denoted by a sequence of characters delimited by the double quote character, e.g., `"x-values"`, `"New iteration results"`.
Character strings are entered using either matching double (`"`) or single (`'`) quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using `\` as the escape character, so `\` is entered and printed as `\\`, and inside double quotes `"` is entered as `\"`. Other useful escape sequences are `\n`, newline, `\t`, tab and `\b`, backspace—see `?Quotes` for a full list.
Character vectors may be concatenated into a vector by the `c()` function; examples of their use will emerge frequently.
The `paste()` function takes an arbitrary number of arguments and concatenates them one by one into character strings. Any numbers given among the arguments are coerced into character strings in the evident way, that is, in the same way they would be if they were printed. The arguments are by default separated in the result by a single blank character, but this can be changed by the named argument, `sep=string`, which changes it to `string`, possibly empty.
For example
```
> labs <- paste(c("X","Y"), 1:10, sep="")
```
makes `labs` into the character vector
```
c("X1", "Y2", "X3", "Y4", "X5", "Y6", "X7", "Y8", "X9", "Y10")
```
Note particularly that recycling of short lists takes place here too; thus `c("X", "Y")` is repeated 5 times to match the sequence `1:10`. [9](#FOOT9)
### 2.7 Index vectors; selecting and modifying subsets of a data set
Subsets of the elements of a vector may be selected by appending to the name of the vector an *index vector* in square brackets. More generally any expression that evaluates to a vector may have subsets of its elements similarly selected by appending an index vector in square brackets immediately after the expression.
Such index vectors can be any of four distinct types.
1. **A logical vector**. In this case the index vector is recycled to the same length as the vector from which elements are to be selected. Values corresponding to `TRUE` in the index vector are selected and those corresponding to `FALSE` are omitted. For example
```
> y <- x[!is.na(x)]
```
creates (or re-creates) an object `y` which will contain the non-missing values of `x`, in the same order. Note that if `x` has missing values, `y` will be shorter than `x`. Also
```
> (x+1)[(!is.na(x)) & x>0] -> z
```
creates an object `z` and places in it the values of the vector `x+1` for which the corresponding value in `x` was both non-missing and positive.
2. **A vector of positive integral quantities**. In this case the values in the index vector must lie in the set {1, 2, …, `length(x)`}. The corresponding elements of the vector are selected and concatenated, *in that order*, in the result. The index vector can be of any length and the result is of the same length as the index vector. For example `x[6]` is the sixth component of `x` and
```
> x[1:10]
```
selects the first 10 elements of `x` (assuming `length(x)` is not less than 10). Also
```
> c("x","y")[rep(c(1,2,2,1), times=4)]
```
(an admittedly unlikely thing to do) produces a character vector of length 16 consisting of `"x", "y", "y", "x"` repeated four times.
3. **A vector of negative integral quantities**. Such an index vector specifies the values to be *excluded* rather than included. Thus
```
> y <- x[-(1:5)]
```
gives `y` all but the first five elements of `x`.
4. **A vector of character strings**. This possibility only applies where an object has a `names` attribute to identify its components. In this case a sub-vector of the names vector may be used in the same way as the positive integral labels in item 2 further above.
```
> fruit <- c(5, 10, 1, 20)
> names(fruit) <- c("orange", "banana", "apple", "peach")
> lunch <- fruit[c("apple","orange")]
```
The advantage is that alphanumeric *names* are often easier to remember than *numeric indices*. This option is particularly useful in connection with data frames, as we shall see later.
An indexed expression can also appear on the receiving end of an assignment, in which case the assignment operation is performed *only on those elements of the vector*. The expression must be of the form `vector[index\_vector]` as having an arbitrary expression in place of the vector name does not make much sense here.
For example
```
> x[is.na(x)] <- 0
```
replaces any missing values in `x` by zeros and
```
> y[y < 0] <- -y[y < 0]
```
has the same effect as
```
> y <- abs(y)
```
### 2.8 Other types of objects
Vectors are the most important type of object in R, but there are several others which we will meet more formally in later sections.
* *matrices* or more generally *arrays* are multi-dimensional generalizations of vectors. In fact, they *are* vectors that can be indexed by two or more indices and will be printed in special ways. See [Arrays and matrices](#Arrays-and-matrices).
* *factors* provide compact ways to handle categorical data. See [Factors](#Factors).
* *lists* are a general form of vector in which the various elements need not be of the same type, and are often themselves vectors or lists. Lists provide a convenient way to return the results of a statistical computation. See [Lists](#Lists).
* *data frames* are matrix-like structures, in which the columns can be of different types. Think of data frames as ‘data matrices’ with one row per observational unit but with (possibly) both numerical and categorical variables. Many experiments are best described by data frames: the treatments are categorical but the response is numeric. See [Data frames](#Data-frames).
* *functions* are themselves objects in R which can be stored in the project’s workspace. This provides a simple and convenient way to extend R. See [Writing your own functions](#Writing-your-own-functions).
3 Objects, their modes and attributes
-------------------------------------
### 3.1 Intrinsic attributes: mode and length
The entities R operates on are technically known as *objects*. Examples are vectors of numeric (real) or complex values, vectors of logical values and vectors of character strings. These are known as “atomic” structures since their components are all of the same type, or *mode*, namely *numeric*[10](#FOOT10), *complex*, *logical*, *character* and *raw*.
Vectors must have their values *all of the same mode*. Thus any given vector must be unambiguously either *logical*, *numeric*, *complex*, *character* or *raw*. (The only apparent exception to this rule is the special “value” listed as `NA` for quantities not available, but in fact there are several types of `NA`). Note that a vector can be empty and still have a mode. For example the empty character string vector is listed as `character(0)` and the empty numeric vector as `numeric(0)`.
R also operates on objects called *lists*, which are of mode *list*. These are ordered sequences of objects which individually can be of any mode. *lists* are known as “recursive” rather than atomic structures since their components can themselves be lists in their own right.
The other recursive structures are those of mode *function* and *expression*. Functions are the objects that form part of the R system along with similar user written functions, which we discuss in some detail later. Expressions as objects form an advanced part of R which will not be discussed in this guide, except indirectly when we discuss *formulae* used with modeling in R.
By the *mode* of an object we mean the basic type of its fundamental constituents. This is a special case of a “property” of an object. Another property of every object is its *length*. The functions `mode(object)` and `length(object)` can be used to find out the mode and length of any defined structure [11](#FOOT11).
Further properties of an object are usually provided by `attributes(object)`, see [Getting and setting attributes](#Getting-and-setting-attributes). Because of this, *mode* and *length* are also called “intrinsic attributes” of an object.
For example, if `z` is a complex vector of length 100, then in an expression `mode(z)` is the character string `"complex"` and `length(z)` is `100`.
R caters for changes of mode almost anywhere it could be considered sensible to do so, (and a few where it might not be). For example with
```
> z <- 0:9
```
we could put
```
> digits <- as.character(z)
```
after which `digits` is the character vector `c("0", "1", "2",
…, "9")`. A further *coercion*, or change of mode, reconstructs the numerical vector again:
```
> d <- as.integer(digits)
```
Now `d` and `z` are the same.[12](#FOOT12) There is a large collection of functions of the form `as.something()` for either coercion from one mode to another, or for investing an object with some other attribute it may not already possess. The reader should consult the different help files to become familiar with them.
### 3.2 Changing the length of an object
An “empty” object may still have a mode. For example
```
> e <- numeric()
```
makes `e` an empty vector structure of mode numeric. Similarly `character()` is a empty character vector, and so on. Once an object of any size has been created, new components may be added to it simply by giving it an index value outside its previous range. Thus
```
> e[3] <- 17
```
now makes `e` a vector of length 3, (the first two components of which are at this point both `NA`). This applies to any structure at all, provided the mode of the additional component(s) agrees with the mode of the object in the first place.
This automatic adjustment of lengths of an object is used often, for example in the `scan()` function for input. (see [The scan() function](#The-scan_0028_0029-function).)
Conversely to truncate the size of an object requires only an assignment to do so. Hence if `alpha` is an object of length 10, then
```
> alpha <- alpha[2 * 1:5]
```
makes it an object of length 5 consisting of just the former components with even index. (The old indices are not retained, of course.) We can then retain just the first three values by
```
> length(alpha) <- 3
```
and vectors can be extended (by missing values) in the same way.
### 3.3 Getting and setting attributes
The function `attributes(object)` returns a list of all the non-intrinsic attributes currently defined for that object. The function `attr(object, name)` can be used to select a specific attribute. These functions are rarely used, except in rather special circumstances when some new attribute is being created for some particular purpose, for example to associate a creation date or an operator with an R object. The concept, however, is very important.
Some care should be exercised when assigning or deleting attributes since they are an integral part of the object system used in R.
When it is used on the left hand side of an assignment it can be used either to associate a new attribute with `object` or to change an existing one. For example
```
> attr(z, "dim") <- c(10,10)
```
allows R to treat `z` as if it were a 10-by-10 matrix.
### 3.4 The class of an object
All objects in R have a *class*, reported by the function `class`. For simple vectors this is just the mode, for example `"numeric"`, `"logical"`, `"character"` or `"list"`, but `"matrix"`, `"array"`, `"factor"` and `"data.frame"` are other possible values.
A special attribute known as the *class* of the object is used to allow for an object-oriented style[13](#FOOT13) of programming in R. For example if an object has class `"data.frame"`, it will be printed in a certain way, the `plot()` function will display it graphically in a certain way, and other so-called generic functions such as `summary()` will react to it as an argument in a way sensitive to its class.
To remove temporarily the effects of class, use the function `unclass()`. For example if `winter` has the class `"data.frame"` then
```
> winter
```
will print it in data frame form, which is rather like a matrix, whereas
```
> unclass(winter)
```
will print it as an ordinary list. Only in rather special situations do you need to use this facility, but one is when you are learning to come to terms with the idea of class and generic functions.
Generic functions and classes will be discussed further in [Object orientation](#Object-orientation), but only briefly.
4 Ordered and unordered factors
-------------------------------
A *factor* is a vector object used to specify a discrete classification (grouping) of the components of other vectors of the same length. R provides both *ordered* and *unordered* factors. While the “real” application of factors is with model formulae (see [Contrasts](#Contrasts)), we here look at a specific example.
### 4.1 A specific example
Suppose, for example, we have a sample of 30 tax accountants from all the states and territories of Australia[14](#FOOT14) and their individual state of origin is specified by a character vector of state mnemonics as
```
> state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa",
"qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas",
"sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa",
"sa", "act", "nsw", "vic", "vic", "act")
```
Notice that in the case of a character vector, “sorted” means sorted in alphabetical order.
A *factor* is similarly created using the `factor()` function:
```
> statef <- factor(state)
```
The `print()` function handles factors slightly differently from other objects:
```
> statef
[1] tas sa qld nsw nsw nt wa wa qld vic nsw vic qld qld sa
[16] tas sa nt wa vic qld nsw nsw wa sa act nsw vic vic act
Levels: act nsw nt qld sa tas vic wa
```
To find out the levels of a factor the function `levels()` can be used.
```
> levels(statef)
[1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa"
```
### 4.2 The function `tapply()` and ragged arrays
To continue the previous example, suppose we have the incomes of the same tax accountants in another vector (in suitably large units of money)
```
> incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
59, 46, 58, 43)
```
To calculate the sample mean income for each state we can now use the special function `tapply()`:
```
> incmeans <- tapply(incomes, statef, mean)
```
giving a means vector with the components labelled by the levels
```
act nsw nt qld sa tas vic wa
44.500 57.333 55.500 53.600 55.000 60.500 56.000 52.250
```
The function `tapply()` is used to apply a function, here `mean()`, to each group of components of the first argument, here `incomes`, defined by the levels of the second component, here `statef`[15](#FOOT15), as if they were separate vector structures. The result is a structure of the same length as the levels attribute of the factor containing the results. The reader should consult the help document for more details.
Suppose further we needed to calculate the standard errors of the state income means. To do this we need to write an R function to calculate the standard error for any given vector. Since there is an builtin function `var()` to calculate the sample variance, such a function is a very simple one liner, specified by the assignment:
```
> stdError <- function(x) sqrt(var(x)/length(x))
```
(Writing functions will be considered later in [Writing your own functions](#Writing-your-own-functions). Note that R’s a builtin function `sd()` is something different.) After this assignment, the standard errors are calculated by
```
> incster <- tapply(incomes, statef, stdError)
```
and the values calculated are then
```
> incster
act nsw nt qld sa tas vic wa
1.5 4.3102 4.5 4.1061 2.7386 0.5 5.244 2.6575
```
As an exercise you may care to find the usual 95% confidence limits for the state mean incomes. To do this you could use `tapply()` once more with the `length()` function to find the sample sizes, and the `qt()` function to find the percentage points of the appropriate *t*-distributions. (You could also investigate R’s facilities for *t*-tests.)
The function `tapply()` can also be used to handle more complicated indexing of a vector by multiple categories. For example, we might wish to split the tax accountants by both state and sex. However in this simple instance (just one factor) what happens can be thought of as follows. The values in the vector are collected into groups corresponding to the distinct entries in the factor. The function is then applied to each of these groups individually. The value is a vector of function results, labelled by the `levels` attribute of the factor.
The combination of a vector and a labelling factor is an example of what is sometimes called a *ragged array*, since the subclass sizes are possibly irregular. When the subclass sizes are all the same the indexing may be done implicitly and much more efficiently, as we see in the next section.
### 4.3 Ordered factors
The levels of factors are stored in alphabetical order, or in the order they were specified to `factor` if they were specified explicitly.
Sometimes the levels will have a natural ordering that we want to record and want our statistical analysis to make use of. The `ordered()` function creates such ordered factors but is otherwise identical to `factor`. For most purposes the only difference between ordered and unordered factors is that the former are printed showing the ordering of the levels, but the contrasts generated for them in fitting linear models are different.
5 Arrays and matrices
---------------------
### 5.1 Arrays
An array can be considered as a multiply subscripted collection of data entries, for example numeric. R allows simple facilities for creating and handling arrays, and in particular the special case of matrices.
A dimension vector is a vector of non-negative integers. If its length is *k* then the array is *k*-dimensional, e.g. a matrix is a *2*-dimensional array. The dimensions are indexed from one up to the values given in the dimension vector.
A vector can be used by R as an array only if it has a dimension vector as its *dim* attribute. Suppose, for example, `z` is a vector of 1500 elements. The assignment
```
> dim(z) <- c(3,5,100)
```
gives it the *dim* attribute that allows it to be treated as a *3* by *5* by *100* array.
Other functions such as `matrix()` and `array()` are available for simpler and more natural looking assignments, as we shall see in [The array() function](#The-array_0028_0029-function).
The values in the data vector give the values in the array in the same order as they would occur in FORTRAN, that is “column major order,” with the first subscript moving fastest and the last subscript slowest.
For example if the dimension vector for an array, say `a`, is `c(3,4,2)` then there are 3 \* 4 \* 2 = 24 entries in `a` and the data vector holds them in the order `a[1,1,1], a[2,1,1], …, a[2,4,2], a[3,4,2]`.
Arrays can be one-dimensional: such arrays are usually treated in the same way as vectors (including when printing), but the exceptions can cause confusion.
### 5.2 Array indexing. Subsections of an array
Individual elements of an array may be referenced by giving the name of the array followed by the subscripts in square brackets, separated by commas.
More generally, subsections of an array may be specified by giving a sequence of *index vectors* in place of subscripts; however *if any index position is given an empty index vector, then the full range of that subscript is taken*.
Continuing the previous example, `a[2,,]` is a 4 \* 2 array with dimension vector `c(4,2)` and data vector containing the values
```
c(a[2,1,1], a[2,2,1], a[2,3,1], a[2,4,1],
a[2,1,2], a[2,2,2], a[2,3,2], a[2,4,2])
```
in that order. `a[,,]` stands for the entire array, which is the same as omitting the subscripts entirely and using `a` alone.
For any array, say `Z`, the dimension vector may be referenced explicitly as `dim(Z)` (on either side of an assignment).
Also, if an array name is given with just *one subscript or index vector*, then the corresponding values of the data vector only are used; in this case the dimension vector is ignored. This is not the case, however, if the single index is not a vector but itself an array, as we next discuss.
### 5.3 Index matrices
As well as an index vector in any subscript position, a matrix may be used with a single *index matrix* in order either to assign a vector of quantities to an irregular collection of elements in the array, or to extract an irregular collection as a vector.
A matrix example makes the process clear. In the case of a doubly indexed array, an index matrix may be given consisting of two columns and as many rows as desired. The entries in the index matrix are the row and column indices for the doubly indexed array. Suppose for example we have a *4* by *5* array `X` and we wish to do the following:
* Extract elements `X[1,3]`, `X[2,2]` and `X[3,1]` as a vector structure, and
* Replace these entries in the array `X` by zeroes.
In this case we need a *3* by *2* subscript array, as in the following example.
```
> x <- array(1:20, dim=c(4,5)) # Generate a 4 by 5 array.
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
> i <- array(c(1:3,3:1), dim=c(3,2))
> i # `i` is a 3 by 2 index array.
[,1] [,2]
[1,] 1 3
[2,] 2 2
[3,] 3 1
> x[i] # Extract those elements
[1] 9 6 3
> x[i] <- 0 # Replace those elements by zeros.
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 0 13 17
[2,] 2 0 10 14 18
[3,] 0 7 11 15 19
[4,] 4 8 12 16 20
>
```
Negative indices are not allowed in index matrices. `NA` and zero values are allowed: rows in the index matrix containing a zero are ignored, and rows containing an `NA` produce an `NA` in the result.
As a less trivial example, suppose we wish to generate an (unreduced) design matrix for a block design defined by factors `blocks` (`b` levels) and `varieties` (`v` levels). Further suppose there are `n` plots in the experiment. We could proceed as follows:
```
> Xb <- matrix(0, n, b)
> Xv <- matrix(0, n, v)
> ib <- cbind(1:n, blocks)
> iv <- cbind(1:n, varieties)
> Xb[ib] <- 1
> Xv[iv] <- 1
> X <- cbind(Xb, Xv)
```
To construct the incidence matrix, `N` say, we could use
```
> N <- crossprod(Xb, Xv)
```
However a simpler direct way of producing this matrix is to use `table()`:
```
> N <- table(blocks, varieties)
```
Index matrices must be numerical: any other form of matrix (e.g. a logical or character matrix) supplied as a matrix is treated as an indexing vector.
### 5.4 The `array()` function
As well as giving a vector structure a `dim` attribute, arrays can be constructed from vectors by the `array` function, which has the form
```
> Z <- array(data\_vector, dim\_vector)
```
For example, if the vector `h` contains 24 or fewer, numbers then the command
```
> Z <- array(h, dim=c(3,4,2))
```
would use `h` to set up *3* by *4* by *2* array in `Z`. If the size of `h` is exactly 24 the result is the same as
```
> Z <- h ; dim(Z) <- c(3,4,2)
```
However if `h` is shorter than 24, its values are recycled from the beginning again to make it up to size 24 (see [The recycling rule](#The-recycling-rule)) but `dim(h) <- c(3,4,2)` would signal an error about mismatching length. As an extreme but common example
```
> Z <- array(0, c(3,4,2))
```
makes `Z` an array of all zeros.
At this point `dim(Z)` stands for the dimension vector `c(3,4,2)`, and `Z[1:24]` stands for the data vector as it was in `h`, and `Z[]` with an empty subscript or `Z` with no subscript stands for the entire array as an array.
Arrays may be used in arithmetic expressions and the result is an array formed by element-by-element operations on the data vector. The `dim` attributes of operands generally need to be the same, and this becomes the dimension vector of the result. So if `A`, `B` and `C` are all similar arrays, then
```
> D <- 2*A*B + C + 1
```
makes `D` a similar array with its data vector being the result of the given element-by-element operations. However the precise rule concerning mixed array and vector calculations has to be considered a little more carefully.
#### 5.4.1 Mixed vector and array arithmetic. The recycling rule
The precise rule affecting element by element mixed calculations with vectors and arrays is somewhat quirky and hard to find in the references. From experience we have found the following to be a reliable guide.
* The expression is scanned from left to right.
* Any short vector operands are extended by recycling their values until they match the size of any other operands.
* As long as short vectors and arrays *only* are encountered, the arrays must all have the same `dim` attribute or an error results.
* Any vector operand longer than a matrix or array operand generates an error.
* If array structures are present and no error or coercion to vector has been precipitated, the result is an array structure with the common `dim` attribute of its array operands.
### 5.5 The outer product of two arrays
An important operation on arrays is the *outer product*. If `a` and `b` are two numeric arrays, their outer product is an array whose dimension vector is obtained by concatenating their two dimension vectors (order is important), and whose data vector is got by forming all possible products of elements of the data vector of `a` with those of `b`. The outer product is formed by the special operator `%o%`:
```
> ab <- a %o% b
```
An alternative is
```
> ab <- outer(a, b, "*")
```
The multiplication function can be replaced by an arbitrary function of two variables. For example if we wished to evaluate the function f(x; y) = cos(y)/(1 + x^2) over a regular grid of values with *x*- and *y*-coordinates defined by the R vectors `x` and `y` respectively, we could proceed as follows:
```
> f <- function(x, y) cos(y)/(1 + x^2)
> z <- outer(x, y, f)
```
In particular the outer product of two ordinary vectors is a doubly subscripted array (that is a matrix, of rank at most 1). Notice that the outer product operator is of course non-commutative. Defining your own R functions will be considered further in [Writing your own functions](#Writing-your-own-functions).
#### An example: Determinants of 2 by 2 single-digit matrices
As an artificial but cute example, consider the determinants of *2* by *2* matrices *[a, b; c, d]* where each entry is a non-negative integer in the range *0, 1, …, 9*, that is a digit.
The problem is to find the determinants, *ad - bc*, of all possible matrices of this form and represent the frequency with which each value occurs as a *high density* plot. This amounts to finding the probability distribution of the determinant if each digit is chosen independently and uniformly at random.
A neat way of doing this uses the `outer()` function twice:
```
> d <- outer(0:9, 0:9)
> fr <- table(outer(d, d, "-"))
> plot(fr, xlab="Determinant", ylab="Frequency")
```
Notice that `plot()` here uses a histogram like plot method, because it “sees” that `fr` is of class `"table"`. The “obvious” way of doing this problem with `for` loops, to be discussed in [Loops and conditional execution](#Loops-and-conditional-execution), is so inefficient as to be impractical.
It is also perhaps surprising that about 1 in 20 such matrices is singular.
### 5.6 Generalized transpose of an array
The function `aperm(a, perm)` may be used to permute an array, `a`. The argument `perm` must be a permutation of the integers *{1, …, k}*, where *k* is the number of subscripts in `a`. The result of the function is an array of the same size as `a` but with old dimension given by `perm[j]` becoming the new `j`-th dimension. The easiest way to think of this operation is as a generalization of transposition for matrices. Indeed if `A` is a matrix, (that is, a doubly subscripted array) then `B` given by
```
> B <- aperm(A, c(2,1))
```
is just the transpose of `A`. For this special case a simpler function `t()` is available, so we could have used `B <- t(A)`.
### 5.7 Matrix facilities
As noted above, a matrix is just an array with two subscripts. However it is such an important special case it needs a separate discussion. R contains many operators and functions that are available only for matrices. For example `t(X)` is the matrix transpose function, as noted above. The functions `nrow(A)` and `ncol(A)` give the number of rows and columns in the matrix `A` respectively.
#### 5.7.1 Matrix multiplication
The operator `%*%` is used for matrix multiplication. An *n* by *1* or *1* by *n* matrix may of course be used as an *n*-vector if in the context such is appropriate. Conversely, vectors which occur in matrix multiplication expressions are automatically promoted either to row or column vectors, whichever is multiplicatively coherent, if possible, (although this is not always unambiguously possible, as we see later).
If, for example, `A` and `B` are square matrices of the same size, then
```
> A * B
```
is the matrix of element by element products and
```
> A %*% B
```
is the matrix product. If `x` is a vector, then
```
> x %*% A %*% x
```
is a quadratic form.[16](#FOOT16)
The function `crossprod()` forms “crossproducts”, meaning that `crossprod(X, y)` is the same as `t(X) %*% y` but the operation is more efficient. If the second argument to `crossprod()` is omitted it is taken to be the same as the first.
The meaning of `diag()` depends on its argument. `diag(v)`, where `v` is a vector, gives a diagonal matrix with elements of the vector as the diagonal entries. On the other hand `diag(M)`, where `M` is a matrix, gives the vector of main diagonal entries of `M`. This is the same convention as that used for `diag()` in MATLAB. Also, somewhat confusingly, if `k` is a single numeric value then `diag(k)` is the `k` by `k` identity matrix!
#### 5.7.2 Linear equations and inversion
Solving linear equations is the inverse of matrix multiplication. When after
```
> b <- A %*% x
```
only `A` and `b` are given, the vector `x` is the solution of that linear equation system. In R,
```
> solve(A,b)
```
solves the system, returning `x` (up to some accuracy loss). Note that in linear algebra, formally `x = A^{-1} %*% b` where `A^{-1}` denotes the *inverse* of `A`, which can be computed by
```
solve(A)
```
but rarely is needed. Numerically, it is both inefficient and potentially unstable to compute `x <- solve(A) %*% b` instead of `solve(A,b)`.
The quadratic form `x %*% A^{-1} %*%
x` which is used in multivariate computations, should be computed by something like[17](#FOOT17) `x %*% solve(A,x)`, rather than computing the inverse of `A`.
#### 5.7.3 Eigenvalues and eigenvectors
The function `eigen(Sm)` calculates the eigenvalues and eigenvectors of a symmetric matrix `Sm`. The result of this function is a list of two components named `values` and `vectors`. The assignment
```
> ev <- eigen(Sm)
```
will assign this list to `ev`. Then `ev$val` is the vector of eigenvalues of `Sm` and `ev$vec` is the matrix of corresponding eigenvectors. Had we only needed the eigenvalues we could have used the assignment:
```
> evals <- eigen(Sm)$values
```
`evals` now holds the vector of eigenvalues and the second component is discarded. If the expression
```
> eigen(Sm)
```
is used by itself as a command the two components are printed, with their names. For large matrices it is better to avoid computing the eigenvectors if they are not needed by using the expression
```
> evals <- eigen(Sm, only.values = TRUE)$values
```
#### 5.7.4 Singular value decomposition and determinants
The function `svd(M)` takes an arbitrary matrix argument, `M`, and calculates the singular value decomposition of `M`. This consists of a matrix of orthonormal columns `U` with the same column space as `M`, a second matrix of orthonormal columns `V` whose column space is the row space of `M` and a diagonal matrix of positive entries `D` such that `M = U %*% D %*%
t(V)`. `D` is actually returned as a vector of the diagonal elements. The result of `svd(M)` is actually a list of three components named `d`, `u` and `v`, with evident meanings.
If `M` is in fact square, then, it is not hard to see that
```
> absdetM <- prod(svd(M)$d)
```
calculates the absolute value of the determinant of `M`. If this calculation were needed often with a variety of matrices it could be defined as an R function
```
> absdet <- function(M) prod(svd(M)$d)
```
after which we could use `absdet()` as just another R function. As a further trivial but potentially useful example, you might like to consider writing a function, say `tr()`, to calculate the trace of a square matrix. [Hint: You will not need to use an explicit loop. Look again at the `diag()` function.]
R has a builtin function `det` to calculate a determinant, including the sign, and another, `determinant`, to give the sign and modulus (optionally on log scale),
#### 5.7.5 Least squares fitting and the QR decomposition
The function `lsfit()` returns a list giving results of a least squares fitting procedure. An assignment such as
```
> ans <- lsfit(X, y)
```
gives the results of a least squares fit where `y` is the vector of observations and `X` is the design matrix. See the help facility for more details, and also for the follow-up function `ls.diag()` for, among other things, regression diagnostics. Note that a grand mean term is automatically included and need not be included explicitly as a column of `X`. Further note that you almost always will prefer using `lm(.)` (see [Linear models](#Linear-models)) to `lsfit()` for regression modelling.
Another closely related function is `qr()` and its allies. Consider the following assignments
```
> Xplus <- qr(X)
> b <- qr.coef(Xplus, y)
> fit <- qr.fitted(Xplus, y)
> res <- qr.resid(Xplus, y)
```
These compute the orthogonal projection of `y` onto the range of `X` in `fit`, the projection onto the orthogonal complement in `res` and the coefficient vector for the projection in `b`, that is, `b` is essentially the result of the MATLAB ‘backslash’ operator.
It is not assumed that `X` has full column rank. Redundancies will be discovered and removed as they are found.
This alternative is the older, low-level way to perform least squares calculations. Although still useful in some contexts, it would now generally be replaced by the statistical models features, as will be discussed in [Statistical models in R](#Statistical-models-in-R).
### 5.8 Forming partitioned matrices, `cbind()` and `rbind()`
As we have already seen informally, matrices can be built up from other vectors and matrices by the functions `cbind()` and `rbind()`. Roughly `cbind()` forms matrices by binding together matrices horizontally, or column-wise, and `rbind()` vertically, or row-wise.
In the assignment
```
> X <- cbind(arg\_1, arg\_2, arg\_3, …)
```
the arguments to `cbind()` must be either vectors of any length, or matrices with the same column size, that is the same number of rows. The result is a matrix with the concatenated arguments arg\_1, arg\_2, … forming the columns.
If some of the arguments to `cbind()` are vectors they may be shorter than the column size of any matrices present, in which case they are cyclically extended to match the matrix column size (or the length of the longest vector if no matrices are given).
The function `rbind()` does the corresponding operation for rows. In this case any vector argument, possibly cyclically extended, are of course taken as row vectors.
Suppose `X1` and `X2` have the same number of rows. To combine these by columns into a matrix `X`, together with an initial column of `1`s we can use
```
> X <- cbind(1, X1, X2)
```
The result of `rbind()` or `cbind()` always has matrix status. Hence `cbind(x)` and `rbind(x)` are possibly the simplest ways explicitly to allow the vector `x` to be treated as a column or row matrix respectively.
### 5.9 The concatenation function, `c()`, with arrays
It should be noted that whereas `cbind()` and `rbind()` are concatenation functions that respect `dim` attributes, the basic `c()` function does not, but rather clears numeric objects of all `dim` and `dimnames` attributes. This is occasionally useful in its own right.
The official way to coerce an array back to a simple vector object is to use `as.vector()`
```
> vec <- as.vector(X)
```
However a similar result can be achieved by using `c()` with just one argument, simply for this side-effect:
```
> vec <- c(X)
```
There are slight differences between the two, but ultimately the choice between them is largely a matter of style (with the former being preferable).
### 5.10 Frequency tables from factors
Recall that a factor defines a partition into groups. Similarly a pair of factors defines a two way cross classification, and so on. The function `table()` allows frequency tables to be calculated from equal length factors. If there are *k* factor arguments, the result is a *k*-way array of frequencies.
Suppose, for example, that `statef` is a factor giving the state code for each entry in a data vector. The assignment
```
> statefr <- table(statef)
```
gives in `statefr` a table of frequencies of each state in the sample. The frequencies are ordered and labelled by the `levels` attribute of the factor. This simple case is equivalent to, but more convenient than,
```
> statefr <- tapply(statef, statef, length)
```
Further suppose that `incomef` is a factor giving a suitably defined “income class” for each entry in the data vector, for example with the `cut()` function:
```
> factor(cut(incomes, breaks = 35+10*(0:7))) -> incomef
```
Then to calculate a two-way table of frequencies:
```
> table(incomef,statef)
statef
incomef act nsw nt qld sa tas vic wa
(35,45] 1 1 0 1 0 0 1 0
(45,55] 1 1 1 1 2 0 1 3
(55,65] 0 3 1 3 2 2 2 1
(65,75] 0 1 0 0 0 0 1 0
```
Extension to higher-way frequency tables is immediate.
6 Lists and data frames
-----------------------
### 6.1 Lists
An R *list* is an object consisting of an ordered collection of objects known as its *components*.
There is no particular need for the components to be of the same mode or type, and, for example, a list could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on. Here is a simple example of how to make a list:
```
> Lst <- list(name="Fred", wife="Mary", no.children=3,
child.ages=c(4,7,9))
```
Components are always *numbered* and may always be referred to as such. Thus if `Lst` is the name of a list with four components, these may be individually referred to as `Lst[[1]]`, `Lst[[2]]`, `Lst[[3]]` and `Lst[[4]]`. If, further, `Lst[[4]]` is a vector subscripted array then `Lst[[4]][1]` is its first entry.
If `Lst` is a list, then the function `length(Lst)` gives the number of (top level) components it has.
Components of lists may also be *named*, and in this case the component may be referred to either by giving the component name as a character string in place of the number in double square brackets, or, more conveniently, by giving an expression of the form
```
> name$component\_name
```
for the same thing.
This is a very useful convention as it makes it easier to get the right component if you forget the number.
So in the simple example given above:
`Lst$name` is the same as `Lst[[1]]` and is the string `"Fred"`,
`Lst$wife` is the same as `Lst[[2]]` and is the string `"Mary"`,
`Lst$child.ages[1]` is the same as `Lst[[4]][1]` and is the number `4`.
Additionally, one can also use the names of the list components in double square brackets, i.e., `Lst[["name"]]` is the same as `Lst$name`. This is especially useful, when the name of the component to be extracted is stored in another variable as in
```
> x <- "name"; Lst[[x]]
```
It is very important to distinguish `Lst[[1]]` from `Lst[1]`. ‘``[[…]]``’ is the operator used to select a single element, whereas ‘``[…]``’ is a general subscripting operator. Thus the former is the *first object in the list* `Lst`, and if it is a named list the name is *not* included. The latter is a *sublist of the list `Lst` consisting of the first entry only. If it is a named list, the names are transferred to the sublist.*
The names of components may be abbreviated down to the minimum number of letters needed to identify them uniquely. Thus `Lst$coefficients` may be minimally specified as `Lst$coe` and `Lst$covariance` as `Lst$cov`.
The vector of names is in fact simply an attribute of the list like any other and may be handled as such. Other structures besides lists may, of course, similarly be given a *names* attribute also.
### 6.2 Constructing and modifying lists
New lists may be formed from existing objects by the function `list()`. An assignment of the form
```
> Lst <- list(name\_1=object\_1, …, name\_m=object\_m)
```
sets up a list `Lst` of *m* components using object\_1, …, object\_m for the components and giving them names as specified by the argument names, (which can be freely chosen). If these names are omitted, the components are numbered only. The components used to form the list are *copied* when forming the new list and the originals are not affected.
Lists, like any subscripted object, can be extended by specifying additional components. For example
```
> Lst[5] <- list(matrix=Mat)
```
#### 6.2.1 Concatenating lists
When the concatenation function `c()` is given list arguments, the result is an object of mode list also, whose components are those of the argument lists joined together in sequence.
```
> list.ABC <- c(list.A, list.B, list.C)
```
Recall that with vector objects as arguments the concatenation function similarly joined together all arguments into a single vector structure. In this case all other attributes, such as `dim` attributes, are discarded.
### 6.3 Data frames
A *data frame* is a list with class `"data.frame"`. There are restrictions on lists that may be made into data frames, namely
* The components must be vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames.
* Matrices, lists, and data frames provide as many variables to the new data frame as they have columns, elements, or variables, respectively.
* Numeric vectors, logicals and factors are included as is, and by default[18](#FOOT18) character vectors are coerced to be factors, whose levels are the unique values appearing in the vector.
* Vector structures appearing as variables of the data frame must all have the *same length*, and matrix structures must all have the same *row size*.
A data frame may for many purposes be regarded as a matrix with columns possibly of differing modes and attributes. It may be displayed in matrix form, and its rows and columns extracted using matrix indexing conventions.
#### 6.3.1 Making data frames
Objects satisfying the restrictions placed on the columns (components) of a data frame may be used to form one using the function `data.frame`:
```
> accountants <- data.frame(home=statef, loot=incomes, shot=incomef)
```
A list whose components conform to the restrictions of a data frame may be *coerced* into a data frame using the function `as.data.frame()`
The simplest way to construct a data frame from scratch is to use the `read.table()` function to read an entire data frame from an external file. This is discussed further in [Reading data from files](#Reading-data-from-files).
#### 6.3.2 `attach()` and `detach()`
The `$` notation, such as `accountants$home`, for list components is not always very convenient. A useful facility would be somehow to make the components of a list or data frame temporarily visible as variables under their component name, without the need to quote the list name explicitly each time.
The `attach()` function takes a ‘database’ such as a list or data frame as its argument. Thus suppose `lentils` is a data frame with three variables `lentils$u`, `lentils$v`, `lentils$w`. The attach
```
> attach(lentils)
```
places the data frame in the search path at position 2, and provided there are no variables `u`, `v` or `w` in position 1, `u`, `v` and `w` are available as variables from the data frame in their own right. At this point an assignment such as
```
> u <- v+w
```
does not replace the component `u` of the data frame, but rather masks it with another variable `u` in the working directory at position 1 on the search path. To make a permanent change to the data frame itself, the simplest way is to resort once again to the `$` notation:
```
> lentils$u <- v+w
```
However the new value of component `u` is not visible until the data frame is detached and attached again.
To detach a data frame, use the function
```
> detach()
```
More precisely, this statement detaches from the search path the entity currently at position 2. Thus in the present context the variables `u`, `v` and `w` would be no longer visible, except under the list notation as `lentils$u` and so on. Entities at positions greater than 2 on the search path can be detached by giving their number to `detach`, but it is much safer to always use a name, for example by `detach(lentils)` or `detach("lentils")`
> **Note:** In R lists and data frames can only be attached at position 2 or above, and what is attached is a *copy* of the original object. You can alter the attached values *via* `assign`, but the original list or data frame is unchanged.
>
>
>
#### 6.3.3 Working with data frames
A useful convention that allows you to work with many different problems comfortably together in the same working directory is
* gather together all variables for any well defined and separate problem in a data frame under a suitably informative name;
* when working with a problem attach the appropriate data frame at position 2, and use the working directory at level 1 for operational quantities and temporary variables;
* before leaving a problem, add any variables you wish to keep for future reference to the data frame using the `$` form of assignment, and then `detach()`;
* finally remove all unwanted variables from the working directory and keep it as clean of left-over temporary variables as possible.
In this way it is quite simple to work with many problems in the same directory, all of which have variables named `x`, `y` and `z`, for example.
#### 6.3.4 Attaching arbitrary lists
`attach()` is a generic function that allows not only directories and data frames to be attached to the search path, but other classes of object as well. In particular any object of mode `"list"` may be attached in the same way:
```
> attach(any.old.list)
```
Anything that has been attached can be detached by `detach`, by position number or, preferably, by name.
#### 6.3.5 Managing the search path
The function `search` shows the current search path and so is a very useful way to keep track of which data frames and lists (and packages) have been attached and detached. Initially it gives
```
> search()
[1] ".GlobalEnv" "Autoloads" "package:base"
```
where `.GlobalEnv` is the workspace.[19](#FOOT19)
After `lentils` is attached we have
```
> search()
[1] ".GlobalEnv" "lentils" "Autoloads" "package:base"
> ls(2)
[1] "u" "v" "w"
```
and as we see `ls` (or `objects`) can be used to examine the contents of any position on the search path.
Finally, we detach the data frame and confirm it has been removed from the search path.
```
> detach("lentils")
> search()
[1] ".GlobalEnv" "Autoloads" "package:base"
```
7 Reading data from files
-------------------------
Large data objects will usually be read as values from external files rather than entered during an R session at the keyboard. R input facilities are simple and their requirements are fairly strict and even rather inflexible. There is a clear presumption by the designers of R that you will be able to modify your input files using other tools, such as file editors or Perl[20](#FOOT20) to fit in with the requirements of R. Generally this is very simple.
If variables are to be held mainly in data frames, as we strongly suggest they should be, an entire data frame can be read directly with the `read.table()` function. There is also a more primitive input function, `scan()`, that can be called directly.
For more details on importing data into R and also exporting data, see the *R Data Import/Export* manual.
### 7.1 The `read.table()` function
To read an entire data frame directly, the external file will normally have a special form.
* The first line of the file should have a *name* for each variable in the data frame.
* Each additional line of the file has as its first item a *row label* and the values for each variable.
If the file has one fewer item in its first line than in its second, this arrangement is presumed to be in force. So the first few lines of a file to be read as a data frame might look as follows.
By default numeric items (except row labels) are read as numeric variables and non-numeric variables, such as `Cent.heat` in the example, as factors. This can be changed if necessary.
The function `read.table()` can then be used to read the data frame directly
```
> HousePrice <- read.table("houses.data")
```
Often you will want to omit including the row labels directly and use the default labels. In this case the file may omit the row label column as in the following.
The data frame may then be read as
```
> HousePrice <- read.table("houses.data", header=TRUE)
```
where the `header=TRUE` option specifies that the first line is a line of headings, and hence, by implication from the form of the file, that no explicit row labels are given.
### 7.2 The `scan()` function
Suppose the data vectors are of equal length and are to be read in parallel. Further suppose that there are three vectors, the first of mode character and the remaining two of mode numeric, and the file is `input.dat`. The first step is to use `scan()` to read in the three vectors as a list, as follows
```
> inp <- scan("input.dat", list("",0,0))
```
The second argument is a dummy list structure that establishes the mode of the three vectors to be read. The result, held in `inp`, is a list whose components are the three vectors read in. To separate the data items into three separate vectors, use assignments like
```
> label <- inp[[1]]; x <- inp[[2]]; y <- inp[[3]]
```
More conveniently, the dummy list can have named components, in which case the names can be used to access the vectors read in. For example
```
> inp <- scan("input.dat", list(id="", x=0, y=0))
```
If you wish to access the variables separately they may either be re-assigned to variables in the working frame:
```
> label <- inp$id; x <- inp$x; y <- inp$y
```
or the list may be attached at position 2 of the search path (see [Attaching arbitrary lists](#Attaching-arbitrary-lists)).
If the second argument is a single value and not a list, a single vector is read in, all components of which must be of the same mode as the dummy value.
```
> X <- matrix(scan("light.dat", 0), ncol=5, byrow=TRUE)
```
There are more elaborate input facilities available and these are detailed in the manuals.
### 7.3 Accessing builtin datasets
Around 100 datasets are supplied with R (in package **datasets**), and others are available in packages (including the recommended packages supplied with R). To see the list of datasets currently available use
```
data()
```
All the datasets supplied with R are available directly by name. However, many packages still use the obsolete convention in which `data` was also used to load datasets into R, for example
```
data(infert)
```
and this can still be used with the standard packages (as in this example). In most cases this will load an R object of the same name. However, in a few cases it loads several objects, so see the on-line help for the object to see what to expect.
#### 7.3.1 Loading data from other R packages
To access data from a particular package, use the `package` argument, for example
```
data(package="rpart")
data(Puromycin, package="datasets")
```
If a package has been attached by `library`, its datasets are automatically included in the search.
User-contributed packages can be a rich source of datasets.
### 7.4 Editing data
When invoked on a data frame or matrix, `edit` brings up a separate spreadsheet-like environment for editing. This is useful for making small changes once a data set has been read. The command
```
> xnew <- edit(xold)
```
will allow you to edit your data set `xold`, and on completion the changed object is assigned to `xnew`. If you want to alter the original dataset `xold`, the simplest way is to use `fix(xold)`, which is equivalent to `xold <- edit(xold)`.
Use
```
> xnew <- edit(data.frame())
```
to enter new data via the spreadsheet interface.
8 Probability distributions
---------------------------
### 8.1 R as a set of statistical tables
One convenient use of R is to provide a comprehensive set of statistical tables. Functions are provided to evaluate the cumulative distribution function P(X <= x), the probability density function and the quantile function (given *q*, the smallest *x* such that P(X <= x) > q), and to simulate from the distribution.
Prefix the name given here by ‘`d`’ for the density, ‘`p`’ for the CDF, ‘`q`’ for the quantile function and ‘`r`’ for simulation (*r*andom deviates). The first argument is `x` for `dxxx`, `q` for `pxxx`, `p` for `qxxx` and `n` for `rxxx` (except for `rhyper`, `rsignrank` and `rwilcox`, for which it is `nn`). In not quite all cases is the non-centrality parameter `ncp` currently available: see the on-line help for details.
The `pxxx` and `qxxx` functions all have logical arguments `lower.tail` and `log.p` and the `dxxx` ones have `log`. This allows, e.g., getting the cumulative (or “integrated”) *hazard* function, H(t) = - log(1 - F(t)), by
```
- pxxx(t, ..., lower.tail = FALSE, log.p = TRUE)
```
or more accurate log-likelihoods (by `dxxx(..., log =
TRUE)`), directly.
In addition there are functions `ptukey` and `qtukey` for the distribution of the studentized range of samples from a normal distribution, and `dmultinom` and `rmultinom` for the multinomial distribution. Further distributions are available in contributed packages, notably [**SuppDists**](https://CRAN.R-project.org/package=SuppDists).
Here are some examples
```
> ## 2-tailed p-value for t distribution
> 2*pt(-2.43, df = 13)
> ## upper 1% point for an F(2, 7) distribution
> qf(0.01, 2, 7, lower.tail = FALSE)
```
See the on-line help on `RNG` for how random-number generation is done in R.
### 8.2 Examining the distribution of a set of data
Given a (univariate) set of data we can examine its distribution in a large number of ways. The simplest is to examine the numbers. Two slightly different summaries are given by `summary` and `fivenum` and a display of the numbers by `stem` (a “stem and leaf” plot).
```
> attach(faithful)
> summary(eruptions)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.600 2.163 4.000 3.488 4.454 5.100
> fivenum(eruptions)
[1] 1.6000 2.1585 4.0000 4.4585 5.1000
> stem(eruptions)
The decimal point is 1 digit(s) to the left of the |
16 | 070355555588
18 | 000022233333335577777777888822335777888
20 | 00002223378800035778
22 | 0002335578023578
24 | 00228
26 | 23
28 | 080
30 | 7
32 | 2337
34 | 250077
36 | 0000823577
38 | 2333335582225577
40 | 0000003357788888002233555577778
42 | 03335555778800233333555577778
44 | 02222335557780000000023333357778888
46 | 0000233357700000023578
48 | 00000022335800333
50 | 0370
```
A stem-and-leaf plot is like a histogram, and R has a function `hist` to plot histograms.
```
> hist(eruptions)
## make the bins smaller, make a plot of density
> hist(eruptions, seq(1.6, 5.2, 0.2), prob=TRUE)
> lines(density(eruptions, bw=0.1))
> rug(eruptions) # show the actual data points
```
More elegant density plots can be made by `density`, and we added a line produced by `density` in this example. The bandwidth `bw` was chosen by trial-and-error as the default gives too much smoothing (it usually does for “interesting” densities). (Better automated methods of bandwidth choice are available, and in this example `bw = "SJ"` gives a good result.)
We can plot the empirical cumulative distribution function by using the function `ecdf`.
```
> plot(ecdf(eruptions), do.points=FALSE, verticals=TRUE)
```
This distribution is obviously far from any standard distribution. How about the right-hand mode, say eruptions of longer than 3 minutes? Let us fit a normal distribution and overlay the fitted CDF.
```
> long <- eruptions[eruptions > 3]
> plot(ecdf(long), do.points=FALSE, verticals=TRUE)
> x <- seq(3, 5.4, 0.01)
> lines(x, pnorm(x, mean=mean(long), sd=sqrt(var(long))), lty=3)
```
Quantile-quantile (Q-Q) plots can help us examine this more carefully.
```
par(pty="s") # arrange for a square figure region
qqnorm(long); qqline(long)
```
which shows a reasonable fit but a shorter right tail than one would expect from a normal distribution. Let us compare this with some simulated data from a *t* distribution
```
x <- rt(250, df = 5)
qqnorm(x); qqline(x)
```
which will usually (if it is a random sample) show longer tails than expected for a normal. We can make a Q-Q plot against the generating distribution by
```
qqplot(qt(ppoints(250), df = 5), x, xlab = "Q-Q plot for t dsn")
qqline(x)
```
Finally, we might want a more formal test of agreement with normality (or not). R provides the Shapiro-Wilk test
```
> shapiro.test(long)
Shapiro-Wilk normality test
data: long
W = 0.9793, p-value = 0.01052
```
and the Kolmogorov-Smirnov test
```
> ks.test(long, "pnorm", mean = mean(long), sd = sqrt(var(long)))
One-sample Kolmogorov-Smirnov test
data: long
D = 0.0661, p-value = 0.4284
alternative hypothesis: two.sided
```
(Note that the distribution theory is not valid here as we have estimated the parameters of the normal distribution from the same sample.)
### 8.3 One- and two-sample tests
So far we have compared a single sample to a normal distribution. A much more common operation is to compare aspects of two samples. Note that in R, all “classical” tests including the ones used below are in package **stats** which is normally loaded.
Consider the following sets of data on the latent heat of the fusion of ice (*cal/gm*) from Rice (1995, p.490)
```
Method A: 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97
80.05 80.03 80.02 80.00 80.02
Method B: 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97
```
Boxplots provide a simple graphical comparison of the two samples.
```
A <- scan()
79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97
80.05 80.03 80.02 80.00 80.02
B <- scan()
80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97
boxplot(A, B)
```
which indicates that the first group tends to give higher results than the second.
To test for the equality of the means of the two examples, we can use an *unpaired* *t*-test by
```
> t.test(A, B)
Welch Two Sample t-test
data: A and B
t = 3.2499, df = 12.027, p-value = 0.00694
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.01385526 0.07018320
sample estimates:
mean of x mean of y
80.02077 79.97875
```
which does indicate a significant difference, assuming normality. By default the R function does not assume equality of variances in the two samples (in contrast to the similar S-PLUS `t.test` function). We can use the F test to test for equality in the variances, provided that the two samples are from normal populations.
```
> var.test(A, B)
F test to compare two variances
data: A and B
F = 0.5837, num df = 12, denom df = 7, p-value = 0.3938
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
0.1251097 2.1052687
sample estimates:
ratio of variances
0.5837405
```
which shows no evidence of a significant difference, and so we can use the classical *t*-test that assumes equality of the variances.
```
> t.test(A, B, var.equal=TRUE)
Two Sample t-test
data: A and B
t = 3.4722, df = 19, p-value = 0.002551
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.01669058 0.06734788
sample estimates:
mean of x mean of y
80.02077 79.97875
```
All these tests assume normality of the two samples. The two-sample Wilcoxon (or Mann-Whitney) test only assumes a common continuous distribution under the null hypothesis.
```
> wilcox.test(A, B)
Wilcoxon rank sum test with continuity correction
data: A and B
W = 89, p-value = 0.007497
alternative hypothesis: true location shift is not equal to 0
Warning message:
Cannot compute exact p-value with ties in: wilcox.test(A, B)
```
Note the warning: there are several ties in each sample, which suggests strongly that these data are from a discrete distribution (probably due to rounding).
There are several ways to compare graphically the two samples. We have already seen a pair of boxplots. The following
```
> plot(ecdf(A), do.points=FALSE, verticals=TRUE, xlim=range(A, B))
> plot(ecdf(B), do.points=FALSE, verticals=TRUE, add=TRUE)
```
will show the two empirical CDFs, and `qqplot` will perform a Q-Q plot of the two samples. The Kolmogorov-Smirnov test is of the maximal vertical distance between the two ecdf’s, assuming a common continuous distribution:
```
> ks.test(A, B)
Two-sample Kolmogorov-Smirnov test
data: A and B
D = 0.5962, p-value = 0.05919
alternative hypothesis: two-sided
Warning message:
cannot compute correct p-values with ties in: ks.test(A, B)
```
9 Grouping, loops and conditional execution
-------------------------------------------
### 9.1 Grouped expressions
R is an expression language in the sense that its only command type is a function or expression which returns a result. Even an assignment is an expression whose result is the value assigned, and it may be used wherever any expression may be used; in particular multiple assignments are possible.
Commands may be grouped together in braces, `{expr\_1;
…; expr\_m}`, in which case the value of the group is the result of the last expression in the group evaluated. Since such a group is also an expression it may, for example, be itself included in parentheses and used as part of an even larger expression, and so on.
### 9.2 Control statements
#### 9.2.1 Conditional execution: `if` statements
The language has available a conditional construction of the form
```
> if (expr\_1) expr\_2 else expr\_3
```
where expr\_1 must evaluate to a single logical value and the result of the entire expression is then evident.
The “short-circuit” operators `&&` and `||` are often used as part of the condition in an `if` statement. Whereas `&` and `|` apply element-wise to vectors, `&&` and `||` apply to vectors of length one, and only evaluate their second argument if necessary.
There is a vectorized version of the `if`/`else` construct, the `ifelse` function. This has the form `ifelse(condition, a,
b)` and returns a vector of the same length as `condition`, with elements `a[i]` if `condition[i]` is true, otherwise `b[i]` (where `a` and `b` are recycled as necessary).
#### 9.2.2 Repetitive execution: `for` loops, `repeat` and `while`
There is also a `for` loop construction which has the form
```
> for (name in expr\_1) expr\_2
```
where `name` is the loop variable. expr\_1 is a vector expression, (often a sequence like `1:20`), and expr\_2 is often a grouped expression with its sub-expressions written in terms of the dummy *name*. expr\_2 is repeatedly evaluated as name ranges through the values in the vector result of expr\_1.
As an example, suppose `ind` is a vector of class indicators and we wish to produce separate plots of `y` versus `x` within classes. One possibility here is to use `coplot()`,[21](#FOOT21) which will produce an array of plots corresponding to each level of the factor. Another way to do this, now putting all plots on the one display, is as follows:
```
> xc <- split(x, ind)
> yc <- split(y, ind)
> for (i in 1:length(yc)) {
plot(xc[[i]], yc[[i]])
abline(lsfit(xc[[i]], yc[[i]]))
}
```
(Note the function `split()` which produces a list of vectors obtained by splitting a larger vector according to the classes specified by a factor. This is a useful function, mostly used in connection with boxplots. See the `help` facility for further details.)
> **Warning**: `for()` loops are used in R code much less often than in compiled languages. Code that takes a ‘whole object’ view is likely to be both clearer and faster in R.
>
>
>
Other looping facilities include the
```
> repeat expr
```
statement and the
```
> while (condition) expr
```
statement.
The `break` statement can be used to terminate any loop, possibly abnormally. This is the only way to terminate `repeat` loops.
The `next` statement can be used to discontinue one particular cycle and skip to the “next”.
Control statements are most often used in connection with *functions* which are discussed in [Writing your own functions](#Writing-your-own-functions), and where more examples will emerge.
10 Writing your own functions
-----------------------------
As we have seen informally along the way, the R language allows the user to create objects of mode *function*. These are true R functions that are stored in a special internal form and may be used in further expressions and so on. In the process, the language gains enormously in power, convenience and elegance, and learning to write useful functions is one of the main ways to make your use of R comfortable and productive.
It should be emphasized that most of the functions supplied as part of the R system, such as `mean()`, `var()`, `postscript()` and so on, are themselves written in R and thus do not differ materially from user written functions.
A function is defined by an assignment of the form
```
> name <- function(arg\_1, arg\_2, …) expression
```
The expression is an R expression, (usually a grouped expression), that uses the arguments, arg\_i, to calculate a value. The value of the expression is the value returned for the function.
A call to the function then usually takes the form `name(expr\_1, expr\_2, …)` and may occur anywhere a function call is legitimate.
### 10.1 Simple examples
As a first example, consider a function to calculate the two sample *t*-statistic, showing “all the steps”. This is an artificial example, of course, since there are other, simpler ways of achieving the same end.
The function is defined as follows:
```
> twosam <- function(y1, y2) {
n1 <- length(y1); n2 <- length(y2)
yb1 <- mean(y1); yb2 <- mean(y2)
s1 <- var(y1); s2 <- var(y2)
s <- ((n1-1)*s1 + (n2-1)*s2)/(n1+n2-2)
tst <- (yb1 - yb2)/sqrt(s*(1/n1 + 1/n2))
tst
}
```
With this function defined, you could perform two sample *t*-tests using a call such as
```
> tstat <- twosam(data$male, data$female); tstat
```
As a second example, consider a function to emulate directly the MATLAB backslash command, which returns the coefficients of the orthogonal projection of the vector *y* onto the column space of the matrix, *X*. (This is ordinarily called the least squares estimate of the regression coefficients.) This would ordinarily be done with the `qr()` function; however this is sometimes a bit tricky to use directly and it pays to have a simple function such as the following to use it safely.
Thus given a *n* by *1* vector *y* and an *n* by *p* matrix *X* then *X \ y* is defined as (X’X)^{-}X’y, where (X’X)^{-} is a generalized inverse of *X'X*.
```
> bslash <- function(X, y) {
X <- qr(X)
qr.coef(X, y)
}
```
After this object is created it may be used in statements such as
```
> regcoeff <- bslash(Xmat, yvar)
```
and so on.
The classical R function `lsfit()` does this job quite well, and more[22](#FOOT22). It in turn uses the functions `qr()` and `qr.coef()` in the slightly counterintuitive way above to do this part of the calculation. Hence there is probably some value in having just this part isolated in a simple to use function if it is going to be in frequent use. If so, we may wish to make it a matrix binary operator for even more convenient use.
### 10.2 Defining new binary operators
Had we given the `bslash()` function a different name, namely one of the form
```
%anything%
```
it could have been used as a *binary operator* in expressions rather than in function form. Suppose, for example, we choose `!` for the internal character. The function definition would then start as
```
> "%!%" <- function(X, y) { … }
```
(Note the use of quote marks.) The function could then be used as `X %!% y`. (The backslash symbol itself is not a convenient choice as it presents special problems in this context.)
The matrix multiplication operator, `%*%`, and the outer product matrix operator `%o%` are other examples of binary operators defined in this way.
### 10.3 Named arguments and defaults
As first noted in [Generating regular sequences](#Generating-regular-sequences), if arguments to called functions are given in the “`name=object`” form, they may be given in any order. Furthermore the argument sequence may begin in the unnamed, positional form, and specify named arguments after the positional arguments.
Thus if there is a function `fun1` defined by
```
> fun1 <- function(data, data.frame, graph, limit) {
[function body omitted]
}
```
then the function may be invoked in several ways, for example
```
> ans <- fun1(d, df, TRUE, 20)
> ans <- fun1(d, df, graph=TRUE, limit=20)
> ans <- fun1(data=d, limit=20, graph=TRUE, data.frame=df)
```
are all equivalent.
In many cases arguments can be given commonly appropriate default values, in which case they may be omitted altogether from the call when the defaults are appropriate. For example, if `fun1` were defined as
```
> fun1 <- function(data, data.frame, graph=TRUE, limit=20) { … }
```
it could be called as
```
> ans <- fun1(d, df)
```
which is now equivalent to the three cases above, or as
```
> ans <- fun1(d, df, limit=10)
```
which changes one of the defaults.
It is important to note that defaults may be arbitrary expressions, even involving other arguments to the same function; they are not restricted to be constants as in our simple example here.
### 10.4 The ‘`…`’ argument
Another frequent requirement is to allow one function to pass on argument settings to another. For example many graphics functions use the function `par()` and functions like `plot()` allow the user to pass on graphical parameters to `par()` to control the graphical output. (See [The par() function](#The-par_0028_0029-function), for more details on the `par()` function.) This can be done by including an extra argument, literally ‘`…`’, of the function, which may then be passed on. An outline example is given below.
```
fun1 <- function(data, data.frame, graph=TRUE, limit=20, ...) {
[omitted statements]
if (graph)
par(pch="*", ...)
[more omissions]
}
```
Less frequently, a function will need to refer to components of ‘`…`’. The expression `list(...)` evaluates all such arguments and returns them in a named list, while `..1`, `..2`, etc. evaluate them one at a time, with ‘`..n`’ returning the n’th unmatched argument.
### 10.5 Assignments within functions
Note that *any ordinary assignments done within the function are local and temporary and are lost after exit from the function*. Thus the assignment `X <- qr(X)` does not affect the value of the argument in the calling program.
To understand completely the rules governing the scope of R assignments the reader needs to be familiar with the notion of an evaluation *frame*. This is a somewhat advanced, though hardly difficult, topic and is not covered further here.
If global and permanent assignments are intended within a function, then either the “superassignment” operator, `<<-` or the function `assign()` can be used. See the `help` document for details. S-PLUS users should be aware that `<<-` has different semantics in R. These are discussed further in [Scope](#Scope).
### 10.6 More advanced examples
#### 10.6.1 Efficiency factors in block designs
As a more complete, if a little pedestrian, example of a function, consider finding the efficiency factors for a block design. (Some aspects of this problem have already been discussed in [Index matrices](#Index-matrices).)
A block design is defined by two factors, say `blocks` (`b` levels) and `varieties` (`v` levels). If *R* and *K* are the *v* by *v* and *b* by *b* *replications* and *block size* matrices, respectively, and *N* is the *b* by *v* incidence matrix, then the efficiency factors are defined as the eigenvalues of the matrix E = I\_v - R^{-1/2}N’K^{-1}NR^{-1/2} = I\_v - A’A, where A = K^{-1/2}NR^{-1/2}. One way to write the function is given below.
```
> bdeff <- function(blocks, varieties) {
blocks <- as.factor(blocks) # minor safety move
b <- length(levels(blocks))
varieties <- as.factor(varieties) # minor safety move
v <- length(levels(varieties))
K <- as.vector(table(blocks)) # remove dim attr
R <- as.vector(table(varieties)) # remove dim attr
N <- table(blocks, varieties)
A <- 1/sqrt(K) * N * rep(1/sqrt(R), rep(b, v))
sv <- svd(A)
list(eff=1 - sv$d^2, blockcv=sv$u, varietycv=sv$v)
}
```
It is numerically slightly better to work with the singular value decomposition on this occasion rather than the eigenvalue routines.
The result of the function is a list giving not only the efficiency factors as the first component, but also the block and variety canonical contrasts, since sometimes these give additional useful qualitative information.
#### 10.6.2 Dropping all names in a printed array
For printing purposes with large matrices or arrays, it is often useful to print them in close block form without the array names or numbers. Removing the `dimnames` attribute will not achieve this effect, but rather the array must be given a `dimnames` attribute consisting of empty strings. For example to print a matrix, `X`
```
> temp <- X
> dimnames(temp) <- list(rep("", nrow(X)), rep("", ncol(X)))
> temp; rm(temp)
```
This can be much more conveniently done using a function, `no.dimnames()`, shown below, as a “wrap around” to achieve the same result. It also illustrates how some effective and useful user functions can be quite short.
```
no.dimnames <- function(a) {
## Remove all dimension names from an array for compact printing.
d <- list()
l <- 0
for(i in dim(a)) {
d[[l <- l + 1]] <- rep("", i)
}
dimnames(a) <- d
a
}
```
With this function defined, an array may be printed in close format using
```
> no.dimnames(X)
```
This is particularly useful for large integer arrays, where patterns are the real interest rather than the values.
#### 10.6.3 Recursive numerical integration
Functions may be recursive, and may themselves define functions within themselves. Note, however, that such functions, or indeed variables, are not inherited by called functions in higher evaluation frames as they would be if they were on the search path.
The example below shows a naive way of performing one-dimensional numerical integration. The integrand is evaluated at the end points of the range and in the middle. If the one-panel trapezium rule answer is close enough to the two panel, then the latter is returned as the value. Otherwise the same process is recursively applied to each panel. The result is an adaptive integration process that concentrates function evaluations in regions where the integrand is farthest from linear. There is, however, a heavy overhead, and the function is only competitive with other algorithms when the integrand is both smooth and very difficult to evaluate.
The example is also given partly as a little puzzle in R programming.
```
area <- function(f, a, b, eps = 1.0e-06, lim = 10) {
fun1 <- function(f, a, b, fa, fb, a0, eps, lim, fun) {
## function ‘fun1’ is only visible inside ‘area’
d <- (a + b)/2
h <- (b - a)/4
fd <- f(d)
a1 <- h * (fa + fd)
a2 <- h * (fd + fb)
if(abs(a0 - a1 - a2) < eps || lim == 0)
return(a1 + a2)
else {
return(fun(f, a, d, fa, fd, a1, eps, lim - 1, fun) +
fun(f, d, b, fd, fb, a2, eps, lim - 1, fun))
}
}
fa <- f(a)
fb <- f(b)
a0 <- ((fa + fb) * (b - a))/2
fun1(f, a, b, fa, fb, a0, eps, lim, fun1)
}
```
### 10.7 Scope
The discussion in this section is somewhat more technical than in other parts of this document. However, it details one of the major differences between S-PLUS and R.
The symbols which occur in the body of a function can be divided into three classes; formal parameters, local variables and free variables. The formal parameters of a function are those occurring in the argument list of the function. Their values are determined by the process of *binding* the actual function arguments to the formal parameters. Local variables are those whose values are determined by the evaluation of expressions in the body of the functions. Variables which are not formal parameters or local variables are called free variables. Free variables become local variables if they are assigned to. Consider the following function definition.
```
f <- function(x) {
y <- 2*x
print(x)
print(y)
print(z)
}
```
In this function, `x` is a formal parameter, `y` is a local variable and `z` is a free variable.
In R the free variable bindings are resolved by first looking in the environment in which the function was created. This is called *lexical scope*. First we define a function called `cube`.
```
cube <- function(n) {
sq <- function() n*n
n*sq()
}
```
The variable `n` in the function `sq` is not an argument to that function. Therefore it is a free variable and the scoping rules must be used to ascertain the value that is to be associated with it. Under static scope (S-PLUS) the value is that associated with a global variable named `n`. Under lexical scope (R) it is the parameter to the function `cube` since that is the active binding for the variable `n` at the time the function `sq` was defined. The difference between evaluation in R and evaluation in S-PLUS is that S-PLUS looks for a global variable called `n` while R first looks for a variable called `n` in the environment created when `cube` was invoked.
```
## first evaluation in S
S> cube(2)
Error in sq(): Object "n" not found
Dumped
S> n <- 3
S> cube(2)
[1] 18
## then the same function evaluated in R
R> cube(2)
[1] 8
```
Lexical scope can also be used to give functions *mutable state*. In the following example we show how R can be used to mimic a bank account. A functioning bank account needs to have a balance or total, a function for making withdrawals, a function for making deposits and a function for stating the current balance. We achieve this by creating the three functions within `account` and then returning a list containing them. When `account` is invoked it takes a numerical argument `total` and returns a list containing the three functions. Because these functions are defined in an environment which contains `total`, they will have access to its value.
The special assignment operator, `<<-`, is used to change the value associated with `total`. This operator looks back in enclosing environments for an environment that contains the symbol `total` and when it finds such an environment it replaces the value, in that environment, with the value of right hand side. If the global or top-level environment is reached without finding the symbol `total` then that variable is created and assigned to there. For most users `<<-` creates a global variable and assigns the value of the right hand side to it[23](#FOOT23). Only when `<<-` has been used in a function that was returned as the value of another function will the special behavior described here occur.
```
open.account <- function(total) {
list(
deposit = function(amount) {
if(amount <= 0)
stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
},
withdraw = function(amount) {
if(amount > total)
stop("You don't have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
},
balance = function() {
cat("Your balance is", total, "\n\n")
}
)
}
ross <- open.account(100)
robert <- open.account(200)
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
```
### 10.8 Customizing the environment
Users can customize their environment in several different ways. There is a site initialization file and every directory can have its own special initialization file. Finally, the special functions `.First` and `.Last` can be used.
The location of the site initialization file is taken from the value of the `R_PROFILE` environment variable. If that variable is unset, the file `Rprofile.site` in the R home subdirectory `etc` is used. This file should contain the commands that you want to execute every time R is started under your system. A second, personal, profile file named `.Rprofile`[24](#FOOT24) can be placed in any directory. If R is invoked in that directory then that file will be sourced. This file gives individual users control over their workspace and allows for different startup procedures in different working directories. If no `.Rprofile` file is found in the startup directory, then R looks for a `.Rprofile` file in the user’s home directory and uses that (if it exists). If the environment variable `R_PROFILE_USER` is set, the file it points to is used instead of the `.Rprofile` files.
Any function named `.First()` in either of the two profile files or in the `.RData` image has a special status. It is automatically performed at the beginning of an R session and may be used to initialize the environment. For example, the definition in the example below alters the prompt to `$` and sets up various other useful things that can then be taken for granted in the rest of the session.
Thus, the sequence in which files are executed is, `Rprofile.site`, the user profile, `.RData` and then `.First()`. A definition in later files will mask definitions in earlier files.
```
> .First <- function() {
options(prompt="$ ", continue="+\t") # `$` is the prompt
options(digits=5, length=999) # custom numbers and printout
x11() # for graphics
par(pch = "+") # plotting character
source(file.path(Sys.getenv("HOME"), "R", "mystuff.R"))
# my personal functions
library(MASS) # attach a package
}
```
Similarly a function `.Last()`, if defined, is (normally) executed at the very end of the session. An example is given below.
```
> .Last <- function() {
graphics.off() # a small safety measure.
cat(paste(date(),"\nAdios\n")) # Is it time for lunch?
}
```
### 10.9 Classes, generic functions and object orientation
The class of an object determines how it will be treated by what are known as *generic* functions. Put the other way round, a generic function performs a task or action on its arguments *specific to the class of the argument itself*. If the argument lacks any `class` attribute, or has a class not catered for specifically by the generic function in question, there is always a *default action* provided.
An example makes things clearer. The class mechanism offers the user the facility of designing and writing generic functions for special purposes. Among the other generic functions are `plot()` for displaying objects graphically, `summary()` for summarizing analyses of various types, and `anova()` for comparing statistical models.
The number of generic functions that can treat a class in a specific way can be quite large. For example, the functions that can accommodate in some fashion objects of class `"data.frame"` include
```
[ [[<- any as.matrix
[<- mean plot summary
```
A currently complete list can be got by using the `methods()` function:
```
> methods(class="data.frame")
```
Conversely the number of classes a generic function can handle can also be quite large. For example the `plot()` function has a default method and variants for objects of classes `"data.frame"`, `"density"`, `"factor"`, and more. A complete list can be got again by using the `methods()` function:
```
> methods(plot)
```
For many generic functions the function body is quite short, for example
```
> coef
function (object, ...)
UseMethod("coef")
```
The presence of `UseMethod` indicates this is a generic function. To see what methods are available we can use `methods()`
```
> methods(coef)
[1] coef.aov* coef.Arima* coef.default* coef.listof*
[5] coef.nls* coef.summary.nls*
Non-visible functions are asterisked
```
In this example there are six methods, none of which can be seen by typing its name. We can read these by either of
```
> getAnywhere("coef.aov")
A single object matching ‘coef.aov’ was found
It was found in the following places
registered S3 method for coef from namespace stats
namespace:stats
with value
function (object, ...)
{
z <- object$coef
z[!is.na(z)]
}
> getS3method("coef", "aov")
function (object, ...)
{
z <- object$coef
z[!is.na(z)]
}
```
A function named `gen.cl` will be invoked by the generic `gen` for class `cl`, so do not name functions in this style unless they are intended to be methods.
The reader is referred to the *R Language Definition* for a more complete discussion of this mechanism.
11 Statistical models in R
--------------------------
This section presumes the reader has some familiarity with statistical methodology, in particular with regression analysis and the analysis of variance. Later we make some rather more ambitious presumptions, namely that something is known about generalized linear models and nonlinear regression.
The requirements for fitting statistical models are sufficiently well defined to make it possible to construct general tools that apply in a broad spectrum of problems.
R provides an interlocking suite of facilities that make fitting statistical models very simple. As we mention in the introduction, the basic output is minimal, and one needs to ask for the details by calling extractor functions.
### 11.1 Defining statistical models; formulae
The template for a statistical model is a linear regression model with independent, homoscedastic errors
```
y_i = sum_{j=0}^p beta_j x_{ij} + e_i, i = 1, …, n,
```
where the e\_i are NID(0, sigma^2). In matrix terms this would be written
```
y = X beta + e
```
where the *y* is the response vector, *X* is the *model matrix* or *design matrix* and has columns *x\_0, x\_1, …, x\_p*, the determining variables. Very often *x\_0* will be a column of ones defining an *intercept* term.
#### Examples
Before giving a formal specification, a few examples may usefully set the picture.
Suppose `y`, `x`, `x0`, `x1`, `x2`, … are numeric variables, `X` is a matrix and `A`, `B`, `C`, … are factors. The following formulae on the left side below specify statistical models as described on the right.
`y ~ x` `y ~ 1 + x`
Both imply the same simple linear regression model of *y* on *x*. The first has an implicit intercept term, and the second an explicit one.
`y ~ 0 + x` `y ~ -1 + x` `y ~ x - 1`
Simple linear regression of *y* on *x* through the origin (that is, without an intercept term).
`log(y) ~ x1 + x2`
Multiple regression of the transformed variable, log(y), on *x1* and *x2* (with an implicit intercept term).
`y ~ poly(x,2)` `y ~ 1 + x + I(x^2)`
Polynomial regression of *y* on *x* of degree 2. The first form uses orthogonal polynomials, and the second uses explicit powers, as basis.
`y ~ X + poly(x,2)`
Multiple regression *y* with model matrix consisting of the matrix *X* as well as polynomial terms in *x* to degree 2.
`y ~ A`
Single classification analysis of variance model of *y*, with classes determined by *A*.
`y ~ A + x`
Single classification analysis of covariance model of *y*, with classes determined by *A*, and with covariate *x*.
`y ~ A*B` `y ~ A + B + A:B` `y ~ B %in% A` `y ~ A/B`
Two factor non-additive model of *y* on *A* and *B*. The first two specify the same crossed classification and the second two specify the same nested classification. In abstract terms all four specify the same model subspace.
`y ~ (A + B + C)^2` `y ~ A*B*C - A:B:C`
Three factor experiment but with a model containing main effects and two factor interactions only. Both formulae specify the same model.
`y ~ A * x` `y ~ A/x` `y ~ A/(1 + x) - 1`
Separate simple linear regression models of *y* on *x* within the levels of *A*, with different codings. The last form produces explicit estimates of as many different intercepts and slopes as there are levels in *A*.
`y ~ A*B + Error(C)` An experiment with two treatment factors, *A* and *B*, and error strata determined by factor *C*. For example a split plot experiment, with whole plots (and hence also subplots), determined by factor *C*.
The operator `~` is used to define a *model formula* in R. The form, for an ordinary linear model, is
```
response ~ op\_1 term\_1 op\_2 term\_2 op\_3 term\_3 …
```
where
response is a vector or matrix, (or expression evaluating to a vector or matrix) defining the response variable(s).
op\_i is an operator, either `+` or `-`, implying the inclusion or exclusion of a term in the model, (the first is optional).
term\_i
is either
* a vector or matrix expression, or `1`,
* a factor, or
* a *formula expression* consisting of factors, vectors or matrices connected by *formula operators*.
In all cases each term defines a collection of columns either to be added to or removed from the model matrix. A `1` stands for an intercept column and is by default included in the model matrix unless explicitly removed.
The *formula operators* are similar in effect to the Wilkinson and Rogers notation used by such programs as Glim and Genstat. One inevitable change is that the operator ‘``.``’ becomes ‘``:``’ since the period is a valid name character in R.
The notation is summarized below (based on Chambers & Hastie, 1992, p.29):
`Y ~ M`
Y is modeled as M.
`M\_1 + M\_2`
Include M\_1 and M\_2.
`M\_1 - M\_2`
Include M\_1 leaving out terms of M\_2.
`M\_1 : M\_2`
The tensor product of M\_1 and M\_2. If both terms are factors, then the “subclasses” factor.
`M\_1 %in% M\_2`
Similar to `M\_1:M\_2`, but with a different coding.
`M\_1 * M\_2`
`M\_1 + M\_2 + M\_1:M\_2`.
`M\_1 / M\_2`
`M\_1 + M\_2 %in% M\_1`.
`M^n`
All terms in M together with “interactions” up to order n
`I(M)` Insulate M. Inside M all operators have their normal arithmetic meaning, and that term appears in the model matrix.
Note that inside the parentheses that usually enclose function arguments all operators have their normal arithmetic meaning. The function `I()` is an identity function used to allow terms in model formulae to be defined using arithmetic operators.
Note particularly that the model formulae specify the *columns of the model matrix*, the specification of the parameters being implicit. This is not the case in other contexts, for example in specifying nonlinear models.
#### 11.1.1 Contrasts
We need at least some idea how the model formulae specify the columns of the model matrix. This is easy if we have continuous variables, as each provides one column of the model matrix (and the intercept will provide a column of ones if included in the model).
What about a *k*-level factor `A`? The answer differs for unordered and ordered factors. For *unordered* factors *k - 1* columns are generated for the indicators of the second, …, *k*th levels of the factor. (Thus the implicit parameterization is to contrast the response at each level with that at the first.) For *ordered* factors the *k - 1* columns are the orthogonal polynomials on *1, …, k*, omitting the constant term.
Although the answer is already complicated, it is not the whole story. First, if the intercept is omitted in a model that contains a factor term, the first such term is encoded into *k* columns giving the indicators for all the levels. Second, the whole behavior can be changed by the `options` setting for `contrasts`. The default setting in R is
```
options(contrasts = c("contr.treatment", "contr.poly"))
```
The main reason for mentioning this is that R and S have different defaults for unordered factors, S using Helmert contrasts. So if you need to compare your results to those of a textbook or paper which used S-PLUS, you will need to set
```
options(contrasts = c("contr.helmert", "contr.poly"))
```
This is a deliberate difference, as treatment contrasts (R’s default) are thought easier for newcomers to interpret.
We have still not finished, as the contrast scheme to be used can be set for each term in the model using the functions `contrasts` and `C`.
We have not yet considered interaction terms: these generate the products of the columns introduced for their component terms.
Although the details are complicated, model formulae in R will normally generate the models that an expert statistician would expect, provided that marginality is preserved. Fitting, for example, a model with an interaction but not the corresponding main effects will in general lead to surprising results, and is for experts only.
### 11.2 Linear models
The basic function for fitting ordinary multiple models is `lm()`, and a streamlined version of the call is as follows:
```
> fitted.model <- lm(formula, data = data.frame)
```
For example
```
> fm2 <- lm(y ~ x1 + x2, data = production)
```
would fit a multiple regression model of *y* on *x1* and *x2* (with implicit intercept term).
The important (but technically optional) parameter `data =
production` specifies that any variables needed to construct the model should come first from the `production` *data frame*. *This is the case regardless of whether data frame `production` has been attached on the search path or not*.
### 11.3 Generic functions for extracting model information
The value of `lm()` is a fitted model object; technically a list of results of class `"lm"`. Information about the fitted model can then be displayed, extracted, plotted and so on by using generic functions that orient themselves to objects of class `"lm"`. These include
```
add1 deviance formula predict step
alias drop1 kappa print summary
anova effects labels proj vcov
coef family plot residuals
```
A brief description of the most commonly used ones is given below.
`anova(object\_1, object\_2)`
Compare a submodel with an outer model and produce an analysis of variance table.
`coef(object)`
Extract the regression coefficient (matrix).
Long form: `coefficients(object)`.
`deviance(object)`
Residual sum of squares, weighted if appropriate.
`formula(object)`
Extract the model formula.
`plot(object)`
Produce four plots, showing residuals, fitted values and some diagnostics.
`predict(object, newdata=data.frame)`
The data frame supplied must have variables specified with the same labels as the original. The value is a vector or matrix of predicted values corresponding to the determining variable values in data.frame.
`print(object)`
Print a concise version of the object. Most often used implicitly.
`residuals(object)`
Extract the (matrix of) residuals, weighted as appropriate.
Short form: `resid(object)`.
`step(object)`
Select a suitable model by adding or dropping terms and preserving hierarchies. The model with the smallest value of AIC (Akaike’s An Information Criterion) discovered in the stepwise search is returned.
`summary(object)`
Print a comprehensive summary of the results of the regression analysis.
`vcov(object)` Returns the variance-covariance matrix of the main parameters of a fitted model object.
### 11.4 Analysis of variance and model comparison
The model fitting function `aov(formula,
data=data.frame)` operates at the simplest level in a very similar way to the function `lm()`, and most of the generic functions listed in the table in [Generic functions for extracting model information](#Generic-functions-for-extracting-model-information) apply.
It should be noted that in addition `aov()` allows an analysis of models with multiple error strata such as split plot experiments, or balanced incomplete block designs with recovery of inter-block information. The model formula
```
response ~ mean.formula + Error(strata.formula)
```
specifies a multi-stratum experiment with error strata defined by the strata.formula. In the simplest case, strata.formula is simply a factor, when it defines a two strata experiment, namely between and within the levels of the factor.
For example, with all determining variables factors, a model formula such as that in:
```
> fm <- aov(yield ~ v + n*p*k + Error(farms/blocks), data=farm.data)
```
would typically be used to describe an experiment with mean model `v + n*p*k` and three error strata, namely “between farms”, “within farms, between blocks” and “within blocks”.
#### 11.4.1 ANOVA tables
Note also that the analysis of variance table (or tables) are for a sequence of fitted models. The sums of squares shown are the decrease in the residual sums of squares resulting from an inclusion of *that term* in the model at *that place* in the sequence. Hence only for orthogonal experiments will the order of inclusion be inconsequential.
For multistratum experiments the procedure is first to project the response onto the error strata, again in sequence, and to fit the mean model to each projection. For further details, see Chambers & Hastie (1992).
A more flexible alternative to the default full ANOVA table is to compare two or more models directly using the `anova()` function.
```
> anova(fitted.model.1, fitted.model.2, …)
```
The display is then an ANOVA table showing the differences between the fitted models when fitted in sequence. The fitted models being compared would usually be an hierarchical sequence, of course. This does not give different information to the default, but rather makes it easier to comprehend and control.
### 11.5 Updating fitted models
The `update()` function is largely a convenience function that allows a model to be fitted that differs from one previously fitted usually by just a few additional or removed terms. Its form is
```
> new.model <- update(old.model, new.formula)
```
In the new.formula the special name consisting of a period, ‘``.``’, only, can be used to stand for “the corresponding part of the old model formula”. For example,
```
> fm05 <- lm(y ~ x1 + x2 + x3 + x4 + x5, data = production)
> fm6 <- update(fm05, . ~ . + x6)
> smf6 <- update(fm6, sqrt(.) ~ .)
```
would fit a five variate multiple regression with variables (presumably) from the data frame `production`, fit an additional model including a sixth regressor variable, and fit a variant on the model where the response had a square root transform applied.
Note especially that if the `data=` argument is specified on the original call to the model fitting function, this information is passed on through the fitted model object to `update()` and its allies.
The name ‘`.`’ can also be used in other contexts, but with slightly different meaning. For example
```
> fmfull <- lm(y ~ . , data = production)
```
would fit a model with response `y` and regressor variables *all other variables in the data frame `production`*.
Other functions for exploring incremental sequences of models are `add1()`, `drop1()` and `step()`. The names of these give a good clue to their purpose, but for full details see the on-line help.
### 11.6 Generalized linear models
Generalized linear modeling is a development of linear models to accommodate both non-normal response distributions and transformations to linearity in a clean and straightforward way. A generalized linear model may be described in terms of the following sequence of assumptions:
* There is a response, *y*, of interest and stimulus variables x\_1, x\_2, …, whose values influence the distribution of the response.
* The stimulus variables influence the distribution of *y* through *a single linear function, only*. This linear function is called the *linear predictor*, and is usually written
```
eta = beta_1 x_1 + beta_2 x_2 + … + beta_p x_p,
```
hence x\_i has no influence on the distribution of *y* if and only if beta\_i is zero.
* The distribution of *y* is of the form
```
f_Y(y; mu, phi)
= exp((A/phi) * (y lambda(mu) - gamma(lambda(mu))) + tau(y, phi))
```
where phi is a *scale parameter* (possibly known), and is constant for all observations, *A* represents a prior weight, assumed known but possibly varying with the observations, and $\mu$ is the mean of *y*. So it is assumed that the distribution of *y* is determined by its mean and possibly a scale parameter as well.
* The mean, mu, is a smooth invertible function of the linear predictor:
```
mu = m(eta), eta = m^{-1}(mu) = ell(mu)
```
and this inverse function, ell(), is called the *link function*.
These assumptions are loose enough to encompass a wide class of models useful in statistical practice, but tight enough to allow the development of a unified methodology of estimation and inference, at least approximately. The reader is referred to any of the current reference works on the subject for full details, such as McCullagh & Nelder (1989) or Dobson (1990).
#### 11.6.1 Families
The class of generalized linear models handled by facilities supplied in R includes *gaussian*, *binomial*, *poisson*, *inverse gaussian* and *gamma* response distributions and also *quasi-likelihood* models where the response distribution is not explicitly specified. In the latter case the *variance function* must be specified as a function of the mean, but in other cases this function is implied by the response distribution.
Each response distribution admits a variety of link functions to connect the mean with the linear predictor. Those automatically available are shown in the following table:
The combination of a response distribution, a link function and various other pieces of information that are needed to carry out the modeling exercise is called the *family* of the generalized linear model.
#### 11.6.2 The `glm()` function
Since the distribution of the response depends on the stimulus variables through a single linear function *only*, the same mechanism as was used for linear models can still be used to specify the linear part of a generalized model. The family has to be specified in a different way.
The R function to fit a generalized linear model is `glm()` which uses the form
```
> fitted.model <- glm(formula, family=family.generator, data=data.frame)
```
The only new feature is the family.generator, which is the instrument by which the family is described. It is the name of a function that generates a list of functions and expressions that together define and control the model and estimation process. Although this may seem a little complicated at first sight, its use is quite simple.
The names of the standard, supplied family generators are given under “Family Name” in the table in [Families](#Families). Where there is a choice of links, the name of the link may also be supplied with the family name, in parentheses as a parameter. In the case of the `quasi` family, the variance function may also be specified in this way.
Some examples make the process clear.
#### The `gaussian` family
A call such as
```
> fm <- glm(y ~ x1 + x2, family = gaussian, data = sales)
```
achieves the same result as
```
> fm <- lm(y ~ x1+x2, data=sales)
```
but much less efficiently. Note how the gaussian family is not automatically provided with a choice of links, so no parameter is allowed. If a problem requires a gaussian family with a nonstandard link, this can usually be achieved through the `quasi` family, as we shall see later.
#### The `binomial` family
Consider a small, artificial example, from Silvey (1970).
On the Aegean island of Kalythos the male inhabitants suffer from a congenital eye disease, the effects of which become more marked with increasing age. Samples of islander males of various ages were tested for blindness and the results recorded. The data is shown below:
The problem we consider is to fit both logistic and probit models to this data, and to estimate for each model the LD50, that is the age at which the chance of blindness for a male inhabitant is 50%.
If *y* is the number of blind at age *x* and *n* the number tested, both models have the form y ~ B(n, F(beta\_0 + beta\_1 x)) where for the probit case, F(z) = Phi(z) is the standard normal distribution function, and in the logit case (the default), F(z) = e^z/(1+e^z). In both cases the LD50 is LD50 = - beta\_0/beta\_1 that is, the point at which the argument of the distribution function is zero.
The first step is to set the data up as a data frame
```
> kalythos <- data.frame(x = c(20,35,45,55,70), n = rep(50,5),
y = c(6,17,26,37,44))
```
To fit a binomial model using `glm()` there are three possibilities for the response:
* If the response is a *vector* it is assumed to hold *binary* data, and so must be a *0/1* vector.
* If the response is a *two-column matrix* it is assumed that the first column holds the number of successes for the trial and the second holds the number of failures.
* If the response is a *factor*, its first level is taken as failure (0) and all other levels as ‘success’ (1).
Here we need the second of these conventions, so we add a matrix to our data frame:
```
> kalythos$Ymat <- cbind(kalythos$y, kalythos$n - kalythos$y)
```
To fit the models we use
```
> fmp <- glm(Ymat ~ x, family = binomial(link=probit), data = kalythos)
> fml <- glm(Ymat ~ x, family = binomial, data = kalythos)
```
Since the logit link is the default the parameter may be omitted on the second call. To see the results of each fit we could use
```
> summary(fmp)
> summary(fml)
```
Both models fit (all too) well. To find the LD50 estimate we can use a simple function:
```
> ld50 <- function(b) -b[1]/b[2]
> ldp <- ld50(coef(fmp)); ldl <- ld50(coef(fml)); c(ldp, ldl)
```
The actual estimates from this data are 43.663 years and 43.601 years respectively.
#### Poisson models
With the Poisson family the default link is the `log`, and in practice the major use of this family is to fit surrogate Poisson log-linear models to frequency data, whose actual distribution is often multinomial. This is a large and important subject we will not discuss further here. It even forms a major part of the use of non-gaussian generalized models overall.
Occasionally genuinely Poisson data arises in practice and in the past it was often analyzed as gaussian data after either a log or a square-root transformation. As a graceful alternative to the latter, a Poisson generalized linear model may be fitted as in the following example:
```
> fmod <- glm(y ~ A + B + x, family = poisson(link=sqrt),
data = worm.counts)
```
#### Quasi-likelihood models
For all families the variance of the response will depend on the mean and will have the scale parameter as a multiplier. The form of dependence of the variance on the mean is a characteristic of the response distribution; for example for the poisson distribution Var(y) = mu.
For quasi-likelihood estimation and inference the precise response distribution is not specified, but rather only a link function and the form of the variance function as it depends on the mean. Since quasi-likelihood estimation uses formally identical techniques to those for the gaussian distribution, this family provides a way of fitting gaussian models with non-standard link functions or variance functions, incidentally.
For example, consider fitting the non-linear regression y = theta\_1 z\_1 / (z\_2 - theta\_2) + e which may be written alternatively as y = 1 / (beta\_1 x\_1 + beta\_2 x\_2) + e where x\_1 = z\_2/z\_1, x\_2 = -1/z\_1, beta\_1 = 1/theta\_1, and beta\_2 = theta\_2/theta\_1. Supposing a suitable data frame to be set up we could fit this non-linear regression as
```
> nlfit <- glm(y ~ x1 + x2 - 1,
family = quasi(link=inverse, variance=constant),
data = biochem)
```
The reader is referred to the manual and the help document for further information, as needed.
### 11.7 Nonlinear least squares and maximum likelihood models
Certain forms of nonlinear model can be fitted by Generalized Linear Models (`glm()`). But in the majority of cases we have to approach the nonlinear curve fitting problem as one of nonlinear optimization. R’s nonlinear optimization routines are `optim()`, `nlm()` and `nlminb()`, which provide the functionality (and more) of S-PLUS’s `ms()` and `nlminb()`. We seek the parameter values that minimize some index of lack-of-fit, and they do this by trying out various parameter values iteratively. Unlike linear regression for example, there is no guarantee that the procedure will converge on satisfactory estimates. All the methods require initial guesses about what parameter values to try, and convergence may depend critically upon the quality of the starting values.
#### 11.7.1 Least squares
One way to fit a nonlinear model is by minimizing the sum of the squared errors (SSE) or residuals. This method makes sense if the observed errors could have plausibly arisen from a normal distribution.
Here is an example from Bates & Watts (1988), page 51. The data are:
```
> x <- c(0.02, 0.02, 0.06, 0.06, 0.11, 0.11, 0.22, 0.22, 0.56, 0.56,
1.10, 1.10)
> y <- c(76, 47, 97, 107, 123, 139, 159, 152, 191, 201, 207, 200)
```
The fit criterion to be minimized is:
```
> fn <- function(p) sum((y - (p[1] * x)/(p[2] + x))^2)
```
In order to do the fit we need initial estimates of the parameters. One way to find sensible starting values is to plot the data, guess some parameter values, and superimpose the model curve using those values.
```
> plot(x, y)
> xfit <- seq(.02, 1.1, .05)
> yfit <- 200 * xfit/(0.1 + xfit)
> lines(spline(xfit, yfit))
```
We could do better, but these starting values of 200 and 0.1 seem adequate. Now do the fit:
```
> out <- nlm(fn, p = c(200, 0.1), hessian = TRUE)
```
After the fitting, `out$minimum` is the SSE, and `out$estimate` are the least squares estimates of the parameters. To obtain the approximate standard errors (SE) of the estimates we do:
```
> sqrt(diag(2*out$minimum/(length(y) - 2) * solve(out$hessian)))
```
The `2` which is subtracted in the line above represents the number of parameters. A 95% confidence interval would be the parameter estimate +/- 1.96 SE. We can superimpose the least squares fit on a new plot:
```
> plot(x, y)
> xfit <- seq(.02, 1.1, .05)
> yfit <- 212.68384222 * xfit/(0.06412146 + xfit)
> lines(spline(xfit, yfit))
```
The standard package **stats** provides much more extensive facilities for fitting non-linear models by least squares. The model we have just fitted is the Michaelis-Menten model, so we can use
```
> df <- data.frame(x=x, y=y)
> fit <- nls(y ~ SSmicmen(x, Vm, K), df)
> fit
Nonlinear regression model
model: y ~ SSmicmen(x, Vm, K)
data: df
Vm K
212.68370711 0.06412123
residual sum-of-squares: 1195.449
> summary(fit)
Formula: y ~ SSmicmen(x, Vm, K)
Parameters:
Estimate Std. Error t value Pr(>|t|)
Vm 2.127e+02 6.947e+00 30.615 3.24e-11
K 6.412e-02 8.281e-03 7.743 1.57e-05
Residual standard error: 10.93 on 10 degrees of freedom
Correlation of Parameter Estimates:
Vm
K 0.7651
```
#### 11.7.2 Maximum likelihood
Maximum likelihood is a method of nonlinear model fitting that applies even if the errors are not normal. The method finds the parameter values which maximize the log likelihood, or equivalently which minimize the negative log-likelihood. Here is an example from Dobson (1990), pp. 108–111. This example fits a logistic model to dose-response data, which clearly could also be fit by `glm()`. The data are:
```
> x <- c(1.6907, 1.7242, 1.7552, 1.7842, 1.8113,
1.8369, 1.8610, 1.8839)
> y <- c( 6, 13, 18, 28, 52, 53, 61, 60)
> n <- c(59, 60, 62, 56, 63, 59, 62, 60)
```
The negative log-likelihood to minimize is:
```
> fn <- function(p)
sum( - (y*(p[1]+p[2]*x) - n*log(1+exp(p[1]+p[2]*x))
+ log(choose(n, y)) ))
```
We pick sensible starting values and do the fit:
```
> out <- nlm(fn, p = c(-50,20), hessian = TRUE)
```
After the fitting, `out$minimum` is the negative log-likelihood, and `out$estimate` are the maximum likelihood estimates of the parameters. To obtain the approximate SEs of the estimates we do:
```
> sqrt(diag(solve(out$hessian)))
```
A 95% confidence interval would be the parameter estimate +/- 1.96 SE.
### 11.8 Some non-standard models
We conclude this chapter with just a brief mention of some of the other facilities available in R for special regression and data analysis problems.
* **Mixed models.** The recommended [**nlme**](https://CRAN.R-project.org/package=nlme) package provides functions `lme()` and `nlme()` for linear and non-linear mixed-effects models, that is linear and non-linear regressions in which some of the coefficients correspond to random effects. These functions make heavy use of formulae to specify the models.
* **Local approximating regressions.** The `loess()` function fits a nonparametric regression by using a locally weighted regression. Such regressions are useful for highlighting a trend in messy data or for data reduction to give some insight into a large data set. Function `loess` is in the standard package **stats**, together with code for projection pursuit regression.
* **Robust regression.** There are several functions available for fitting regression models in a way resistant to the influence of extreme outliers in the data. Function `lqs` in the recommended package [**MASS**](https://CRAN.R-project.org/package=MASS) provides state-of-art algorithms for highly-resistant fits. Less resistant but statistically more efficient methods are available in packages, for example function `rlm` in package [**MASS**](https://CRAN.R-project.org/package=MASS).
* **Additive models.** This technique aims to construct a regression function from smooth additive functions of the determining variables, usually one for each determining variable. Functions `avas` and `ace` in package [**acepack**](https://CRAN.R-project.org/package=acepack) and functions `bruto` and `mars` in package [**mda**](https://CRAN.R-project.org/package=mda) provide some examples of these techniques in user-contributed packages to R. An extension is **Generalized Additive Models**, implemented in user-contributed packages [**gam**](https://CRAN.R-project.org/package=gam) and [**mgcv**](https://CRAN.R-project.org/package=mgcv).
* **Tree-based models.** Rather than seek an explicit global linear model for prediction or interpretation, tree-based models seek to bifurcate the data, recursively, at critical points of the determining variables in order to partition the data ultimately into groups that are as homogeneous as possible within, and as heterogeneous as possible between. The results often lead to insights that other data analysis methods tend not to yield. Models are again specified in the ordinary linear model form. The model fitting function is `tree()`, but many other generic functions such as `plot()` and `text()` are well adapted to displaying the results of a tree-based model fit in a graphical way.
Tree models are available in R *via* the user-contributed packages [**rpart**](https://CRAN.R-project.org/package=rpart) and [**tree**](https://CRAN.R-project.org/package=tree).
12 Graphical procedures
-----------------------
Graphical facilities are an important and extremely versatile component of the R environment. It is possible to use the facilities to display a wide variety of statistical graphs and also to build entirely new types of graph.
The graphics facilities can be used in both interactive and batch modes, but in most cases, interactive use is more productive. Interactive use is also easy because at startup time R initiates a graphics *device driver* which opens a special *graphics window* for the display of interactive graphics. Although this is done automatically, it may useful to know that the command used is `X11()` under UNIX, `windows()` under Windows and `quartz()` under macOS. A new device can always be opened by `dev.new()`.
Once the device driver is running, R plotting commands can be used to produce a variety of graphical displays and to create entirely new kinds of display.
Plotting commands are divided into three basic groups:
* **High-level** plotting functions create a new plot on the graphics device, possibly with axes, labels, titles and so on.
* **Low-level** plotting functions add more information to an existing plot, such as extra points, lines and labels.
* **Interactive** graphics functions allow you interactively add information to, or extract information from, an existing plot, using a pointing device such as a mouse.
In addition, R maintains a list of *graphical parameters* which can be manipulated to customize your plots.
This manual only describes what are known as ‘base’ graphics. A separate graphics sub-system in package **grid** coexists with base – it is more powerful but harder to use. There is a recommended package [**lattice**](https://CRAN.R-project.org/package=lattice) which builds on **grid** and provides ways to produce multi-panel plots akin to those in the *Trellis* system in S.
### 12.1 High-level plotting commands
High-level plotting functions are designed to generate a complete plot of the data passed as arguments to the function. Where appropriate, axes, labels and titles are automatically generated (unless you request otherwise.) High-level plotting commands always start a new plot, erasing the current plot if necessary.
#### 12.1.1 The `plot()` function
One of the most frequently used plotting functions in R is the `plot()` function. This is a *generic* function: the type of plot produced is dependent on the type or *class* of the first argument.
`plot(x, y)` `plot(xy)`
If x and y are vectors, `plot(x, y)` produces a scatterplot of y against x. The same effect can be produced by supplying one argument (second form) as either a list containing two elements x and y or a two-column matrix.
`plot(x)`
If x is a time series, this produces a time-series plot. If x is a numeric vector, it produces a plot of the values in the vector against their index in the vector. If x is a complex vector, it produces a plot of imaginary versus real parts of the vector elements.
`plot(f)` `plot(f, y)`
f is a factor object, y is a numeric vector. The first form generates a bar plot of f; the second form produces boxplots of y for each level of f.
`plot(df)` `plot(~ expr)` `plot(y ~ expr)` df is a data frame, y is any object, expr is a list of object names separated by ‘`+`’ (e.g., `a + b + c`). The first two forms produce distributional plots of the variables in a data frame (first form) or of a number of named objects (second form). The third form plots y against every object named in expr.
#### 12.1.2 Displaying multivariate data
R provides two very useful functions for representing multivariate data. If `X` is a numeric matrix or data frame, the command
```
> pairs(X)
```
produces a pairwise scatterplot matrix of the variables defined by the columns of `X`, that is, every column of `X` is plotted against every other column of `X` and the resulting *n(n-1)* plots are arranged in a matrix with plot scales constant over the rows and columns of the matrix.
When three or four variables are involved a *coplot* may be more enlightening. If `a` and `b` are numeric vectors and `c` is a numeric vector or factor object (all of the same length), then the command
```
> coplot(a ~ b | c)
```
produces a number of scatterplots of `a` against `b` for given values of `c`. If `c` is a factor, this simply means that `a` is plotted against `b` for every level of `c`. When `c` is numeric, it is divided into a number of *conditioning intervals* and for each interval `a` is plotted against `b` for values of `c` within the interval. The number and position of intervals can be controlled with `given.values=` argument to `coplot()`—the function `co.intervals()` is useful for selecting intervals. You can also use two *given* variables with a command like
```
> coplot(a ~ b | c + d)
```
which produces scatterplots of `a` against `b` for every joint conditioning interval of `c` and `d`.
The `coplot()` and `pairs()` function both take an argument `panel=` which can be used to customize the type of plot which appears in each panel. The default is `points()` to produce a scatterplot but by supplying some other low-level graphics function of two vectors `x` and `y` as the value of `panel=` you can produce any type of plot you wish. An example panel function useful for coplots is `panel.smooth()`.
#### 12.1.3 Display graphics
Other high-level graphics functions produce different types of plots. Some examples are:
`qqnorm(x)` `qqline(x)` `qqplot(x, y)`
Distribution-comparison plots. The first form plots the numeric vector `x` against the expected Normal order scores (a normal scores plot) and the second adds a straight line to such a plot by drawing a line through the distribution and data quartiles. The third form plots the quantiles of `x` against those of `y` to compare their respective distributions.
`hist(x)` `hist(x, nclass=n)` `hist(x, breaks=b, …)`
Produces a histogram of the numeric vector `x`. A sensible number of classes is usually chosen, but a recommendation can be given with the `nclass=` argument. Alternatively, the breakpoints can be specified exactly with the `breaks=` argument. If the `probability=TRUE` argument is given, the bars represent relative frequencies divided by bin width instead of counts.
`dotchart(x, …)`
Constructs a dotchart of the data in `x`. In a dotchart the *y*-axis gives a labelling of the data in `x` and the *x*-axis gives its value. For example it allows easy visual selection of all data entries with values lying in specified ranges.
`image(x, y, z, …)` `contour(x, y, z, …)` `persp(x, y, z, …)`
Plots of three variables. The `image` plot draws a grid of rectangles using different colours to represent the value of `z`, the `contour` plot draws contour lines to represent the value of `z`, and the `persp` plot draws a 3D surface.
#### 12.1.4 Arguments to high-level plotting functions
There are a number of arguments which may be passed to high-level graphics functions, as follows:
`add=TRUE`
Forces the function to act as a low-level graphics function, superimposing the plot on the current plot (some functions only).
`axes=FALSE`
Suppresses generation of axes—useful for adding your own custom axes with the `axis()` function. The default, `axes=TRUE`, means include axes.
`log="x"` `log="y"` `log="xy"`
Causes the *x*, *y* or both axes to be logarithmic. This will work for many, but not all, types of plot.
`type=`
The `type=` argument controls the type of plot produced, as follows:
`type="p"` Plot individual points (the default)
`type="l"` Plot lines
`type="b"` Plot points connected by lines (*both*)
`type="o"` Plot points overlaid by lines
`type="h"` Plot vertical lines from points to the zero axis (*high-density*)
`type="s"` `type="S"` Step-function plots. In the first form, the top of the vertical defines the point; in the second, the bottom.
`type="n"` No plotting at all. However axes are still drawn (by default) and the coordinate system is set up according to the data. Ideal for creating plots with subsequent low-level graphics functions.
`xlab=string` `ylab=string`
Axis labels for the *x* and *y* axes. Use these arguments to change the default labels, usually the names of the objects used in the call to the high-level plotting function.
`main=string`
Figure title, placed at the top of the plot in a large font.
`sub=string` Sub-title, placed just below the *x*-axis in a smaller font.
### 12.2 Low-level plotting commands
Sometimes the high-level plotting functions don’t produce exactly the kind of plot you desire. In this case, low-level plotting commands can be used to add extra information (such as points, lines or text) to the current plot.
Some of the more useful low-level plotting functions are:
`points(x, y)` `lines(x, y)`
Adds points or connected lines to the current plot. `plot()`’s `type=` argument can also be passed to these functions (and defaults to `"p"` for `points()` and `"l"` for `lines()`.)
`text(x, y, labels, …)`
Add text to a plot at points given by `x, y`. Normally `labels` is an integer or character vector in which case `labels[i]` is plotted at point `(x[i], y[i])`. The default is `1:length(x)`.
**Note**: This function is often used in the sequence
```
> plot(x, y, type="n"); text(x, y, names)
```
The graphics parameter `type="n"` suppresses the points but sets up the axes, and the `text()` function supplies special characters, as specified by the character vector `names` for the points.
`abline(a, b)` `abline(h=y)` `abline(v=x)` `abline(lm.obj)`
Adds a line of slope `b` and intercept `a` to the current plot. `h=y` may be used to specify *y*-coordinates for the heights of horizontal lines to go across a plot, and `v=x` similarly for the *x*-coordinates for vertical lines. Also lm.obj may be list with a `coefficients` component of length 2 (such as the result of model-fitting functions,) which are taken as an intercept and slope, in that order.
`polygon(x, y, …)`
Draws a polygon defined by the ordered vertices in (`x`, `y`) and (optionally) shade it in with hatch lines, or fill it if the graphics device allows the filling of figures.
`legend(x, y, legend, …)`
Adds a legend to the current plot at the specified position. Plotting characters, line styles, colors etc., are identified with the labels in the character vector `legend`. At least one other argument v (a vector the same length as `legend`) with the corresponding values of the plotting unit must also be given, as follows:
`legend( , fill=v)` Colors for filled boxes
`legend( , col=v)` Colors in which points or lines will be drawn
`legend( , lty=v)` Line styles
`legend( , lwd=v)` Line widths
`legend( , pch=v)` Plotting characters (character vector)
`title(main, sub)`
Adds a title `main` to the top of the current plot in a large font and (optionally) a sub-title `sub` at the bottom in a smaller font.
`axis(side, …)`
Adds an axis to the current plot on the side given by the first argument (1 to 4, counting clockwise from the bottom.) Other arguments control the positioning of the axis within or beside the plot, and tick positions and labels. Useful for adding custom axes after calling `plot()` with the `axes=FALSE` argument.
Low-level plotting functions usually require some positioning information (e.g., *x* and *y* coordinates) to determine where to place the new plot elements. Coordinates are given in terms of *user coordinates* which are defined by the previous high-level graphics command and are chosen based on the supplied data.
Where `x` and `y` arguments are required, it is also sufficient to supply a single argument being a list with elements named `x` and `y`. Similarly a matrix with two columns is also valid input. In this way functions such as `locator()` (see below) may be used to specify positions on a plot interactively.
#### 12.2.1 Mathematical annotation
In some cases, it is useful to add mathematical symbols and formulae to a plot. This can be achieved in R by specifying an *expression* rather than a character string in any one of `text`, `mtext`, `axis`, or `title`. For example, the following code draws the formula for the Binomial probability function:
```
> text(x, y, expression(paste(bgroup("(", atop(n, x), ")"), p^x, q^{n-x})))
```
More information, including a full listing of the features available can obtained from within R using the commands:
```
> help(plotmath)
> example(plotmath)
> demo(plotmath)
```
#### 12.2.2 Hershey vector fonts
It is possible to specify Hershey vector fonts for rendering text when using the `text` and `contour` functions. There are three reasons for using the Hershey fonts:
* Hershey fonts can produce better output, especially on a computer screen, for rotated and/or small text.
* Hershey fonts provide certain symbols that may not be available in the standard fonts. In particular, there are zodiac signs, cartographic symbols and astronomical symbols.
* Hershey fonts provide cyrillic and japanese (Kana and Kanji) characters.
More information, including tables of Hershey characters can be obtained from within R using the commands:
```
> help(Hershey)
> demo(Hershey)
> help(Japanese)
> demo(Japanese)
```
### 12.3 Interacting with graphics
R also provides functions which allow users to extract or add information to a plot using a mouse. The simplest of these is the `locator()` function:
`locator(n, type)`
Waits for the user to select locations on the current plot using the left mouse button. This continues until `n` (default 512) points have been selected, or another mouse button is pressed. The `type` argument allows for plotting at the selected points and has the same effect as for high-level graphics commands; the default is no plotting. `locator()` returns the locations of the points selected as a list with two components `x` and `y`.
`locator()` is usually called with no arguments. It is particularly useful for interactively selecting positions for graphic elements such as legends or labels when it is difficult to calculate in advance where the graphic should be placed. For example, to place some informative text near an outlying point, the command
```
> text(locator(1), "Outlier", adj=0)
```
may be useful. (`locator()` will be ignored if the current device, such as `postscript` does not support interactive pointing.)
`identify(x, y, labels)`
Allow the user to highlight any of the points defined by `x` and `y` (using the left mouse button) by plotting the corresponding component of `labels` nearby (or the index number of the point if `labels` is absent). Returns the indices of the selected points when another button is pressed.
Sometimes we want to identify particular *points* on a plot, rather than their positions. For example, we may wish the user to select some observation of interest from a graphical display and then manipulate that observation in some way. Given a number of *(x, y)* coordinates in two numeric vectors `x` and `y`, we could use the `identify()` function as follows:
```
> plot(x, y)
> identify(x, y)
```
The `identify()` functions performs no plotting itself, but simply allows the user to move the mouse pointer and click the left mouse button near a point. If there is a point near the mouse pointer it will be marked with its index number (that is, its position in the `x`/`y` vectors) plotted nearby. Alternatively, you could use some informative string (such as a case name) as a highlight by using the `labels` argument to `identify()`, or disable marking altogether with the `plot = FALSE` argument. When the process is terminated (see above), `identify()` returns the indices of the selected points; you can use these indices to extract the selected points from the original vectors `x` and `y`.
### 12.4 Using graphics parameters
When creating graphics, particularly for presentation or publication purposes, R’s defaults do not always produce exactly that which is required. You can, however, customize almost every aspect of the display using *graphics parameters*. R maintains a list of a large number of graphics parameters which control things such as line style, colors, figure arrangement and text justification among many others. Every graphics parameter has a name (such as ‘`col`’, which controls colors,) and a value (a color number, for example.)
A separate list of graphics parameters is maintained for each active device, and each device has a default set of parameters when initialized. Graphics parameters can be set in two ways: either permanently, affecting all graphics functions which access the current device; or temporarily, affecting only a single graphics function call.
#### 12.4.1 Permanent changes: The `par()` function
The `par()` function is used to access and modify the list of graphics parameters for the current graphics device.
`par()` Without arguments, returns a list of all graphics parameters and their values for the current device.
`par(c("col", "lty"))` With a character vector argument, returns only the named graphics parameters (again, as a list.)
`par(col=4, lty=2)` With named arguments (or a single list argument), sets the values of the named graphics parameters, and returns the original values of the parameters as a list.
Setting graphics parameters with the `par()` function changes the value of the parameters *permanently*, in the sense that all future calls to graphics functions (on the current device) will be affected by the new value. You can think of setting graphics parameters in this way as setting “default” values for the parameters, which will be used by all graphics functions unless an alternative value is given.
Note that calls to `par()` *always* affect the global values of graphics parameters, even when `par()` is called from within a function. This is often undesirable behavior—usually we want to set some graphics parameters, do some plotting, and then restore the original values so as not to affect the user’s R session. You can restore the initial values by saving the result of `par()` when making changes, and restoring the initial values when plotting is complete.
```
> oldpar <- par(col=4, lty=2)
… plotting commands …
> par(oldpar)
```
To save and restore *all* settable[25](#FOOT25) graphical parameters use
```
> oldpar <- par(no.readonly=TRUE)
… plotting commands …
> par(oldpar)
```
#### 12.4.2 Temporary changes: Arguments to graphics functions
Graphics parameters may also be passed to (almost) any graphics function as named arguments. This has the same effect as passing the arguments to the `par()` function, except that the changes only last for the duration of the function call. For example:
```
> plot(x, y, pch="+")
```
produces a scatterplot using a plus sign as the plotting character, without changing the default plotting character for future plots.
Unfortunately, this is not implemented entirely consistently and it is sometimes necessary to set and reset graphics parameters using `par()`.
### 12.5 Graphics parameters list
The following sections detail many of the commonly-used graphical parameters. The R help documentation for the `par()` function provides a more concise summary; this is provided as a somewhat more detailed alternative.
Graphics parameters will be presented in the following form:
`name=value` A description of the parameter’s effect. name is the name of the parameter, that is, the argument name to use in calls to `par()` or a graphics function. value is a typical value you might use when setting the parameter.
Note that `axes` is **not** a graphics parameter but an argument to a few `plot` methods: see `xaxt` and `yaxt`.
#### 12.5.1 Graphical elements
R plots are made up of points, lines, text and polygons (filled regions.) Graphical parameters exist which control how these *graphical elements* are drawn, as follows:
`pch="+"`
Character to be used for plotting points. The default varies with graphics drivers, but it is usually a circle. Plotted points tend to appear slightly above or below the appropriate position unless you use `"."` as the plotting character, which produces centered points.
`pch=4`
When `pch` is given as an integer between 0 and 25 inclusive, a specialized plotting symbol is produced. To see what the symbols are, use the command
```
> legend(locator(1), as.character(0:25), pch = 0:25)
```
Those from 21 to 25 may appear to duplicate earlier symbols, but can be coloured in different ways: see the help on `points` and its examples.
In addition, `pch` can be a character or a number in the range `32:255` representing a character in the current font.
`lty=2`
Line types. Alternative line styles are not supported on all graphics devices (and vary on those that do) but line type 1 is always a solid line, line type 0 is always invisible, and line types 2 and onwards are dotted or dashed lines, or some combination of both.
`lwd=2`
Line widths. Desired width of lines, in multiples of the “standard” line width. Affects axis lines as well as lines drawn with `lines()`, etc. Not all devices support this, and some have restrictions on the widths that can be used.
`col=2`
Colors to be used for points, lines, text, filled regions and images. A number from the current palette (see `?palette`) or a named colour.
`col.axis` `col.lab` `col.main` `col.sub`
The color to be used for axis annotation, *x* and *y* labels, main and sub-titles, respectively.
`font=2`
An integer which specifies which font to use for text. If possible, device drivers arrange so that `1` corresponds to plain text, `2` to bold face, `3` to italic, `4` to bold italic and `5` to a symbol font (which include Greek letters).
`font.axis` `font.lab` `font.main` `font.sub`
The font to be used for axis annotation, *x* and *y* labels, main and sub-titles, respectively.
`adj=-0.1`
Justification of text relative to the plotting position. `0` means left justify, `1` means right justify and `0.5` means to center horizontally about the plotting position. The actual value is the proportion of text that appears to the left of the plotting position, so a value of `-0.1` leaves a gap of 10% of the text width between the text and the plotting position.
`cex=1.5`
Character expansion. The value is the desired size of text characters (including plotting characters) relative to the default text size.
`cex.axis` `cex.lab` `cex.main` `cex.sub` The character expansion to be used for axis annotation, *x* and *y* labels, main and sub-titles, respectively.
#### 12.5.2 Axes and tick marks
Many of R’s high-level plots have axes, and you can construct axes yourself with the low-level `axis()` graphics function. Axes have three main components: the *axis line* (line style controlled by the `lty` graphics parameter), the *tick marks* (which mark off unit divisions along the axis line) and the *tick labels* (which mark the units.) These components can be customized with the following graphics parameters.
`lab=c(5, 7, 12)`
The first two numbers are the desired number of tick intervals on the *x* and *y* axes respectively. The third number is the desired length of axis labels, in characters (including the decimal point.) Choosing a too-small value for this parameter may result in all tick labels being rounded to the same number!
`las=1`
Orientation of axis labels. `0` means always parallel to axis, `1` means always horizontal, and `2` means always perpendicular to the axis.
`mgp=c(3, 1, 0)`
Positions of axis components. The first component is the distance from the axis label to the axis position, in text lines. The second component is the distance to the tick labels, and the final component is the distance from the axis position to the axis line (usually zero). Positive numbers measure outside the plot region, negative numbers inside.
`tck=0.01`
Length of tick marks, as a fraction of the size of the plotting region. When `tck` is small (less than 0.5) the tick marks on the *x* and *y* axes are forced to be the same size. A value of 1 gives grid lines. Negative values give tick marks outside the plotting region. Use `tck=0.01` and `mgp=c(1,-1.5,0)` for internal tick marks.
`xaxs="r"` `yaxs="i"`
Axis styles for the *x* and *y* axes, respectively. With styles `"i"` (internal) and `"r"` (the default) tick marks always fall within the range of the data, however style `"r"` leaves a small amount of space at the edges. (S has other styles not implemented in R.)
#### 12.5.3 Figure margins
A single plot in R is known as a `figure` and comprises a *plot region* surrounded by margins (possibly containing axis labels, titles, etc.) and (usually) bounded by the axes themselves.
A typical figure is
Graphics parameters controlling figure layout include:
`mai=c(1, 0.5, 0.5, 0)`
Widths of the bottom, left, top and right margins, respectively, measured in inches.
`mar=c(4, 2, 2, 1)` Similar to `mai`, except the measurement unit is text lines.
`mar` and `mai` are equivalent in the sense that setting one changes the value of the other. The default values chosen for this parameter are often too large; the right-hand margin is rarely needed, and neither is the top margin if no title is being used. The bottom and left margins must be large enough to accommodate the axis and tick labels. Furthermore, the default is chosen without regard to the size of the device surface: for example, using the `postscript()` driver with the `height=4` argument will result in a plot which is about 50% margin unless `mar` or `mai` are set explicitly. When multiple figures are in use (see below) the margins are reduced, however this may not be enough when many figures share the same page.
#### 12.5.4 Multiple figure environment
R allows you to create an *n* by *m* array of figures on a single page. Each figure has its own margins, and the array of figures is optionally surrounded by an *outer margin*, as shown in the following figure.
The graphical parameters relating to multiple figures are as follows:
`mfcol=c(3, 2)` `mfrow=c(2, 4)`
Set the size of a multiple figure array. The first value is the number of rows; the second is the number of columns. The only difference between these two parameters is that setting `mfcol` causes figures to be filled by column; `mfrow` fills by rows.
The layout in the Figure could have been created by setting `mfrow=c(3,2)`; the figure shows the page after four plots have been drawn.
Setting either of these can reduce the base size of symbols and text (controlled by `par("cex")` and the pointsize of the device). In a layout with exactly two rows and columns the base size is reduced by a factor of 0.83: if there are three or more of either rows or columns, the reduction factor is 0.66.
`mfg=c(2, 2, 3, 2)`
Position of the current figure in a multiple figure environment. The first two numbers are the row and column of the current figure; the last two are the number of rows and columns in the multiple figure array. Set this parameter to jump between figures in the array. You can even use different values for the last two numbers than the *true* values for unequally-sized figures on the same page.
`fig=c(4, 9, 1, 4)/10`
Position of the current figure on the page. Values are the positions of the left, right, bottom and top edges respectively, as a percentage of the page measured from the bottom left corner. The example value would be for a figure in the bottom right of the page. Set this parameter for arbitrary positioning of figures within a page. If you want to add a figure to a current page, use `new=TRUE` as well (unlike S).
`oma=c(2, 0, 3, 0)` `omi=c(0, 0, 0.8, 0)`
Size of outer margins. Like `mar` and `mai`, the first measures in text lines and the second in inches, starting with the bottom margin and working clockwise.
Outer margins are particularly useful for page-wise titles, etc. Text can be added to the outer margins with the `mtext()` function with argument `outer=TRUE`. There are no outer margins by default, however, so you must create them explicitly using `oma` or `omi`.
More complicated arrangements of multiple figures can be produced by the `split.screen()` and `layout()` functions, as well as by the **grid** and [**lattice**](https://CRAN.R-project.org/package=lattice) packages.
### 12.6 Device drivers
R can generate graphics (of varying levels of quality) on almost any type of display or printing device. Before this can begin, however, R needs to be informed what type of device it is dealing with. This is done by starting a *device driver*. The purpose of a device driver is to convert graphical instructions from R (“draw a line,” for example) into a form that the particular device can understand.
Device drivers are started by calling a device driver function. There is one such function for every device driver: type `help(Devices)` for a list of them all. For example, issuing the command
```
> postscript()
```
causes all future graphics output to be sent to the printer in PostScript format. Some commonly-used device drivers are:
`X11()`
For use with the X11 window system on Unix-alikes
`windows()`
For use on Windows
`quartz()`
For use on macOS
`postscript()`
For printing on PostScript printers, or creating PostScript graphics files.
`pdf()`
Produces a PDF file, which can also be included into PDF files.
`png()`
Produces a bitmap PNG file. (Not always available: see its help page.)
`jpeg()`
Produces a bitmap JPEG file, best used for `image` plots. (Not always available: see its help page.)
When you have finished with a device, be sure to terminate the device driver by issuing the command
```
> dev.off()
```
This ensures that the device finishes cleanly; for example in the case of hardcopy devices this ensures that every page is completed and has been sent to the printer. (This will happen automatically at the normal end of a session.)
#### 12.6.1 PostScript diagrams for typeset documents
By passing the `file` argument to the `postscript()` device driver function, you may store the graphics in PostScript format in a file of your choice. The plot will be in landscape orientation unless the `horizontal=FALSE` argument is given, and you can control the size of the graphic with the `width` and `height` arguments (the plot will be scaled as appropriate to fit these dimensions.) For example, the command
```
> postscript("file.ps", horizontal=FALSE, height=5, pointsize=10)
```
will produce a file containing PostScript code for a figure five inches high, perhaps for inclusion in a document. It is important to note that if the file named in the command already exists, it will be overwritten. This is the case even if the file was only created earlier in the same R session.
Many usages of PostScript output will be to incorporate the figure in another document. This works best when *encapsulated* PostScript is produced: R always produces conformant output, but only marks the output as such when the `onefile=FALSE` argument is supplied. This unusual notation stems from S-compatibility: it really means that the output will be a single page (which is part of the EPSF specification). Thus to produce a plot for inclusion use something like
```
> postscript("plot1.eps", horizontal=FALSE, onefile=FALSE,
height=8, width=6, pointsize=10)
```
#### 12.6.2 Multiple graphics devices
In advanced use of R it is often useful to have several graphics devices in use at the same time. Of course only one graphics device can accept graphics commands at any one time, and this is known as the *current device*. When multiple devices are open, they form a numbered sequence with names giving the kind of device at any position.
The main commands used for operating with multiple devices, and their meanings are as follows:
`X11()` [UNIX]
`windows()` `win.printer()` `win.metafile()` [Windows]
`quartz()` [macOS]
`postscript()` `pdf()` `png()` `jpeg()` `tiff()` `bitmap()` `…`
Each new call to a device driver function opens a new graphics device, thus extending by one the device list. This device becomes the current device, to which graphics output will be sent.
`dev.list()`
Returns the number and name of all active devices. The device at position 1 on the list is always the *null device* which does not accept graphics commands at all.
`dev.next()` `dev.prev()`
Returns the number and name of the graphics device next to, or previous to the current device, respectively.
`dev.set(which=k)`
Can be used to change the current graphics device to the one at position k of the device list. Returns the number and label of the device.
`dev.off(k)`
Terminate the graphics device at point k of the device list. For some devices, such as `postscript` devices, this will either print the file immediately or correctly complete the file for later printing, depending on how the device was initiated.
`dev.copy(device, …, which=k)` `dev.print(device, …, which=k)`
Make a copy of the device k. Here `device` is a device function, such as `postscript`, with extra arguments, if needed, specified by ‘`…`’. `dev.print` is similar, but the copied device is immediately closed, so that end actions, such as printing hardcopies, are immediately performed.
`graphics.off()` Terminate all graphics devices on the list, except the null device.
### 12.7 Dynamic graphics
R does not have builtin capabilities for dynamic or interactive graphics, e.g. rotating point clouds or to “brushing” (interactively highlighting) points. However, extensive dynamic graphics facilities are available in the system GGobi by Swayne, Cook and Buja available from
> <http://ggobi.org/>
>
>
>
and these can be accessed from R via the package [**rggobi**](https://CRAN.R-project.org/package=rggobi), described at <http://ggobi.org/rggobi.html>.
Also, package [**rgl**](https://CRAN.R-project.org/package=rgl) provides ways to interact with 3D plots, for example of surfaces.
13 Packages
-----------
All R functions and datasets are stored in *packages*. Only when a package is loaded are its contents available. This is done both for efficiency (the full list would take more memory and would take longer to search than a subset), and to aid package developers, who are protected from name clashes with other code. The process of developing packages is described in [Creating R packages](https://cran.r-project.org/doc/manuals/R-exts.html#Creating-R-packages) in Writing R Extensions. Here, we will describe them from a user’s point of view.
To see which packages are installed at your site, issue the command
```
> library()
```
with no arguments. To load a particular package (e.g., the [**boot**](https://CRAN.R-project.org/package=boot) package containing functions from Davison & Hinkley (1997)), use a command like
```
> library(boot)
```
Users connected to the Internet can use the `install.packages()` and `update.packages()` functions (available through the `Packages` menu in the Windows and macOS GUIs, see [Installing packages](https://cran.r-project.org/doc/manuals/R-admin.html#Installing-packages) in R Installation and Administration) to install and update packages.
To see which packages are currently loaded, use
```
> search()
```
to display the search list. Some packages may be loaded but not available on the search list (see [Namespaces](#Namespaces)): these will be included in the list given by
```
> loadedNamespaces()
```
To see a list of all available help topics in an installed package, use
```
> help.start()
```
to start the HTML help system, and then navigate to the package listing in the `Reference` section.
### 13.1 Standard packages
The standard (or *base*) packages are considered part of the R source code. They contain the basic functions that allow R to work, and the datasets and standard statistical and graphical functions that are described in this manual. They should be automatically available in any R installation. See R packages in R FAQ, for a complete list.
### 13.2 Contributed packages and CRAN
There are thousands of contributed packages for R, written by many different authors. Some of these packages implement specialized statistical methods, others give access to data or hardware, and others are designed to complement textbooks. Some (the *recommended* packages) are distributed with every binary distribution of R. Most are available for download from CRAN (<https://CRAN.R-project.org/> and its mirrors) and other repositories such as Bioconductor (<https://www.bioconductor.org/>). The *R FAQ* contains a list of CRAN packages current at the time of release, but the collection of available packages changes very frequently.
### 13.3 Namespaces
Packages have *namespaces*, which do three things: they allow the package writer to hide functions and data that are meant only for internal use, they prevent functions from breaking when a user (or other package writer) picks a name that clashes with one in the package, and they provide a way to refer to an object within a particular package.
For example, `t()` is the transpose function in R, but users might define their own function named `t`. Namespaces prevent the user’s definition from taking precedence, and breaking every function that tries to transpose a matrix.
There are two operators that work with namespaces. The double-colon operator `::` selects definitions from a particular namespace. In the example above, the transpose function will always be available as `base::t`, because it is defined in the `base` package. Only functions that are exported from the package can be retrieved in this way.
The triple-colon operator `:::` may be seen in a few places in R code: it acts like the double-colon operator but also allows access to hidden objects. Users are more likely to use the `getAnywhere()` function, which searches multiple packages.
Packages are often inter-dependent, and loading one may cause others to be automatically loaded. The colon operators described above will also cause automatic loading of the associated package. When packages with namespaces are loaded automatically they are not added to the search list.
14 OS facilities
----------------
R has quite extensive facilities to access the OS under which it is running: this allows it to be used as a scripting language and that ability is much used by R itself, for example to install packages.
Because R’s own scripts need to work across all platforms, considerable effort has gone into make the scripting facilities as platform-independent as is feasible.
### 14.1 Files and directories
There are many functions to manipulate files and directories. Here are pointers to some of the more commonly used ones.
To create an (empty) file or directory, use `file.create` or `dir.create`. (These are the analogues of the POSIX utilities `touch` and `mkdir`.) For temporary files and directories in the R session directory see `tempfile`.
Files can be removed by either `file.remove` or `unlink`: the latter can remove directory trees.
For directory listings use `list.files` (also available as `dir`) or `list.dirs`. These can select files using a regular expression: to select by wildcards use `Sys.glob`.
Many types of information on a filepath (including for example if it is a file or directory) can be found by `file.info`.
There are several ways to find out if a file ‘exists’ (a file can exist on the filesystem and not be visible to the current user). There are functions `file.exists`, `file.access` and `file_test` with various versions of this test: `file_test` is a version of the POSIX `test` command for those familiar with shell scripting.
Function `file.copy` is the R analogue of the POSIX command `cp`.
Choosing files can be done interactively by `file.choose`: the Windows port has the more versatile functions `choose.files` and `choose.dir` and there are similar functions in the **tcltk** package: `tk_choose.files` and `tk_choose.dir`.
Functions `file.show` and `file.edit` will display and edit one or more files in a way appropriate to the R port, using the facilities of a console (such as RGui on Windows or R.app on macOS) if one is in use.
There is some support for *links* in the filesystem: see functions `file.link` and `Sys.readlink`.
### 14.2 Filepaths
With a few exceptions, R relies on the underlying OS functions to manipulate filepaths. Some aspects of this are allowed to depend on the OS, and do, even down to the version of the OS. There are POSIX standards for how OSes should interpret filepaths and many R users assume POSIX compliance: but Windows does not claim to be compliant and other OSes may be less than completely compliant.
The following are some issues which have been encountered with filepaths.
* POSIX filesystems are case-sensitive, so `foo.png` and `Foo.PNG` are different files. However, the defaults on Windows and macOS are to be case-insensitive, and FAT filesystems (commonly used on removable storage) are not normally case-sensitive (and all filepaths may be mapped to lower case).
* Almost all the Windows’ OS services support the use of slash or backslash as the filepath separator, and R converts the known exceptions to the form required by Windows.
* The behaviour of filepaths with a trailing slash is OS-dependent. Such paths are not valid on Windows and should not be expected to work. POSIX-2008 requires such paths to match only directories, but earlier versions allowed them to also match files. So they are best avoided.
* Multiple slashes in filepaths such as `/abc//def` are valid on POSIX filesystems and treated as if there was only one slash. They are *usually* accepted by Windows’ OS functions. However, leading double slashes may have a different meaning.
* Windows’ UNC filepaths (such as `\\server\dir1\dir2\file` and `\\?\UNC\server\dir1\dir2\file`) are not supported, but they may work in some R functions. POSIX filesystems are allowed to treat a leading double slash specially.
* Windows allows filepaths containing drives and relative to the current directory on a drive, e.g. `d:foo/bar` refers to `d:/a/b/c/foo/bar` if the current directory *on drive `d:`* is `/a/b/c`. It is intended that these work, but the use of absolute paths is safer.
Functions `basename` and `dirname` select parts of a file path: the recommended way to assemble a file path from components is `file.path`. Function `pathexpand` does ‘tilde expansion’, substituting values for home directories (the current user’s, and perhaps those of other users).
On filesystems with links, a single file can be referred to by many filepaths. Function `normalizePath` will find a canonical filepath.
Windows has the concepts of short (‘8.3’) and long file names: `normalizePath` will return an absolute path using long file names and `shortPathName` will return a version using short names. The latter does not contain spaces and uses backslash as the separator, so is sometimes useful for exporting names from R.
File *permissions* are a related topic. R has support for the POSIX concepts of read/write/execute permission for owner/group/all but this may be only partially supported on the filesystem, so for example on Windows only read-only files (for the account running the R session) are recognized. Access Control Lists (ACLs) are employed on several filesystems, but do not have an agreed standard and R has no facilities to control them. Use `Sys.chmod` to change permissions.
### 14.3 System commands
Functions `system` and `system2` are used to invoke a system command and optionally collect its output. `system2` is a little more general but its main advantage is that it is easier to write cross-platform code using it.
`system` behaves differently on Windows from other OSes (because the API C call of that name does). Elsewhere it invokes a shell to run the command: the Windows port of R has a function `shell` to do that.
To find out if the OS includes a command, use `Sys.which`, which attempts to do this in a cross-platform way (unfortunately it is not a standard OS service).
Function `shQuote` will quote filepaths as needed for commands in the current OS.
### 14.4 Compression and Archives
Recent versions of R have extensive facilities to read and write compressed files, often transparently. Reading of files in R is to a vey large extent done by *connections*, and the `file` function which is used to open a connection to a file (or a URL) and is able to identify the compression used from the ‘magic’ header of the file.
The type of compression which has been supported for longest is `gzip` compression, and that remains a good general compromise. Files compressed by the earlier Unix `compress` utility can also be read, but these are becoming rare. Two other forms of compression, those of the `bzip2` and `xz` utilities are also available. These generally achieve higher rates of compression (depending on the file, much higher) at the expense of slower decompression and much slower compression.
There is some confusion between `xz` and `lzma` compression (see <https://en.wikipedia.org/wiki/Xz> and <https://en.wikipedia.org/wiki/LZMA>): R can read files compressed by most versions of either.
File archives are single files which contain a collection of files, the most common ones being ‘tarballs’ and zip files as used to distribute R packages. R can list and unpack both (see functions `untar` and `unzip`) and create both (for `zip` with the help of an external program).
Appendix A A sample session
---------------------------
The following session is intended to introduce to you some features of the R environment by using them. Many features of the system will be unfamiliar and puzzling at first, but this puzzlement will soon disappear.
`Start R appropriately for your platform (see [Invoking R](#Invoking-R)).` The R program begins, with a banner.
(Within R code, the prompt on the left hand side will not be shown to avoid confusion.)
`help.start()`
Start the HTML interface to on-line help (using a web browser available at your machine). You should briefly explore the features of this facility with the mouse.
Iconify the help window and move on to the next part.
`x <- rnorm(50)` `y <- rnorm(x)`
Generate two pseudo-random normal vectors of *x*- and *y*-coordinates.
`plot(x, y)`
Plot the points in the plane. A graphics window will appear automatically.
`ls()`
See which R objects are now in the R workspace.
`rm(x, y)`
Remove objects no longer needed. (Clean up).
`x <- 1:20`
Make *x = (1, 2, …, 20)*.
`w <- 1 + sqrt(x)/2`
A ‘weight’ vector of standard deviations.
`dummy <- data.frame(x=x, y= x + rnorm(x)*w)` `dummy`
Make a *data frame* of two columns, *x* and *y*, and look at it.
`fm <- lm(y ~ x, data=dummy)` `summary(fm)`
Fit a simple linear regression and look at the analysis. With `y` to the left of the tilde, we are modelling *y* dependent on *x*.
`fm1 <- lm(y ~ x, data=dummy, weight=1/w^2)` `summary(fm1)`
Since we know the standard deviations, we can do a weighted regression.
`attach(dummy)`
Make the columns in the data frame visible as variables.
`lrf <- lowess(x, y)`
Make a nonparametric local regression function.
`plot(x, y)`
Standard point plot.
`lines(x, lrf$y)`
Add in the local regression.
`abline(0, 1, lty=3)`
The true regression line: (intercept 0, slope 1).
`abline(coef(fm))`
Unweighted regression line.
`abline(coef(fm1), col = "red")`
Weighted regression line.
`detach()`
Remove data frame from the search path.
`plot(fitted(fm), resid(fm),` `xlab="Fitted values",` `ylab="Residuals",` `main="Residuals vs Fitted")`
A standard regression diagnostic plot to check for heteroscedasticity. Can you see it?
`qqnorm(resid(fm), main="Residuals Rankit Plot")`
A normal scores plot to check for skewness, kurtosis and outliers. (Not very useful here.)
`rm(fm, fm1, lrf, x, dummy)` Clean up again.
The next section will look at data from the classical experiment of Michelson to measure the speed of light. This dataset is available in the `morley` object, but we will read it to illustrate the `read.table` function.
`filepath <- system.file("data", "morley.tab" , package="datasets")` `filepath`
Get the path to the data file.
`file.show(filepath)`
Optional. Look at the file.
`mm <- read.table(filepath)` `mm`
Read in the Michelson data as a data frame, and look at it. There are five experiments (column `Expt`) and each has 20 runs (column `Run`) and `sl` is the recorded speed of light, suitably coded.
`mm$Expt <- factor(mm$Expt)` `mm$Run <- factor(mm$Run)`
Change `Expt` and `Run` into factors.
`attach(mm)`
Make the data frame visible at position 2 (the default).
`plot(Expt, Speed, main="Speed of Light Data", xlab="Experiment No.")`
Compare the five experiments with simple boxplots.
`fm <- aov(Speed ~ Run + Expt, data=mm)` `summary(fm)`
Analyze as a randomized block, with ‘runs’ and ‘experiments’ as factors.
`fm0 <- update(fm, . ~ . - Run)` `anova(fm0, fm)`
Fit the sub-model omitting ‘runs’, and compare using a formal analysis of variance.
`detach()` `rm(fm, fm0)`
Clean up before moving on.
We now look at some more graphical features: contour and image plots.
`x <- seq(-pi, pi, len=50)` `y <- x`
*x* is a vector of 50 equally spaced values in the interval [-pi\, pi]. *y* is the same.
`f <- outer(x, y, function(x, y) cos(y)/(1 + x^2))`
*f* is a square matrix, with rows and columns indexed by *x* and *y* respectively, of values of the function cos(y)/(1 + x^2).
`oldpar <- par(no.readonly = TRUE)` `par(pty="s")`
Save the plotting parameters and set the plotting region to “square”.
`contour(x, y, f)` `contour(x, y, f, nlevels=15, add=TRUE)`
Make a contour map of *f*; add in more lines for more detail.
`fa <- (f-t(f))/2`
`fa` is the “asymmetric part” of *f*. (`t()` is transpose).
`contour(x, y, fa, nlevels=15)`
Make a contour plot, …
`par(oldpar)`
… and restore the old graphics parameters.
`image(x, y, f)` `image(x, y, fa)`
Make some high density image plots, (of which you can get hardcopies if you wish), …
`objects(); rm(x, y, f, fa)` … and clean up before moving on.
R can do complex arithmetic, also.
`th <- seq(-pi, pi, len=100)` `z <- exp(1i*th)`
`1i` is used for the complex number *i*.
`par(pty="s")` `plot(z, type="l")`
Plotting complex arguments means plot imaginary versus real parts. This should be a circle.
`w <- rnorm(100) + rnorm(100)*1i`
Suppose we want to sample points within the unit circle. One method would be to take complex numbers with standard normal real and imaginary parts …
`w <- ifelse(Mod(w) > 1, 1/w, w)`
… and to map any outside the circle onto their reciprocal.
`plot(w, xlim=c(-1,1), ylim=c(-1,1), pch="+",xlab="x", ylab="y")` `lines(z)`
All points are inside the unit circle, but the distribution is not uniform.
`w <- sqrt(runif(100))*exp(2*pi*runif(100)*1i)` `plot(w, xlim=c(-1,1), ylim=c(-1,1), pch="+", xlab="x", ylab="y")` `lines(z)`
The second method uses the uniform distribution. The points should now look more evenly spaced over the disc.
`rm(th, w, z)`
Clean up again.
`q()` Quit the R program. You will be asked if you want to save the R workspace, and for an exploratory session like this, you probably do not want to save it.
Appendix B Invoking R
---------------------
Users of R on Windows or macOS should read the OS-specific section first, but command-line use is also supported.
### B.1 Invoking R from the command line
When working at a command line on UNIX or Windows, the command ‘`R`’ can be used both for starting the main R program in the form
```
R [options] [<infile] [>outfile],
```
or, via the `R CMD` interface, as a wrapper to various R tools (e.g., for processing files in R documentation format or manipulating add-on packages) which are not intended to be called “directly”.
At the Windows command-line, `Rterm.exe` is preferred to `R`.
You need to ensure that either the environment variable `TMPDIR` is unset or it points to a valid place to create temporary files and directories.
Most options control what happens at the beginning and at the end of an R session. The startup mechanism is as follows (see also the on-line help for topic ‘`Startup`’ for more information, and the section below for some Windows-specific details).
* Unless `--no-environ` was given, R searches for user and site files to process for setting environment variables. The name of the site file is the one pointed to by the environment variable `R_ENVIRON`; if this is unset, `R\_HOME/etc/Renviron.site` is used (if it exists). The user file is the one pointed to by the environment variable `R_ENVIRON_USER` if this is set; otherwise, files `.Renviron` in the current or in the user’s home directory (in that order) are searched for. These files should contain lines of the form ‘`name=value`’. (See `help("Startup")` for a precise description.) Variables you might want to set include `R_PAPERSIZE` (the default paper size), `R_PRINTCMD` (the default print command) and `R_LIBS` (specifies the list of R library trees searched for add-on packages).
* Then R searches for the site-wide startup profile unless the command line option `--no-site-file` was given. The name of this file is taken from the value of the `R_PROFILE` environment variable. If that variable is unset, the default `R\_HOME/etc/Rprofile.site` is used if this exists.
* Then, unless `--no-init-file` was given, R searches for a user profile and sources it. The name of this file is taken from the environment variable `R_PROFILE_USER`; if unset, a file called `.Rprofile` in the current directory or in the user’s home directory (in that order) is searched for.
* It also loads a saved workspace from file `.RData` in the current directory if there is one (unless `--no-restore` or `--no-restore-data` was specified).
* Finally, if a function `.First()` exists, it is executed. This function (as well as `.Last()` which is executed at the end of the R session) can be defined in the appropriate startup profiles, or reside in `.RData`.
In addition, there are options for controlling the memory available to the R process (see the on-line help for topic ‘`Memory`’ for more information). Users will not normally need to use these unless they are trying to limit the amount of memory used by R.
R accepts the following command-line options.
`--help` `-h`
Print short help message to standard output and exit successfully.
`--version`
Print version information to standard output and exit successfully.
`--encoding=enc`
Specify the encoding to be assumed for input from the console or `stdin`. This needs to be an encoding known to `iconv`: see its help page. (`--encoding enc` is also accepted.) The input is re-encoded to the locale R is running in and needs to be representable in the latter’s encoding (so e.g. you cannot re-encode Greek text in a French locale unless that locale uses the UTF-8 encoding).
`RHOME`
Print the path to the R “home directory” to standard output and exit successfully. Apart from the front-end shell script and the man page, R installation puts everything (executables, packages, etc.) into this directory.
`--save` `--no-save`
Control whether data sets should be saved or not at the end of the R session. If neither is given in an interactive session, the user is asked for the desired behavior when ending the session with `q()`; in non-interactive use one of these must be specified or implied by some other option (see below).
`--no-environ`
Do not read any user file to set environment variables.
`--no-site-file`
Do not read the site-wide profile at startup.
`--no-init-file`
Do not read the user’s profile at startup.
`--restore` `--no-restore` `--no-restore-data`
Control whether saved images (file `.RData` in the directory where R was started) should be restored at startup or not. The default is to restore. (`--no-restore` implies all the specific `--no-restore-\*` options.)
`--no-restore-history`
Control whether the history file (normally file `.Rhistory` in the directory where R was started, but can be set by the environment variable `R_HISTFILE`) should be restored at startup or not. The default is to restore.
`--no-Rconsole`
(Windows only) Prevent loading the `Rconsole` file at startup.
`--vanilla`
Combine `--no-save`, `--no-environ`, `--no-site-file`, `--no-init-file` and `--no-restore`. Under Windows, this also includes `--no-Rconsole`.
`-f file` `--file=file`
(not `Rgui.exe`) Take input from file: ‘`-`’ means `stdin`. Implies `--no-save` unless `--save` has been set. On a Unix-alike, shell metacharacters should be avoided in file (but spaces are allowed).
`-e expression`
(not `Rgui.exe`) Use expression as an input line. One or more `-e` options can be used, but not together with `-f` or `--file`. Implies `--no-save` unless `--save` has been set. (There is a limit of 10,000 bytes on the total length of expressions used in this way. Expressions containing spaces or shell metacharacters will need to be quoted.)
`--no-readline`
(UNIX only) Turn off command-line editing via **readline**. This is useful when running R from within Emacs using the ESS (“Emacs Speaks Statistics”) package. See [The command-line editor](#The-command_002dline-editor), for more information. Command-line editing is enabled for default interactive use (see `--interactive`). This option also affects tilde-expansion: see the help for `path.expand`.
`--min-vsize=N` `--min-nsize=N`
For expert use only: set the initial trigger sizes for garbage collection of vector heap (in bytes) and *cons cells* (number) respectively. Suffix ‘`M`’ specifies megabytes or millions of cells respectively. The defaults are 6Mb and 350k respectively and can also be set by environment variables `R_NSIZE` and `R_VSIZE`.
`--max-ppsize=N`
Specify the maximum size of the pointer protection stack as N locations. This defaults to 10000, but can be increased to allow large and complicated calculations to be done. Currently the maximum value accepted is 100000.
`--max-mem-size=N`
(Windows only) Specify a limit for the amount of memory to be used both for R objects and working areas. This is set by default to the smaller of the amount of physical RAM in the machine and for 32-bit R, 1.5Gb[26](#FOOT26), and must be between 32Mb and the maximum allowed on that version of Windows.
`--quiet` `--silent` `-q`
Do not print out the initial copyright and welcome messages.
`--no-echo`
Make R run as quietly as possible. This option is intended to support programs which use R to compute results for them. It implies `--quiet` and `--no-save`.
`--interactive`
(UNIX only) Assert that R really is being run interactively even if input has been redirected: use if input is from a FIFO or pipe and fed from an interactive program. (The default is to deduce that R is being run interactively if and only if `stdin` is connected to a terminal or `pty`.) Using `-e`, `-f` or `--file` asserts non-interactive use even if `--interactive` is given.
Note that this does not turn on command-line editing.
`--ess`
(Windows only) Set `Rterm` up for use by `R-inferior-mode` in ESS, including asserting interactive use (without the command-line editor) and no buffering of `stdout`.
`--verbose`
Print more information about progress, and in particular set R’s option `verbose` to `TRUE`. R code uses this option to control the printing of diagnostic messages.
`--debugger=name` `-d name`
(UNIX only) Run R through debugger name. For most debuggers (the exceptions are `valgrind` and recent versions of `gdb`), further command line options are disregarded, and should instead be given when starting the R executable from inside the debugger.
`--gui=type` `-g type`
(UNIX only) Use type as graphical user interface (note that this also includes interactive graphics). Currently, possible values for type are ‘`X11`’ (the default) and, provided that ‘`Tcl/Tk`’ support is available, ‘`Tk`’. (For back-compatibility, ‘`x11`’ and ‘`tk`’ are accepted.)
`--arch=name`
(UNIX only) Run the specified sub-architecture.
`--args` This flag does nothing except cause the rest of the command line to be skipped: this can be useful to retrieve values from it with `commandArgs(TRUE)`.
Note that input and output can be redirected in the usual way (using ‘`<`’ and ‘`>`’), but the line length limit of 4095 bytes still applies. Warning and error messages are sent to the error channel (`stderr`).
The command `R CMD` allows the invocation of various tools which are useful in conjunction with R, but not intended to be called “directly”. The general form is
```
R CMD command args
```
where command is the name of the tool and args the arguments passed on to it.
Currently, the following tools are available.
`BATCH` Run R in batch mode. Runs `R --restore --save` with possibly further options (see `?BATCH`).
`COMPILE` (UNIX only) Compile C, C++, Fortran … files for use with R.
`SHLIB` Build shared library for dynamic loading.
`INSTALL` Install add-on packages.
`REMOVE` Remove add-on packages.
`build` Build (that is, package) add-on packages.
`check` Check add-on packages.
`LINK` (UNIX only) Front-end for creating executable programs.
`Rprof` Post-process R profiling files.
`Rdconv` `Rd2txt` Convert Rd format to various other formats, including HTML, LaTeX, plain text, and extracting the examples. `Rd2txt` can be used as shorthand for `Rd2conv -t txt`.
`Rd2pdf` Convert Rd format to PDF.
`Stangle` Extract S/R code from Sweave or other vignette documentation
`Sweave` Process Sweave or other vignette documentation
`Rdiff` Diff R output ignoring headers etc
`config` Obtain configuration information
`javareconf` (Unix only) Update the Java configuration variables
`rtags` (Unix only) Create Emacs-style tag files from C, R, and Rd files
`open` (Windows only) Open a file via Windows’ file associations
`texify` (Windows only) Process (La)TeX files with R’s style files
Use
```
R CMD command --help
```
to obtain usage information for each of the tools accessible via the `R CMD` interface.
In addition, you can use options `--arch=`, `--no-environ`, `--no-init-file`, `--no-site-file` and `--vanilla` between `R` and `CMD`: these affect any R processes run by the tools. (Here `--vanilla` is equivalent to `--no-environ --no-site-file --no-init-file`.) However, note that `R CMD` does not of itself use any R startup files (in particular, neither user nor site `Renviron` files), and all of the R processes run by these tools (except `BATCH`) use `--no-restore`. Most use `--vanilla` and so invoke no R startup files: the current exceptions are `INSTALL`, `REMOVE`, `Sweave` and `SHLIB` (which uses `--no-site-file --no-init-file`).
```
R CMD cmd args
```
for any other executable `cmd` on the path or given by an absolute filepath: this is useful to have the same environment as R or the specific commands run under, for example to run `ldd` or `pdflatex`. Under Windows cmd can be an executable or a batch file, or if it has extension `.sh` or `.pl` the appropriate interpreter (if available) is called to run it.
### B.2 Invoking R under Windows
There are two ways to run R under Windows. Within a terminal window (e.g. `cmd.exe` or a more capable shell), the methods described in the previous section may be used, invoking by `R.exe` or more directly by `Rterm.exe`. For interactive use, there is a console-based GUI (`Rgui.exe`).
The startup procedure under Windows is very similar to that under UNIX, but references to the ‘home directory’ need to be clarified, as this is not always defined on Windows. If the environment variable `R_USER` is defined, that gives the home directory. Next, if the environment variable `HOME` is defined, that gives the home directory. After those two user-controllable settings, R tries to find system defined home directories. It first tries to use the Windows "personal" directory (typically `My Documents` in recent versions of Windows). If that fails, and environment variables `HOMEDRIVE` and `HOMEPATH` are defined (and they normally are) these define the home directory. Failing all those, the home directory is taken to be the starting directory.
You need to ensure that either the environment variables `TMPDIR`, `TMP` and `TEMP` are either unset or one of them points to a valid place to create temporary files and directories.
Environment variables can be supplied as ‘`name=value`’ pairs on the command line.
If there is an argument ending `.RData` (in any case) it is interpreted as the path to the workspace to be restored: it implies `--restore` and sets the working directory to the parent of the named file. (This mechanism is used for drag-and-drop and file association with `RGui.exe`, but also works for `Rterm.exe`. If the named file does not exist it sets the working directory if the parent directory exists.)
The following additional command-line options are available when invoking `RGui.exe`.
`--mdi` `--sdi` `--no-mdi`
Control whether `Rgui` will operate as an MDI program (with multiple child windows within one main window) or an SDI application (with multiple top-level windows for the console, graphics and pager). The command-line setting overrides the setting in the user’s `Rconsole` file.
`--debug` Enable the “Break to debugger” menu item in `Rgui`, and trigger a break to the debugger during command line processing.
Under Windows with `R CMD` you may also specify your own `.bat`, `.exe`, `.sh` or `.pl` file. It will be run under the appropriate interpreter (Perl for `.pl`) with several environment variables set appropriately, including `R_HOME`, `R_OSTYPE`, `PATH`, `BSTINPUTS` and `TEXINPUTS`. For example, if you already have `latex.exe` on your path, then
```
R CMD latex.exe mydoc
```
will run LaTeX on `mydoc.tex`, with the path to R’s `share/texmf` macros appended to `TEXINPUTS`. (Unfortunately, this does not help with the MiKTeX build of LaTeX, but `R CMD texify mydoc` will work in that case.)
### B.3 Invoking R under macOS
There are two ways to run R under macOS. Within a `Terminal.app` window by invoking `R`, the methods described in the first subsection apply. There is also console-based GUI (`R.app`) that by default is installed in the `Applications` folder on your system. It is a standard double-clickable macOS application.
The startup procedure under macOS is very similar to that under UNIX, but `R.app` does not make use of command-line arguments. The ‘home directory’ is the one inside the R.framework, but the startup and current working directory are set as the user’s home directory unless a different startup directory is given in the Preferences window accessible from within the GUI.
### B.4 Scripting with R
If you just want to run a file `foo.R` of R commands, the recommended way is to use `R CMD BATCH foo.R`. If you want to run this in the background or as a batch job use OS-specific facilities to do so: for example in most shells on Unix-alike OSes `R CMD
BATCH foo.R &` runs a background job.
You can pass parameters to scripts via additional arguments on the command line: for example (where the exact quoting needed will depend on the shell in use)
```
R CMD BATCH "--args arg1 arg2" foo.R &
```
will pass arguments to a script which can be retrieved as a character vector by
```
args <- commandArgs(TRUE)
```
This is made simpler by the alternative front-end `Rscript`, which can be invoked by
```
Rscript foo.R arg1 arg2
```
and this can also be used to write executable script files like (at least on Unix-alikes, and in some Windows shells)
```
#! /path/to/Rscript
args <- commandArgs(TRUE)
...
q(status=<exit status code>)
```
If this is entered into a text file `runfoo` and this is made executable (by `chmod 755 runfoo`), it can be invoked for different arguments by
```
runfoo arg1 arg2
```
For further options see `help("Rscript")`. This writes R output to `stdout` and `stderr`, and this can be redirected in the usual way for the shell running the command.
If you do not wish to hardcode the path to `Rscript` but have it in your path (which is normally the case for an installed R except on Windows, but e.g. macOS users may need to add `/usr/local/bin` to their path), use
```
#! /usr/bin/env Rscript
...
```
At least in Bourne and bash shells, the `#!` mechanism does **not** allow extra arguments like `#! /usr/bin/env Rscript --vanilla`.
One thing to consider is what `stdin()` refers to. It is commonplace to write R scripts with segments like
```
chem <- scan(n=24)
2.90 3.10 3.40 3.40 3.70 3.70 2.80 2.50 2.40 2.40 2.70 2.20
5.28 3.37 3.03 3.03 28.95 3.77 3.40 2.20 3.50 3.60 3.70 3.70
```
and `stdin()` refers to the script file to allow such traditional usage. If you want to refer to the process’s `stdin`, use `"stdin"` as a `file` connection, e.g. `scan("stdin", ...)`.
Another way to write executable script files (suggested by François Pinard) is to use a *here document* like
```
#!/bin/sh
[environment variables can be set here]
R --no-echo [other options] <<EOF
R program goes here...
EOF
```
but here `stdin()` refers to the program source and `"stdin"` will not be usable.
Short scripts can be passed to `Rscript` on the command-line *via* the `-e` flag. (Empty scripts are not accepted.)
Note that on a Unix-alike the input filename (such as `foo.R`) should not contain spaces nor shell metacharacters.
Appendix C The command-line editor
----------------------------------
### C.1 Preliminaries
When the GNU **readline** library is available at the time R is configured for compilation under UNIX, an inbuilt command line editor allowing recall, editing and re-submission of prior commands is used. Note that other versions of **readline** exist and may be used by the inbuilt command line editor: this used to happen on macOS.
It can be disabled (useful for usage with ESS [27](#FOOT27)) using the startup option `--no-readline`.
Windows versions of R have somewhat simpler command-line editing: see ‘`Console`’ under the ‘`Help`’ menu of the GUI, and the file `README.Rterm` for command-line editing under `Rterm.exe`.
When using R with GNU[28](#FOOT28) **readline** capabilities, the functions described below are available, as well as others (probably) documented in `man readline` or `info
readline` on your system.
Many of these use either Control or Meta characters. Control characters, such as `Control-m`, are obtained by holding the CTRL down while you press the m key, and are written as `C-m` below. Meta characters, such as `Meta-b`, are typed by holding down META[29](#FOOT29) and pressing b, and written as `M-b` in the following. If your terminal does not have a META key enabled, you can still type Meta characters using two-character sequences starting with `ESC`. Thus, to enter `M-b`, you could type ESCb. The `ESC` character sequences are also allowed on terminals with real Meta keys. Note that case is significant for Meta characters.
Some but not all versions[30](#FOOT30) of **readline** will recognize resizing of the terminal window so this is best avoided.
### C.2 Editing actions
The R program keeps a history of the command lines you type, including the erroneous lines, and commands in your history may be recalled, changed if necessary, and re-submitted as new commands. In Emacs-style command-line editing any straight typing you do while in this editing phase causes the characters to be inserted in the command you are editing, displacing any characters to the right of the cursor. In *vi* mode character insertion mode is started by `M-i` or `M-a`, characters are typed and insertion mode is finished by typing a further ESC. (The default is Emacs-style, and only that is described here: for *vi* mode see the **readline** documentation.)
Pressing the RET command at any time causes the command to be re-submitted.
Other editing actions are summarized in the following table.
### C.3 Command-line editor summary
#### Command recall and vertical motion
`C-p` Go to the previous command (backwards in the history).
`C-n` Go to the next command (forwards in the history).
`C-r text` Find the last command with the text string in it. This can be cancelled by `C-g` (and on some versions of R by `C-c`).
On most terminals, you can also use the up and down arrow keys instead of `C-p` and `C-n`, respectively.
#### Horizontal motion of the cursor
`C-a` Go to the beginning of the command.
`C-e` Go to the end of the line.
`M-b` Go back one word.
`M-f` Go forward one word.
`C-b` Go back one character.
`C-f` Go forward one character.
On most terminals, you can also use the left and right arrow keys instead of `C-b` and `C-f`, respectively.
#### Editing and re-submission
`text` Insert text at the cursor.
`C-f text` Append text after the cursor.
`DEL` Delete the previous character (left of the cursor).
`C-d` Delete the character under the cursor.
`M-d` Delete the rest of the word under the cursor, and “save” it.
`C-k` Delete from cursor to end of command, and “save” it.
`C-y` Insert (yank) the last “saved” text here.
`C-t` Transpose the character under the cursor with the next.
`M-l` Change the rest of the word to lower case.
`M-c` Change the rest of the word to upper case.
`RET` Re-submit the command to R.
The final RET terminates the command line editing sequence.
The **readline** key bindings can be customized in the usual way *via* a `~/.inputrc` file. These customizations can be conditioned on application `R`, that is by including a section like
```
$if R
"\C-xd": "q('no')\n"
$endif
```
Appendix F References
---------------------
D. M. Bates and D. G. Watts (1988), *Nonlinear Regression Analysis and Its Applications.* John Wiley & Sons, New York.
Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), *The New S Language.* Chapman & Hall, New York. This book is often called the “*Blue Book*”.
John M. Chambers and Trevor J. Hastie eds. (1992), *Statistical Models in S.* Chapman & Hall, New York. This is also called the “*White Book*”.
John M. Chambers (1998) *Programming with Data*. Springer, New York. This is also called the “*Green Book*”.
A. C. Davison and D. V. Hinkley (1997), *Bootstrap Methods and Their Applications*, Cambridge University Press.
Annette J. Dobson (1990), *An Introduction to Generalized Linear Models*, Chapman and Hall, London.
Peter McCullagh and John A. Nelder (1989), *Generalized Linear Models.* Second edition, Chapman and Hall, London.
John A. Rice (1995), *Mathematical Statistics and Data Analysis.* Second edition. Duxbury Press, Belmont, CA.
S. D. Silvey (1970), *Statistical Inference.* Penguin, London.
#### Footnotes
**(1)** ACM Software Systems award, 1998: <https://awards.acm.org/award_winners/chambers_6640862.cfm>.
**(2)** For portable R code (including that to be used in R packages) only A–Za–z0–9 should be used.
**(3)** **not** inside strings, nor within the argument list of a function definition
**(4)** some of the consoles will not allow you to enter more, and amongst those which do some will silently discard the excess and some will use it as the start of the next line.
**(5)** of unlimited length.
**(6)** The leading “dot” in this file name makes it *invisible* in normal file listings in UNIX, and in default GUI file listings on macOS and Windows.
**(7)** With other than vector types of argument, such as `list` mode arguments, the action of `c()` is rather different. See [Concatenating lists](#Concatenating-lists).
**(8)** Actually, it is still available as `.Last.value` before any other statements are executed.
**(9)** `paste(..., collapse=ss)` joins the arguments into a single character string putting ss in between, e.g., `ss <- "|"`. There are more tools for character manipulation, see the help for `sub` and `substring`.
**(10)** *numeric* mode is actually an amalgam of two distinct modes, namely *integer* and *double* precision, as explained in the manual.
**(11)** Note however that `length(object)` does not always contain intrinsic useful information, e.g., when `object` is a function.
**(12)** In general, coercion from numeric to character and back again will not be exactly reversible, because of roundoff errors in the character representation.
**(13)** A different style using ‘formal’ or ‘S4’ classes is provided in package `methods`.
**(14)** Readers should note that there are eight states and territories in Australia, namely the Australian Capital Territory, New South Wales, the Northern Territory, Queensland, South Australia, Tasmania, Victoria and Western Australia.
**(15)** Note that `tapply()` also works in this case when its second argument is not a factor, e.g., ‘``tapply(incomes, state)``’, and this is true for quite a few other functions, since arguments are *coerced* to factors when necessary (using `as.factor()`).
**(16)** Note that `x %*% x` is ambiguous, as it could mean either x’x or x x’, where x is the column form. In such cases the smaller matrix seems implicitly to be the interpretation adopted, so the scalar x’x is in this case the result. The matrix x x’ may be calculated either by `cbind(x)
%*% x` or `x %*% rbind(x)` since the result of `rbind()` or `cbind()` is always a matrix. However, the best way to compute x’x or x x’ is `crossprod(x)` or `x %o% x` respectively.
**(17)** Even better would be to form a matrix square root B with A = BB’ and find the squared length of the solution of By = x , perhaps using the Cholesky or eigen decomposition of A.
**(18)** Conversion of character columns to factors is overridden using the `stringsAsFactors` argument to the `data.frame()` function.
**(19)** See the on-line help for `autoload` for the meaning of the second term.
**(20)** Under UNIX, the utilities `sed` or`awk` can be used.
**(21)** to be discussed later, or use `xyplot` from package [**lattice**](https://CRAN.R-project.org/package=lattice).
**(22)** See also the methods described in [Statistical models in R](#Statistical-models-in-R)
**(23)** In some sense this mimics the behavior in S-PLUS since in S-PLUS this operator always creates or assigns to a global variable.
**(24)** So it is hidden under UNIX.
**(25)** Some graphics parameters such as the size of the current device are for information only.
**(26)** 2.5Gb on versions of Windows that support 3Gb per process and have the support enabled: see the `rw-FAQ` Q2.9; 3.5Gb on most 64-bit versions of Windows.
**(27)** The ‘Emacs Speaks Statistics’ package; see the URL <https://ESS.R-project.org/>
**(28)** It is possible to build R using an emulation of GNU **readline**, such as one based on NetBSD’s **editline** (also known as **libedit**), in which case only a subset of the capabilities may be provided.
**(29)** On a PC keyboard this is usually the Alt key, occasionally the ‘Windows’ key. On a Mac keyboard normally no meta key is available.
**(30)** In particular, not versions 6.3 or later: this is worked around as from R 3.4.0.
| programming_docs |
r R Data Import/Export R Data Import/Export
====================
This is a guide to importing and exporting data to and from R.
This manual is for R, version 4.1.0 (2021-05-18).
Copyright © 2000–2021 R Core Team
> Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
>
> Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
>
> Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the R Core Team.
>
>
>
Acknowledgements
----------------
The relational databases part of this manual is based in part on an earlier manual by Douglas Bates and Saikat DebRoy. The principal author of this manual was Brian Ripley.
Many volunteers have contributed to the packages used here. The principal authors of the packages mentioned are
>
> [**DBI**](https://CRAN.R-project.org/package=DBI):
> David A. James
>
>
> [**dataframes2xls**](https://CRAN.R-project.org/package=dataframes2xls):
> Guido van Steen
>
>
> [**foreign**](https://CRAN.R-project.org/package=foreign):
> Thomas Lumley, Saikat DebRoy, Douglas Bates, Duncan Murdoch and Roger Bivand
>
>
> [**gdata**](https://CRAN.R-project.org/package=gdata):
> Gregory R. Warnes
>
>
> [**ncdf4**](https://CRAN.R-project.org/package=ncdf4):
> David Pierce
>
>
> [**rJava**](https://CRAN.R-project.org/package=rJava):
> Simon Urbanek
>
>
> [**RJDBC**](https://CRAN.R-project.org/package=RJDBC):
> Simon Urbanek
>
>
> [**RMySQL**](https://CRAN.R-project.org/package=RMySQL):
> David James and Saikat DebRoy
>
>
> [**RNetCDF**](https://CRAN.R-project.org/package=RNetCDF):
> Pavel Michna
>
>
> [**RODBC**](https://CRAN.R-project.org/package=RODBC):
> Michael Lapsley and Brian Ripley
>
>
> [**ROracle**](https://CRAN.R-project.org/package=ROracle):
> David A. James
>
>
> [**RPostgreSQL**](https://CRAN.R-project.org/package=RPostgreSQL):
> Sameer Kumar Prayaga and Tomoaki Nishiyama
>
>
> **RSPerl**:
> Duncan Temple Lang
>
>
> **RSPython**:
> Duncan Temple Lang
>
>
> [**RSQLite**](https://CRAN.R-project.org/package=RSQLite):
> David A. James
>
>
> **SJava**:
> John Chambers and Duncan Temple Lang
>
>
> [**WriteXLS**](https://CRAN.R-project.org/package=WriteXLS):
> Marc Schwartz
>
>
> [**XLConnect**](https://CRAN.R-project.org/package=XLConnect):
> Mirai Solutions GmbH
>
>
> [**XML**](https://CRAN.R-project.org/package=XML): Duncan Temple Lang
>
>
Brian Ripley is the author of the support for connections.
1 Introduction
--------------
Reading data into a statistical system for analysis and exporting the results to some other system for report writing can be frustrating tasks that can take far more time than the statistical analysis itself, even though most readers will find the latter far more appealing.
This manual describes the import and export facilities available either in R itself or via packages which are available from CRAN or elsewhere.
Unless otherwise stated, everything described in this manual is (at least in principle) available on all platforms running R.
In general, statistical systems like R are not particularly well suited to manipulations of large-scale data. Some other systems are better than R at this, and part of the thrust of this manual is to suggest that rather than duplicating functionality in R we can make another system do the work! (For example Therneau & Grambsch (2000) commented that they preferred to do data manipulation in SAS and then use package [**survival**](https://CRAN.R-project.org/package=survival) in S for the analysis.) Database manipulation systems are often very suitable for manipulating and extracting data: several packages to interact with DBMSs are discussed here.
There are packages to allow functionality developed in languages such as `Java`, `perl` and `python` to be directly integrated with R code, making the use of facilities in these languages even more appropriate. (See the [**rJava**](https://CRAN.R-project.org/package=rJava) package from CRAN.)
It is also worth remembering that R like S comes from the Unix tradition of small re-usable tools, and it can be rewarding to use tools such as `awk` and `perl` to manipulate data before import or after export. The case study in Becker, Chambers & Wilks (1988, Chapter 9) is an example of this, where Unix tools were used to check and manipulate the data before input to S. The traditional Unix tools are now much more widely available, including for Windows.
This manual was first written in 2000, and the number of scope of R packages has increased a hundredfold since. For specialist data formats it is worth searching to see if a suitable package already exists.
### 1.1 Imports
The easiest form of data to import into R is a simple text file, and this will often be acceptable for problems of small or medium scale. The primary function to import from a text file is `scan`, and this underlies most of the more convenient functions discussed in [Spreadsheet-like data](#Spreadsheet_002dlike-data).
However, all statistical consultants are familiar with being presented by a client with a memory stick (formerly, a floppy disc or CD-R) of data in some proprietary binary format, for example ‘an Excel spreadsheet’ or ‘an SPSS file’. Often the simplest thing to do is to use the originating application to export the data as a text file (and statistical consultants will have copies of the most common applications on their computers for that purpose). However, this is not always possible, and [Importing from other statistical systems](#Importing-from-other-statistical-systems) discusses what facilities are available to access such files directly from R. For Excel spreadsheets, the available methods are summarized in [Reading Excel spreadsheets](#Reading-Excel-spreadsheets).
In a few cases, data have been stored in a binary form for compactness and speed of access. One application of this that we have seen several times is imaging data, which is normally stored as a stream of bytes as represented in memory, possibly preceded by a header. Such data formats are discussed in [Binary files](#Binary-files) and [Binary connections](#Binary-connections).
For much larger databases it is common to handle the data using a database management system (DBMS). There is once again the option of using the DBMS to extract a plain file, but for many such DBMSs the extraction operation can be done directly from an R package: See [Relational databases](#Relational-databases). Importing data via network connections is discussed in [Network interfaces](#Network-interfaces).
#### 1.1.1 Encodings
Unless the file to be imported from is entirely in ASCII, it is usually necessary to know how it was encoded. For text files, a good way to find out something about its structure is the `file` command-line tool (for Windows, included in `Rtools`). This reports something like
```
text.Rd: UTF-8 Unicode English text
text2.dat: ISO-8859 English text
text3.dat: Little-endian UTF-16 Unicode English character data,
with CRLF line terminators
intro.dat: UTF-8 Unicode text
intro.dat: UTF-8 Unicode (with BOM) text
```
Modern Unix-alike systems, including macOS, are likely to produce UTF-8 files. Windows may produce what it calls ‘Unicode’ files (`UCS-2LE` or just possibly `UTF-16LE`[1](#FOOT1)). Otherwise most files will be in a 8-bit encoding unless from a Chinese/Japanese/Korean locale (which have a wide range of encodings in common use). It is not possible to automatically detect with certainty which 8-bit encoding (although guesses may be possible and `file` may guess as it did in the example above), so you may simply have to ask the originator for some clues (e.g. ‘Russian on Windows’).
‘BOMs’ (Byte Order Marks, <https://en.wikipedia.org/wiki/Byte_order_mark>) cause problems for Unicode files. In the Unix world BOMs are rarely used, whereas in the Windows world they almost always are for UCS-2/UTF-16 files, and often are for UTF-8 files. The `file` utility will not even recognize UCS-2 files without a BOM, but many other utilities will refuse to read files with a BOM and the IANA standards for `UTF-16LE` and `UTF-16BE` prohibit it. We have too often been reduced to looking at the file with the command-line utility `od` or a hex editor to work out its encoding.
Note that `utf8` is not a valid encoding name (`UTF-8` is), and `macintosh` is the most portable name for what is sometimes called ‘Mac Roman’ encoding.
### 1.2 Export to text files
Exporting results from R is usually a less contentious task, but there are still a number of pitfalls. There will be a target application in mind, and often a text file will be the most convenient interchange vehicle. (If a binary file is required, see [Binary files](#Binary-files).)
Function `cat` underlies the functions for exporting data. It takes a `file` argument, and the `append` argument allows a text file to be written via successive calls to `cat`. Better, especially if this is to be done many times, is to open a `file` connection for writing or appending, and `cat` to that connection, then `close` it.
The most common task is to write a matrix or data frame to file as a rectangular grid of numbers, possibly with row and column labels. This can be done by the functions `write.table` and `write`. Function `write` just writes out a matrix or vector in a specified number of columns (and transposes a matrix). Function `write.table` is more convenient, and writes out a data frame (or an object that can be coerced to a data frame) with row and column labels.
There are a number of issues that need to be considered in writing out a data frame to a text file.
1. **Precision** Most of the conversions of real/complex numbers done by these functions is to full precision, but those by `write` are governed by the current setting of `options(digits)`. For more control, use `format` on a data frame, possibly column-by-column.
2. **Header line** R prefers the header line to have no entry for the row names, so the file looks like
```
dist climb time
Greenmantle 2.5 650 16.083
...
```
Some other systems require a (possibly empty) entry for the row names, which is what `write.table` will provide if argument `col.names = NA` is specified. Excel is one such system.
3. **Separator** A common field separator to use in the file is a comma, as that is unlikely to appear in any of the fields in English-speaking countries. Such files are known as CSV (comma separated values) files, and wrapper function `write.csv` provides appropriate defaults. In some locales the comma is used as the decimal point (set this in `write.table` by `dec = ","`) and there CSV files use the semicolon as the field separator: use `write.csv2` for appropriate defaults. There is an IETF standard for CSV files (which mandates commas and CRLF line endings, for which use `eol = "\r\n"`), RFC4180 (see <https://tools.ietf.org/html/rfc4180>), but what is more important in practice is that the file is readable by the application it is targeted at.
Using a semicolon or tab (`sep = "\t"`) are probably the safest options.
4. **Missing values** By default missing values are output as `NA`, but this may be changed by argument `na`. Note that `NaN`s are treated as `NA` by `write.table`, but not by `cat` nor `write`.
5. **Quoting strings** By default strings are quoted (including the row and column names). Argument `quote` controls if character and factor variables are quoted: some programs, for example **Mondrian** (<https://en.wikipedia.org/wiki/Mondrian_(software)>), do not accept quoted strings.
Some care is needed if the strings contain embedded quotes. Three useful forms are
```
> df <- data.frame(a = I("a \" quote"))
> write.table(df)
"a"
"1" "a \" quote"
> write.table(df, qmethod = "double")
"a"
"1" "a "" quote"
> write.table(df, quote = FALSE, sep = ",")
a
1,a " quote
```
The second is the form of escape commonly used by spreadsheets.
6. **Encodings** Text files do not contain metadata on their encodings, so for non-ASCII data the file needs to be targetted to the application intended to read it. All of these functions can write to a *connection* which allows an encoding to be specified for the file, and `write.table` has a `fileEncoding` argument to make this easier.
The hard part is to know what file encoding to use. For use on Windows, it is best to use what Windows calls ‘Unicode’[2](#FOOT2), that is `"UTF-16LE"`. Using UTF-8 is a good way to make portable files that will not easily be confused with any other encoding, but even macOS applications (where UTF-8 is the system encoding) may not recognize them, and Windows applications are most unlikely to. Apparently Excel:mac 2004/8 expected `.csv` files in `"macroman"` encoding (the encoding used in much earlier versions of Mac OS).
Function `write.matrix` in package [**MASS**](https://CRAN.R-project.org/package=MASS) provides a specialized interface for writing matrices, with the option of writing them in blocks and thereby reducing memory usage.
It is possible to use `sink` to divert the standard R output to a file, and thereby capture the output of (possibly implicit) `print` statements. This is not usually the most efficient route, and the `options(width)` setting may need to be increased.
Function `write.foreign` in package [**foreign**](https://CRAN.R-project.org/package=foreign) uses `write.table` to produce a text file and also writes a code file that will read this text file into another statistical package. There is currently support for export to `SAS`, `SPSS` and `Stata`.
### 1.3 XML
When reading data from text files, it is the responsibility of the user to know and to specify the conventions used to create that file, e.g. the comment character, whether a header line is present, the value separator, the representation for missing values (and so on) described in [Export to text files](#Export-to-text-files). A markup language which can be used to describe not only content but also the structure of the content can make a file self-describing, so that one need not provide these details to the software reading the data.
The eXtensible Markup Language – more commonly known simply as XML – can be used to provide such structure, not only for standard datasets but also more complex data structures. XML is becoming extremely popular and is emerging as a standard for general data markup and exchange. It is being used by different communities to describe geographical data such as maps, graphical displays, mathematics and so on.
XML provides a way to specify the file’s encoding, e.g.
```
<?xml version="1.0" encoding="UTF-8"?>
```
although it does not require it.
The [**XML**](https://CRAN.R-project.org/package=XML) package provides general facilities for reading and writing XML documents within R. Package [**StatDataML**](https://CRAN.R-project.org/package=StatDataML) on CRAN is one example building on [**XML**](https://CRAN.R-project.org/package=XML). Another interface to the **libxml2** C library is provided by package [**xml2**](https://CRAN.R-project.org/package=xml2).
yaml is another system for structuring text data, with emphasis on human-readability: it is supported by package [**yaml**](https://CRAN.R-project.org/package=yaml).
2 Spreadsheet-like data
-----------------------
In [Export to text files](#Export-to-text-files) we saw a number of variations on the format of a spreadsheet-like text file, in which the data are presented in a rectangular grid, possibly with row and column labels. In this section we consider importing such files into R.
### 2.1 Variations on `read.table`
The function `read.table` is the most convenient way to read in a rectangular grid of data. Because of the many possibilities, there are several other functions that call `read.table` but change a group of default arguments.
Beware that `read.table` is an inefficient way to read in very large numerical matrices: see `scan` below.
Some of the issues to consider are:
1. **Encoding** If the file contains non-ASCII character fields, ensure that it is read in the correct encoding. This is mainly an issue for reading Latin-1 files in a UTF-8 locale, which can be done by something like
```
read.table("file.dat", fileEncoding="latin1")
```
Note that this will work in any locale which can represent Latin-1 strings, but not many Greek/Russian/Chinese/Japanese … locales.
2. **Header line** We recommend that you specify the `header` argument explicitly, Conventionally the header line has entries only for the columns and not for the row labels, so is one field shorter than the remaining lines. (If R sees this, it sets `header = TRUE`.) If presented with a file that has a (possibly empty) header field for the row labels, read it in by something like
```
read.table("file.dat", header = TRUE, row.names = 1)
```
Column names can be given explicitly via the `col.names`; explicit names override the header line (if present).
3. **Separator** Normally looking at the file will determine the field separator to be used, but with white-space separated files there may be a choice between the default `sep = ""` which uses any white space (spaces, tabs or newlines) as a separator, `sep = " "` and `sep = "\t"`. Note that the choice of separator affects the input of quoted strings.
If you have a tab-delimited file containing empty fields be sure to use `sep = "\t"`.
4. **Quoting** By default character strings can be quoted by either ‘`"`’ or ‘`'`’, and in each case all the characters up to a matching quote are taken as part of the character string. The set of valid quoting characters (which might be none) is controlled by the `quote` argument. For `sep = "\n"` the default is changed to `quote =
""`.
If no separator character is specified, quotes can be escaped within quoted strings by immediately preceding them by ‘`\`’, C-style.
If a separator character is specified, quotes can be escaped within quoted strings by doubling them as is conventional in spreadsheets. For example
```
'One string isn''t two',"one more"
```
can be read by
```
read.table("testfile", sep = ",")
```
This does not work with the default separator.
5. **Missing values** By default the file is assumed to contain the character string `NA` to represent missing values, but this can be changed by the argument `na.strings`, which is a vector of one or more character representations of missing values.
Empty fields in numeric columns are also regarded as missing values.
In numeric columns, the values `NaN`, `Inf` and `-Inf` are accepted.
6. **Unfilled lines** It is quite common for a file exported from a spreadsheet to have all trailing empty fields (and their separators) omitted. To read such files set `fill = TRUE`.
7. **White space in character fields** If a separator is specified, leading and trailing white space in character fields is regarded as part of the field. To strip the space, use argument `strip.white = TRUE`.
8. **Blank lines** By default, `read.table` ignores empty lines. This can be changed by setting `blank.lines.skip = FALSE`, which will only be useful in conjunction with `fill = TRUE`, perhaps to use blank rows to indicate missing cases in a regular layout.
9. **Classes for the variables** Unless you take any special action, `read.table` reads all the columns as character vectors and then tries to select a suitable class for each variable in the data frame. It tries in turn `logical`, `integer`, `numeric` and `complex`, moving on if any entry is not missing and cannot be converted.[3](#FOOT3) If all of these fail, the variable is converted to a factor.
Arguments `colClasses` and `as.is` provide greater control. Specifying `as.is = TRUE` suppresses conversion of character vectors to factors (only). Using `colClasses` allows the desired class to be set for each column in the input: it will be faster and use less memory.
Note that `colClasses` and `as.is` are specified *per* column, not *per* variable, and so include the column of row names (if any).
10. **Comments** By default, `read.table` uses ‘`#`’ as a comment character, and if this is encountered (except in quoted strings) the rest of the line is ignored. Lines containing only white space and a comment are treated as blank lines.
If it is known that there will be no comments in the data file, it is safer (and may be faster) to use `comment.char = ""`.
11. **Escapes** Many OSes have conventions for using backslash as an escape character in text files, but Windows does not (and uses backslash in path names). It is optional in R whether such conventions are applied to data files.
Both `read.table` and `scan` have a logical argument `allowEscapes`. This is false by default, and backslashes are then only interpreted as (under circumstances described above) escaping quotes. If this set to be true, C-style escapes are interpreted, namely the control characters `\a, \b, \f, \n, \r, \t, \v` and octal and hexadecimal representations like `\040` and `\0x2A`. Any other escaped character is treated as itself, including backslash. Note that Unicode escapes such as `\uxxxx` are never interpreted.
12. **Encoding** This can be specified by the `fileEncoding` argument, for example
```
fileEncoding = "UCS-2LE" # Windows ‘Unicode’ files
fileEncoding = "UTF-8"
```
If you know (correctly) the file’s encoding this will almost always work. However, we know of one exception, UTF-8 files with a BOM. Some people claim that UTF-8 files should never have a BOM, but some software (apparently including Excel:mac) uses them, and many Unix-alike OSes do not accept them. So faced with a file which `file` reports as
```
intro.dat: UTF-8 Unicode (with BOM) text
```
it can be read on Windows by
```
read.table("intro.dat", fileEncoding = "UTF-8")
```
but on a Unix-alike might need
```
read.table("intro.dat", fileEncoding = "UTF-8-BOM")
```
(This would most likely work without specifying an encoding in a UTF-8 locale.)
Convenience functions `read.csv` and `read.delim` provide arguments to `read.table` appropriate for CSV and tab-delimited files exported from spreadsheets in English-speaking locales. The variations `read.csv2` and `read.delim2` are appropriate for use in those locales where the comma is used for the decimal point and (for `read.csv2`) for spreadsheets which use semicolons to separate fields.
If the options to `read.table` are specified incorrectly, the error message will usually be of the form
```
Error in scan(file = file, what = what, sep = sep, :
line 1 did not have 5 elements
```
or
```
Error in read.table("files.dat", header = TRUE) :
more columns than column names
```
This may give enough information to find the problem, but the auxiliary function `count.fields` can be useful to investigate further.
Efficiency can be important when reading large data grids. It will help to specify `comment.char = ""`, `colClasses` as one of the atomic vector types (logical, integer, numeric, complex, character or perhaps raw) for each column, and to give `nrows`, the number of rows to be read (and a mild over-estimate is better than not specifying this at all). See the examples in later sections.
### 2.2 Fixed-width-format files
Sometimes data files have no field delimiters but have fields in pre-specified columns. This was very common in the days of punched cards, and is still sometimes used to save file space.
Function `read.fwf` provides a simple way to read such files, specifying a vector of field widths. The function reads the file into memory as whole lines, splits the resulting character strings, writes out a temporary tab-separated file and then calls `read.table`. This is adequate for small files, but for anything more complicated we recommend using the facilities of a language like `perl` to pre-process the file.
Function `read.fortran` is a similar function for fixed-format files, using Fortran-style column specifications.
### 2.3 Data Interchange Format (DIF)
An old format sometimes used for spreadsheet-like data is DIF, or Data Interchange format.
Function `read.DIF` provides a simple way to read such files. It takes arguments similar to `read.table` for assigning types to each of the columns.
On Windows, spreadsheet programs often store spreadsheet data copied to the clipboard in this format; `read.DIF("clipboard")` can read it from there directly. It is slightly more robust than `read.table("clipboard")` in handling spreadsheets with empty cells.
### 2.4 Using `scan` directly
Both `read.table` and `read.fwf` use `scan` to read the file, and then process the results of `scan`. They are very convenient, but sometimes it is better to use `scan` directly.
Function `scan` has many arguments, most of which we have already covered under `read.table`. The most crucial argument is `what`, which specifies a list of modes of variables to be read from the file. If the list is named, the names are used for the components of the returned list. Modes can be numeric, character or complex, and are usually specified by an example, e.g. `0`, `""` or `0i`. For example
```
cat("2 3 5 7", "11 13 17 19", file="ex.dat", sep="\n")
scan(file="ex.dat", what=list(x=0, y="", z=0), flush=TRUE)
```
returns a list with three components and discards the fourth column in the file.
There is a function `readLines` which will be more convenient if all you want is to read whole lines into R for further processing.
One common use of `scan` is to read in a large matrix. Suppose file `matrix.dat` just contains the numbers for a 200 x 2000 matrix. Then we can use
```
A <- matrix(scan("matrix.dat", n = 200*2000), 200, 2000, byrow = TRUE)
```
On one test this took 1 second (under Linux, 3 seconds under Windows on the same machine) whereas
```
A <- as.matrix(read.table("matrix.dat"))
```
took 10 seconds (and more memory), and
```
A <- as.matrix(read.table("matrix.dat", header = FALSE, nrows = 200,
comment.char = "", colClasses = "numeric"))
```
took 7 seconds. The difference is almost entirely due to the overhead of reading 2000 separate short columns: were they of length 2000, `scan` took 9 seconds whereas `read.table` took 18 if used efficiently (in particular, specifying `colClasses`) and 125 if used naively.
Note that timings can depend on the type read and the data. Consider reading a million distinct integers:
```
writeLines(as.character((1+1e6):2e6), "ints.dat")
xi <- scan("ints.dat", what=integer(0), n=1e6) # 0.77s
xn <- scan("ints.dat", what=numeric(0), n=1e6) # 0.93s
xc <- scan("ints.dat", what=character(0), n=1e6) # 0.85s
xf <- as.factor(xc) # 2.2s
DF <- read.table("ints.dat") # 4.5s
```
and a million examples of a small set of codes:
```
code <- c("LMH", "SJC", "CHCH", "SPC", "SOM")
writeLines(sample(code, 1e6, replace=TRUE), "code.dat")
y <- scan("code.dat", what=character(0), n=1e6) # 0.44s
yf <- as.factor(y) # 0.21s
DF <- read.table("code.dat") # 4.9s
DF <- read.table("code.dat", nrows=1e6) # 3.6s
```
Note that these timings depend heavily on the operating system (the basic reads in Windows take at least as twice as long as these Linux times) and on the precise state of the garbage collector.
### 2.5 Re-shaping data
Sometimes spreadsheet data is in a compact format that gives the covariates for each subject followed by all the observations on that subject. R’s modelling functions need observations in a single column. Consider the following sample of data from repeated MRI brain measurements
```
Status Age V1 V2 V3 V4
P 23646 45190 50333 55166 56271
CC 26174 35535 38227 37911 41184
CC 27723 25691 25712 26144 26398
CC 27193 30949 29693 29754 30772
CC 24370 50542 51966 54341 54273
CC 28359 58591 58803 59435 61292
CC 25136 45801 45389 47197 47126
```
There are two covariates and up to four measurements on each subject. The data were exported from Excel as a file `mr.csv`.
We can use `stack` to help manipulate these data to give a single response.
```
zz <- read.csv("mr.csv", strip.white = TRUE)
zzz <- cbind(zz[gl(nrow(zz), 1, 4*nrow(zz)), 1:2], stack(zz[, 3:6]))
```
with result
```
Status Age values ind
X1 P 23646 45190 V1
X2 CC 26174 35535 V1
X3 CC 27723 25691 V1
X4 CC 27193 30949 V1
X5 CC 24370 50542 V1
X6 CC 28359 58591 V1
X7 CC 25136 45801 V1
X11 P 23646 50333 V2
...
```
Function `unstack` goes in the opposite direction, and may be useful for exporting data.
Another way to do this is to use the function `reshape`, by
```
> reshape(zz, idvar="id",timevar="var",
varying=list(c("V1","V2","V3","V4")),direction="long")
Status Age var V1 id
1.1 P 23646 1 45190 1
2.1 CC 26174 1 35535 2
3.1 CC 27723 1 25691 3
4.1 CC 27193 1 30949 4
5.1 CC 24370 1 50542 5
6.1 CC 28359 1 58591 6
7.1 CC 25136 1 45801 7
1.2 P 23646 2 50333 1
2.2 CC 26174 2 38227 2
...
```
The `reshape` function has a more complicated syntax than `stack` but can be used for data where the ‘long’ form has more than the one column in this example. With `direction="wide"`, `reshape` can also perform the opposite transformation.
Some people prefer the tools in packages [**reshape**](https://CRAN.R-project.org/package=reshape), [**reshape2**](https://CRAN.R-project.org/package=reshape2) and [**plyr**](https://CRAN.R-project.org/package=plyr).
### 2.6 Flat contingency tables
Displaying higher-dimensional contingency tables in array form typically is rather inconvenient. In categorical data analysis, such information is often represented in the form of bordered two-dimensional arrays with leading rows and columns specifying the combination of factor levels corresponding to the cell counts. These rows and columns are typically “ragged” in the sense that labels are only displayed when they change, with the obvious convention that rows are read from top to bottom and columns are read from left to right. In R, such “flat” contingency tables can be created using `ftable`, which creates objects of class `"ftable"` with an appropriate print method.
As a simple example, consider the R standard data set `UCBAdmissions` which is a 3-dimensional contingency table resulting from classifying applicants to graduate school at UC Berkeley for the six largest departments in 1973 classified by admission and sex.
```
> data(UCBAdmissions)
> ftable(UCBAdmissions)
Dept A B C D E F
Admit Gender
Admitted Male 512 353 120 138 53 22
Female 89 17 202 131 94 24
Rejected Male 313 207 205 279 138 351
Female 19 8 391 244 299 317
```
The printed representation is clearly more useful than displaying the data as a 3-dimensional array.
There is also a function `read.ftable` for reading in flat-like contingency tables from files. This has additional arguments for dealing with variants on how exactly the information on row and column variables names and levels is represented. The help page for `read.ftable` has some useful examples. The flat tables can be converted to standard contingency tables in array form using `as.table`.
Note that flat tables are characterized by their “ragged” display of row (and maybe also column) labels. If the full grid of levels of the row variables is given, one should instead use `read.table` to read in the data, and create the contingency table from this using `xtabs`.
3 Importing from other statistical systems
------------------------------------------
In this chapter we consider the problem of reading a binary data file written by another statistical system. This is often best avoided, but may be unavoidable if the originating system is not available.
In all cases the facilities described were written for data files from specific versions of the other system (often in the early 2000s), and have not necessarily been updated for the most recent versions of the other system.
### 3.1 EpiInfo, Minitab, S-PLUS, SAS, SPSS, Stata, Systat
The recommended package [**foreign**](https://CRAN.R-project.org/package=foreign) provides import facilities for files produced by these statistical systems, and for export to Stata. In some cases these functions may require substantially less memory than `read.table` would. `write.foreign` (See [Export to text files](#Export-to-text-files)) provides an export mechanism with support currently for `SAS`, `SPSS` and `Stata`.
EpiInfo versions 5 and 6 stored data in a self-describing fixed-width text format. `read.epiinfo` will read these `.REC` files into an R data frame. EpiData also produces data in this format.
Function `read.mtp` imports a ‘Minitab Portable Worksheet’. This returns the components of the worksheet as an R list.
Function `read.xport` reads a file in SAS Transport (XPORT) format and return a list of data frames. If SAS is available on your system, function `read.ssd` can be used to create and run a SAS script that saves a SAS permanent dataset (`.ssd` or `.sas7bdat`) in Transport format. It then calls `read.xport` to read the resulting file. (Package [**Hmisc**](https://CRAN.R-project.org/package=Hmisc) has a similar function `sas.get`, also running SAS.) For those without access to SAS but running on Windows, the SAS System Viewer (a zero-cost download) can be used to open SAS datasets and export them to e.g. `.csv` format.
Function `read.S` which can read binary objects produced by S-PLUS 3.x, 4.x or 2000 on (32-bit) Unix or Windows (and can read them on a different OS). This is able to read many but not all S objects: in particular it can read vectors, matrices and data frames and lists containing those.
Function `data.restore` reads S-PLUS data dumps (created by `data.dump`) with the same restrictions (except that dumps from the Alpha platform can also be read). It should be possible to read data dumps from S-PLUS 5.x and later written with `data.dump(oldStyle=T)`.
If you have access to S-PLUS, it is usually more reliable to `dump` the object(s) in S-PLUS and `source` the dump file in R. For S-PLUS 5.x and later you may need to use `dump(..., oldStyle=T)`, and to read in very large objects it may be preferable to use the dump file as a batch script rather than use the `source` function.
Function `read.spss` can read files created by the ‘save’ and ‘export’ commands in SPSS. It returns a list with one component for each variable in the saved data set. SPSS variables with value labels are optionally converted to R factors.
SPSS Data Entry is an application for creating data entry forms. By default it creates data files with extra formatting information that `read.spss` cannot handle, but it is possible to export the data in an ordinary SPSS format.
Some third-party applications claim to produce data ‘in SPSS format’ but with differences in the formats: `read.spss` may or may not be able to handle these.
Stata `.dta` files are a binary file format. Files from versions 5 up to 12 of Stata can be read and written by functions `read.dta` and `write.dta`. Stata variables with value labels are optionally converted to (and from) R factors. For Stata versions 13 and later see CRAN packages [**readstata13**](https://CRAN.R-project.org/package=readstata13) and [**haven**](https://CRAN.R-project.org/package=haven).
`read.systat` reads those Systat `SAVE` files that are rectangular data files (`mtype = 1`) written on little-endian machines (such as from Windows). These have extension `.sys` or (more recently) `.syd`.
### 3.2 Octave
Octave is a numerical linear algebra system (<https://www.gnu.org/software/octave/>), and function `read.octave` in package [**foreign**](https://CRAN.R-project.org/package=foreign) can read in files in Octave text data format created using the Octave command `save -ascii`, with support for most of the common types of variables, including the standard atomic (real and complex scalars, matrices, and *N*-d arrays, strings, ranges, and boolean scalars and matrices) and recursive (structs, cells, and lists) ones.
4 Relational databases
----------------------
### 4.1 Why use a database?
There are limitations on the types of data that R handles well. Since all data being manipulated by R are resident in memory, and several copies of the data can be created during execution of a function, R is not well suited to extremely large data sets. Data objects that are more than a (few) hundred megabytes in size can cause R to run out of memory, particularly on a 32-bit operating system.
R does not easily support concurrent access to data. That is, if more than one user is accessing, and perhaps updating, the same data, the changes made by one user will not be visible to the others.
R does support persistence of data, in that you can save a data object or an entire worksheet from one session and restore it at the subsequent session, but the format of the stored data is specific to R and not easily manipulated by other systems.
Database management systems (DBMSs) and, in particular, relational DBMSs (RDBMSs) *are* designed to do all of these things well. Their strengths are
1. To provide fast access to selected parts of large databases.
2. Powerful ways to summarize and cross-tabulate columns in databases.
3. Store data in more organized ways than the rectangular grid model of spreadsheets and R data frames.
4. Concurrent access from multiple clients running on multiple hosts while enforcing security constraints on access to the data.
5. Ability to act as a server to a wide range of clients.
The sort of statistical applications for which DBMS might be used are to extract a 10% sample of the data, to cross-tabulate data to produce a multi-dimensional contingency table, and to extract data group by group from a database for separate analysis.
Increasingly OSes are themselves making use of DBMSs for these reasons, so it is nowadays likely that one will be already installed on your (non-Windows) OS. [Akonadi](https://en.wikipedia.org/wiki/Akonadi) is used by KDE4 to store personal information. Several macOS applications, including Mail and Address Book, use SQLite.
### 4.2 Overview of RDBMSs
Traditionally there had been large (and expensive) commercial RDBMSs ([Informix](https://www.ibm.com/software/data/informix/); [Oracle](https://www.oracle.com); Sybase; [IBM’s DB2](https://www.ibm.com/db2); [Microsoft SQL Server](https://www.microsoft.com/sql-server/) on Windows) and academic and small-system databases (such as MySQL[4](#FOOT4), PostgreSQL, Microsoft Access, …), the former marked out by much greater emphasis on data security features. The line is blurring, with MySQL and PostgreSQL having more and more high-end features, and free ‘express’ versions being made available for the commercial DBMSs.
There are other commonly used data sources, including spreadsheets, non-relational databases and even text files (possibly compressed). Open Database Connectivity (ODBC) is a standard to use all of these data sources. It originated on Windows (see <https://docs.microsoft.com/en-us/sql/odbc/microsoft-open-database-connectivity-odbc>) but is also implemented on Linux/Unix/macOS.
All of the packages described later in this chapter provide clients to client/server databases. The database can reside on the same machine or (more often) remotely. There is an ISO standard (in fact several: SQL92 is ISO/IEC 9075, also known as ANSI X3.135-1992, and SQL99 is coming into use) for an interface language called SQL (Structured Query Language, sometimes pronounced ‘sequel’: see Bowman *et al.* 1996 and Kline and Kline 2001) which these DBMSs support to varying degrees.
#### 4.2.1 SQL queries
The more comprehensive R interfaces generate SQL behind the scenes for common operations, but direct use of SQL is needed for complex operations in all. Conventionally SQL is written in upper case, but many users will find it more convenient to use lower case in the R interface functions.
A relational DBMS stores data as a database of *tables* (or *relations*) which are rather similar to R data frames, in that they are made up of *columns* or *fields* of one type (numeric, character, date, currency, …) and *rows* or *records* containing the observations for one entity.
SQL ‘queries’ are quite general operations on a relational database. The classical query is a SELECT statement of the type
```
SELECT State, Murder FROM USArrests WHERE Rape > 30 ORDER BY Murder
SELECT t.sch, c.meanses, t.sex, t.achieve
FROM student as t, school as c WHERE t.sch = c.id
SELECT sex, COUNT(*) FROM student GROUP BY sex
SELECT sch, AVG(sestat) FROM student GROUP BY sch LIMIT 10
```
The first of these selects two columns from the R data frame `USArrests` that has been copied across to a database table, subsets on a third column and asks the results be sorted. The second performs a database *join* on two tables `student` and `school` and returns four columns. The third and fourth queries do some cross-tabulation and return counts or averages. (The five aggregation functions are COUNT(\*) and SUM, MAX, MIN and AVG, each applied to a single column.)
SELECT queries use FROM to select the table, WHERE to specify a condition for inclusion (or more than one condition separated by AND or OR), and ORDER BY to sort the result. Unlike data frames, rows in RDBMS tables are best thought of as unordered, and without an ORDER BY statement the ordering is indeterminate. You can sort (in lexicographical order) on more than one column by separating them by commas. Placing DESC after an ORDER BY puts the sort in descending order.
SELECT DISTINCT queries will only return one copy of each distinct row in the selected table.
The GROUP BY clause selects subgroups of the rows according to the criterion. If more than one column is specified (separated by commas) then multi-way cross-classifications can be summarized by one of the five aggregation functions. A HAVING clause allows the select to include or exclude groups depending on the aggregated value.
If the SELECT statement contains an ORDER BY statement that produces a unique ordering, a LIMIT clause can be added to select (by number) a contiguous block of output rows. This can be useful to retrieve rows a block at a time. (It may not be reliable unless the ordering is unique, as the LIMIT clause can be used to optimize the query.)
There are queries to create a table (CREATE TABLE, but usually one copies a data frame to the database in these interfaces), INSERT or DELETE or UPDATE data. A table is destroyed by a DROP TABLE ‘query’.
Kline and Kline (2001) discuss the details of the implementation of SQL in Microsoft SQL Server 2000, Oracle, MySQL and PostgreSQL.
#### 4.2.2 Data types
Data can be stored in a database in various data types. The range of data types is DBMS-specific, but the SQL standard defines many types, including the following that are widely implemented (often not by the SQL name).
`float(p)` Real number, with optional precision. Often called `real` or `double` or `double precision`.
`integer` 32-bit integer. Often called `int`.
`smallint` 16-bit integer
`character(n)` fixed-length character string. Often called `char`.
`character varying(n)` variable-length character string. Often called `varchar`. Almost always has a limit of 255 chars.
`boolean` true or false. Sometimes called `bool` or `bit`.
`date` calendar date
`time` time of day
`timestamp` date and time
There are variants on `time` and `timestamp`, `with
timezone`. Other types widely implemented are `text` and `blob`, for large blocks of text and binary data, respectively.
The more comprehensive of the R interface packages hide the type conversion issues from the user.
### 4.3 R interface packages
There are several packages available on CRAN to help R communicate with DBMSs. They provide different levels of abstraction. Some provide means to copy whole data frames to and from databases. All have functions to select data within the database via SQL queries, and to retrieve the result as a whole as a data frame or in pieces (usually as groups of rows).
All except [**RODBC**](https://CRAN.R-project.org/package=RODBC) are tied to one DBMS, but there has been a proposal for a unified ‘front-end’ package [**DBI**](https://CRAN.R-project.org/package=DBI) (<https://developer.r-project.org/db/>) in conjunction with a ‘back-end’, the most developed of which is [**RMySQL**](https://CRAN.R-project.org/package=RMySQL). Also on CRAN are the back-ends [**ROracle**](https://CRAN.R-project.org/package=ROracle), [**RPostgreSQL**](https://CRAN.R-project.org/package=RPostgreSQL) and [**RSQLite**](https://CRAN.R-project.org/package=RSQLite) (which works with the bundled DBMS `SQLite`, <https://www.sqlite.org/index.html>) and [**RJDBC**](https://CRAN.R-project.org/package=RJDBC) (which uses Java and can connect to any DBMS that has a JDBC driver).
**PL/R** ([`https://joeconway.com/plr`](https://joeconway.com/plr/)) is a project to embed R into PostgreSQL.
Package [**RMongo**](https://CRAN.R-project.org/package=RMongo) provides an R interface to a Java client for ‘MongoDB’ (<https://en.wikipedia.org/wiki/MongoDB>) databases, which are queried using JavaScript rather than SQL. Package [**mongolite**](https://CRAN.R-project.org/package=mongolite) is another client using **mongodb**’s C driver.
#### 4.3.1 Packages using DBI
Package [**RMySQL**](https://CRAN.R-project.org/package=RMySQL) on CRAN provides an interface to the MySQL database system (see <https://www.mysql.com> and Dubois, 2000) or its fork MariaDB (see <https://mariadb.org/>). The description here applies to versions `0.5-0` and later: earlier versions had a substantially different interface. The current version requires the [**DBI**](https://CRAN.R-project.org/package=DBI) package, and this description will apply with minor changes to all the other back-ends to [**DBI**](https://CRAN.R-project.org/package=DBI).
MySQL exists on Unix/Linux/macOS and Windows: there is a ‘Community Edition’ released under GPL but commercial licenses are also available. MySQL was originally a ‘light and lean’ database. (It preserves the case of names where the operating file system is case-sensitive, so not on Windows.)
The call `dbDriver("MySQL")` returns a database connection manager object, and then a call to `dbConnect` opens a database connection which can subsequently be closed by a call to the generic function `dbDisconnect`. Use `dbDriver("Oracle")`, `dbDriver("PostgreSQL")` or `dbDriver("SQLite")` with those DBMSs and packages [**ROracle**](https://CRAN.R-project.org/package=ROracle), [**RPostgreSQL**](https://CRAN.R-project.org/package=RPostgreSQL) or [**RSQLite**](https://CRAN.R-project.org/package=RSQLite) respectively.
SQL queries can be sent by either `dbSendQuery` or `dbGetQuery`. `dbGetquery` sends the query and retrieves the results as a data frame. `dbSendQuery` sends the query and returns an object of class inheriting from `"DBIResult"` which can be used to retrieve the results, and subsequently used in a call to `dbClearResult` to remove the result.
Function `fetch` is used to retrieve some or all of the rows in the query result, as a list. The function `dbHasCompleted` indicates if all the rows have been fetched, and `dbGetRowCount` returns the number of rows in the result.
These are convenient interfaces to read/write/test/delete tables in the database. `dbReadTable` and `dbWriteTable` copy to and from an R data frame, mapping the row names of the data frame to the field `row_names` in the `MySQL` table.
```
> library(RMySQL) # will load DBI as well
## open a connection to a MySQL database
> con <- dbConnect(dbDriver("MySQL"), dbname = "test")
## list the tables in the database
> dbListTables(con)
## load a data frame into the database, deleting any existing copy
> data(USArrests)
> dbWriteTable(con, "arrests", USArrests, overwrite = TRUE)
TRUE
> dbListTables(con)
[1] "arrests"
## get the whole table
> dbReadTable(con, "arrests")
Murder Assault UrbanPop Rape
Alabama 13.2 236 58 21.2
Alaska 10.0 263 48 44.5
Arizona 8.1 294 80 31.0
Arkansas 8.8 190 50 19.5
...
## Select from the loaded table
> dbGetQuery(con, paste("select row_names, Murder from arrests",
"where Rape > 30 order by Murder"))
row_names Murder
1 Colorado 7.9
2 Arizona 8.1
3 California 9.0
4 Alaska 10.0
5 New Mexico 11.4
6 Michigan 12.1
7 Nevada 12.2
8 Florida 15.4
> dbRemoveTable(con, "arrests")
> dbDisconnect(con)
```
#### 4.3.2 Package RODBC
Package [**RODBC**](https://CRAN.R-project.org/package=RODBC) on CRAN provides an interface to database sources supporting an ODBC interface. This is very widely available, and allows the same R code to access different database systems. [**RODBC**](https://CRAN.R-project.org/package=RODBC) runs on Unix/Linux, Windows and macOS, and almost all database systems provide support for ODBC. We have tested Microsoft SQL Server, Access, MySQL, PostgreSQL, Oracle and IBM DB2 on Windows and MySQL, MariaDB, Oracle, PostgreSQL and SQLite on Linux.
ODBC is a client-server system, and we have happily connected to a DBMS running on a Unix server from a Windows client, and *vice versa*.
On Windows ODBC support is part of the OS. On Unix/Linux you will need an ODBC Driver Manager such as unixODBC (<http://www.unixODBC.org>) or iOBDC (<http://www.iODBC.org>: this is pre-installed in macOS) and an installed driver for your database system.
Windows provides drivers not just for DBMSs but also for Excel (`.xls`) spreadsheets, DBase (`.dbf`) files and even text files. (The named applications do *not* need to be installed. Which file formats are supported depends on the versions of the drivers.) There are versions for Excel and Access 2007/2010 (go to <https://www.microsoft.com/en-us/download/default.aspx>, and search for ‘Office ODBC’, which will lead to `AccessDatabaseEngine.exe`), the ‘2007 Office System Driver’ (the latter has a version for 64-bit Windows, and that will also read earlier versions).
On macOS the Actual Technologies (<https://www.actualtech.com/product_access.php>) drivers provide ODBC interfaces to Access databases and to Excel spreadsheets (not including Excel 2007/2010).
Many simultaneous connections are possible. A connection is opened by a call to `odbcConnect` or `odbcDriverConnect` (which on the Windows GUI allows a database to be selected via dialog boxes) which returns a handle used for subsequent access to the database. Printing a connection will provide some details of the ODBC connection, and calling `odbcGetInfo` will give details on the client and server.
A connection is closed by a call to `close` or `odbcClose`, and also (with a warning) when not R object refers to it and at the end of an R session.
Details of the tables on a connection can be found using `sqlTables`.
Function `sqlSave` copies an R data frame to a table in the database, and `sqlFetch` copies a table in the database to an R data frame.
An SQL query can be sent to the database by a call to `sqlQuery`. This returns the result in an R data frame. (`sqlCopy` sends a query to the database and saves the result as a table in the database.) A finer level of control is attained by first calling `odbcQuery` and then `sqlGetResults` to fetch the results. The latter can be used within a loop to retrieve a limited number of rows at a time, as can function `sqlFetchMore`.
Here is an example using PostgreSQL, for which the ODBC driver maps column and data frame names to lower case. We use a database `testdb` we created earlier, and had the DSN (data source name) set up in `~/.odbc.ini` under `unixODBC`. Exactly the same code worked using MyODBC to access a MySQL database under Linux or Windows (where MySQL also maps names to lowercase). Under Windows, DSNs are set up in the ODBC applet in the Control Panel (‘Data Sources (ODBC)’ in the ‘Administrative Tools’ section).
```
> library(RODBC)
## tell it to map names to l/case
> channel <- odbcConnect("testdb", uid="ripley", case="tolower")
## load a data frame into the database
> data(USArrests)
> sqlSave(channel, USArrests, rownames = "state", addPK = TRUE)
> rm(USArrests)
## list the tables in the database
> sqlTables(channel)
TABLE_QUALIFIER TABLE_OWNER TABLE_NAME TABLE_TYPE REMARKS
1 usarrests TABLE
## list it
> sqlFetch(channel, "USArrests", rownames = "state")
murder assault urbanpop rape
Alabama 13.2 236 58 21.2
Alaska 10.0 263 48 44.5
...
## an SQL query, originally on one line
> sqlQuery(channel, "select state, murder from USArrests
where rape > 30 order by murder")
state murder
1 Colorado 7.9
2 Arizona 8.1
3 California 9.0
4 Alaska 10.0
5 New Mexico 11.4
6 Michigan 12.1
7 Nevada 12.2
8 Florida 15.4
## remove the table
> sqlDrop(channel, "USArrests")
## close the connection
> odbcClose(channel)
```
As a simple example of using ODBC under Windows with a Excel spreadsheet, we can read from a spreadsheet by
```
> library(RODBC)
> channel <- odbcConnectExcel("bdr.xls")
## list the spreadsheets
> sqlTables(channel)
TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
1 C:\\bdr NA Sheet1$ SYSTEM TABLE NA
2 C:\\bdr NA Sheet2$ SYSTEM TABLE NA
3 C:\\bdr NA Sheet3$ SYSTEM TABLE NA
4 C:\\bdr NA Sheet1$Print_Area TABLE NA
## retrieve the contents of sheet 1, by either of
> sh1 <- sqlFetch(channel, "Sheet1")
> sh1 <- sqlQuery(channel, "select * from [Sheet1$]")
```
Notice that the specification of the table is different from the name returned by `sqlTables`: `sqlFetch` is able to map the differences.
5 Binary files
--------------
Binary connections ([Connections](#Connections)) are now the preferred way to handle binary files.
### 5.1 Binary data formats
Packages [**h5**](https://CRAN.R-project.org/package=h5), Bioconductor’s **rhdf5**, [**RNetCDF**](https://CRAN.R-project.org/package=RNetCDF) and [**ncdf4**](https://CRAN.R-project.org/package=ncdf4) on CRAN provide interfaces to NASA’s HDF5 (Hierarchical Data Format, see <https://www.hdfgroup.org/HDF5/>) and to UCAR’s netCDF data files (network Common Data Form, see <https://www.unidata.ucar.edu/software/netcdf/>).
Both of these are systems to store scientific data in array-oriented ways, including descriptions, labels, formats, units, …. HDF5 also allows *groups* of arrays, and the R interface maps lists to HDF5 groups, and can write numeric and character vectors and matrices.
NetCDF’s version 4 format (confusingly, implemented in netCDF 4.1.1 and later, but not in 4.0.1) includes the use of various HDF5 formats. This is handled by package [**ncdf4**](https://CRAN.R-project.org/package=ncdf4) whereas [**RNetCDF**](https://CRAN.R-project.org/package=RNetCDF) handles version 3 files.
The availability of software to support these formats is somewhat limited by platform, especially on Windows.
### 5.2 dBase files (DBF)
`dBase` was a DOS program written by Ashton-Tate and later owned by Borland which has a binary flat-file format that became popular, with file extension `.dbf`. It has been adopted for the ’Xbase’ family of databases, covering dBase, Clipper, FoxPro and their Windows equivalents Visual dBase, Visual Objects and Visual FoxPro (see <https://www.clicketyclick.dk/databases/xbase/format/>). A dBase file contains a header and then a series of fields and so is most similar to an R data frame. The data itself is stored in text format, and can include character, logical and numeric fields, and other types in later versions (see for example <https://www.loc.gov/preservation/digital/formats/fdd/fdd000325.shtml> and <https://www.clicketyclick.dk/databases/xbase/format/index.html>).
Functions `read.dbf` and `write.dbf` provide ways to read and write basic DBF files on all R platforms. For Windows users `odbcConnectDbase` in package [**RODBC**](https://CRAN.R-project.org/package=RODBC) provides more comprehensive facilities to read DBF files *via* Microsoft’s dBase ODBC driver (and the Visual FoxPro driver can also be used via `odbcDriverConnect`).
6 Image files
-------------
A particular class of binary files are those representing images, and a not uncommon request is to read such a file into R as a matrix.
There are many formats for image files (most with lots of variants), and it may be necessary to use external conversion software to first convert the image into one of the formats for which a package currently provides an R reader. A versatile example of such software is ImageMagick and its fork GraphicsMagick. These provide command-line programs `convert` and `gm convert` to convert images from one format to another: what formats they can input is determined when they are compiled, and the supported formats can be listed by e.g. `convert -list format`.
Package [**pixmap**](https://CRAN.R-project.org/package=pixmap) has a function `read.pnm` to read ‘portable anymap’ images in PBM (black/white), PGM (grey) and PPM (RGB colour) formats. These are also known as ‘netpbm’ formats.
Packages [**bmp**](https://CRAN.R-project.org/package=bmp), [**jpeg**](https://CRAN.R-project.org/package=jpeg) and [**png**](https://CRAN.R-project.org/package=png) read the formats after which they are named. See also packages [**biOps**](https://CRAN.R-project.org/package=biOps) and [**Momocs**](https://CRAN.R-project.org/package=Momocs), and Bioconductor package **EBImage**.
TIFF is more a meta-format, a wrapper within which a very large variety of image formats can be embedded. Packages [**rtiff**](https://CRAN.R-project.org/package=rtiff) and [**tiff**](https://CRAN.R-project.org/package=tiff) can read some of the sub-formats (depending on the external `libtiff` software against which they are compiled). There some facilities for specialized sub-formats, for example in Bioconductor package **beadarray**.
Raster files are common in the geographical sciences, and package [**rgdal**](https://CRAN.R-project.org/package=rgdal) provides an interface to GDAL which provides some facilities of its own to read raster files and links to many others. Which formats it supports is determined when GDAL is compiled: use `gdalDrivers()` to see what these are for the build you are using. It can be useful for uncommon formats such as JPEG 2000 (which is a different format from JPEG, and not currently supported in the macOS nor Windows binary versions of [**rgdal**](https://CRAN.R-project.org/package=rgdal)).
7 Connections
-------------
*Connections* are used in R in the sense of Chambers (1998) and Ripley (2001), a set of functions to replace the use of file names by a flexible interface to file-like objects.
### 7.1 Types of connections
The most familiar type of connection will be a file, and file connections are created by function `file`. File connections can (if the OS will allow it for the particular file) be opened for reading or writing or appending, in text or binary mode. In fact, files can be opened for both reading and writing, and R keeps a separate file position for reading and writing.
Note that by default a connection is not opened when it is created. The rule is that a function using a connection should open a connection (needed) if the connection is not already open, and close a connection after use if it opened it. In brief, leave the connection in the state you found it in. There are generic functions `open` and `close` with methods to explicitly open and close connections.
Files compressed via the algorithm used by `gzip` can be used as connections created by the function `gzfile`, whereas files compressed by `bzip2` can be used via `bzfile`.
Unix programmers are used to dealing with special files `stdin`, `stdout` and `stderr`. These exist as *terminal connections* in R. They may be normal files, but they might also refer to input from and output to a GUI console. (Even with the standard Unix R interface, `stdin` refers to the lines submitted from `readline` rather than a file.)
The three terminal connections are always open, and cannot be opened or closed. `stdout` and `stderr` are conventionally used for normal output and error messages respectively. They may normally go to the same place, but whereas normal output can be re-directed by a call to `sink`, error output is sent to `stderr` unless re-directed by `sink, type="message")`. Note carefully the language used here: the connections cannot be re-directed, but output can be sent to other connections.
*Text connections* are another source of input. They allow R character vectors to be read as if the lines were being read from a text file. A text connection is created and opened by a call to `textConnection`, which copies the current contents of the character vector to an internal buffer at the time of creation.
Text connections can also be used to capture R output to a character vector. `textConnection` can be asked to create a new character object or append to an existing one, in both cases in the user’s workspace. The connection is opened by the call to `textConnection`, and at all times the complete lines output to the connection are available in the R object. Closing the connection writes any remaining output to a final element of the character vector.
*Pipes* are a special form of file that connects to another process, and pipe connections are created by the function `pipe`. Opening a pipe connection for writing (it makes no sense to append to a pipe) runs an OS command, and connects its standard input to whatever R then writes to that connection. Conversely, opening a pipe connection for input runs an OS command and makes its standard output available for R input from that connection.
URLs of types ‘`http://`’, ‘`https://`’, ‘`ftp://`’ and ‘`file://`’ can be read from using the function `url`. For convenience, `file` will also accept these as the file specification and call `url`.
Sockets can also be used as connections via function `socketConnection` on platforms which support Berkeley-like sockets (most Unix systems, Linux and Windows). Sockets can be written to or read from, and both client and server sockets can be used.
### 7.2 Output to connections
We have described functions `cat`, `write`, `write.table` and `sink` as writing to a file, possibly appending to a file if argument `append = TRUE`, and this is what they did prior to R version 1.2.0.
The current behaviour is equivalent, but what actually happens is that when the `file` argument is a character string, a file connection is opened (for writing or appending) and closed again at the end of the function call. If we want to repeatedly write to the same file, it is more efficient to explicitly declare and open the connection, and pass the connection object to each call to an output function. This also makes it possible to write to pipes, which was implemented earlier in a limited way via the syntax `file = "|cmd"` (which can still be used).
There is a function `writeLines` to write complete text lines to a connection.
Some simple examples are
```
zz <- file("ex.data", "w") # open an output file connection
cat("TITLE extra line", "2 3 5 7", "", "11 13 17",
file = zz, sep = "\n")
cat("One more line\n", file = zz)
close(zz)
## convert decimal point to comma in output, using a pipe (Unix)
## both R strings and (probably) the shell need \ doubled
zz <- pipe(paste("sed s/\\\\./,/ >", "outfile"), "w")
cat(format(round(rnorm(100), 4)), sep = "\n", file = zz)
close(zz)
## now look at the output file:
file.show("outfile", delete.file = TRUE)
## capture R output: use examples from help(lm)
zz <- textConnection("ex.lm.out", "w")
sink(zz)
example(lm, prompt.echo = "> ")
sink()
close(zz)
## now ‘ex.lm.out’ contains the output for futher processing.
## Look at it by, e.g.,
cat(ex.lm.out, sep = "\n")
```
### 7.3 Input from connections
The basic functions to read from connections are `scan` and `readLines`. These take a character string argument and open a file connection for the duration of the function call, but explicitly opening a file connection allows a file to be read sequentially in different formats.
Other functions that call `scan` can also make use of connections, in particular `read.table`.
Some simple examples are
```
## read in file created in last examples
readLines("ex.data")
unlink("ex.data")
## read listing of current directory (Unix)
readLines(pipe("ls -1"))
# remove trailing commas from an input file.
# Suppose we are given a file ‘data’ containing
450, 390, 467, 654, 30, 542, 334, 432, 421,
357, 497, 493, 550, 549, 467, 575, 578, 342,
446, 547, 534, 495, 979, 479
# Then read this by
scan(pipe("sed -e s/,$// data"), sep=",")
```
For convenience, if the `file` argument specifies a FTP, HTTP or HTTPS URL, the URL is opened for reading via `url`. Specifying files via ‘`file://foo.bar`’ is also allowed.
#### 7.3.1 Pushback
C programmers may be familiar with the `ungetc` function to push back a character onto a text input stream. R connections have the same idea in a more powerful way, in that an (essentially) arbitrary number of lines of text can be pushed back onto a connection via a call to `pushBack`.
Pushbacks operate as a stack, so a read request first uses each line from the most recently pushbacked text, then those from earlier pushbacks and finally reads from the connection itself. Once a pushbacked line is read completely, it is cleared. The number of pending lines pushed back can be found via a call to `pushBackLength`.
A simple example will show the idea.
```
> zz <- textConnection(LETTERS)
> readLines(zz, 2)
[1] "A" "B"
> scan(zz, "", 4)
Read 4 items
[1] "C" "D" "E" "F"
> pushBack(c("aa", "bb"), zz)
> scan(zz, "", 4)
Read 4 items
[1] "aa" "bb" "G" "H"
> close(zz)
```
Pushback is only available for connections opened for input in text mode.
### 7.4 Listing and manipulating connections
A summary of all the connections currently opened by the user can be found by `showConnections()`, and a summary of all connections, including closed and terminal connections, by `showConnections(all
= TRUE)`
The generic function `seek` can be used to read and (on some connections) reset the current position for reading or writing. Unfortunately it depends on OS facilities which may be unreliable (e.g. with text files under Windows). Function `isSeekable` reports if `seek` can change the position on the connection given by its argument.
The function `truncate` can be used to truncate a file opened for writing at its current position. It works only for `file` connections, and is not implemented on all platforms.
### 7.5 Binary connections
Functions `readBin` and `writeBin` read to and write from binary connections. A connection is opened in binary mode by appending `"b"` to the mode specification, that is using mode `"rb"` for reading, and mode `"wb"` or `"ab"` (where appropriate) for writing. The functions have arguments
```
readBin(con, what, n = 1, size = NA, endian = .Platform$endian)
writeBin(object, con, size = NA, endian = .Platform$endian)
```
In each case `con` is a connection which will be opened if necessary for the duration of the call, and if a character string is given it is assumed to specify a file name.
It is slightly simpler to describe writing, so we will do that first. `object` should be an atomic vector object, that is a vector of mode `numeric`, `integer`, `logical`, `character`, `complex` or `raw`, without attributes. By default this is written to the file as a stream of bytes exactly as it is represented in memory.
`readBin` reads a stream of bytes from the file and interprets them as a vector of mode given by `what`. This can be either an object of the appropriate mode (e.g. `what=integer()`) or a character string describing the mode (one of the five given in the previous paragraph or `"double"` or `"int"`). Argument `n` specifies the maximum number of vector elements to read from the connection: if fewer are available a shorter vector will be returned. Argument `signed` allows 1-byte and 2-byte integers to be read as signed (the default) or unsigned integers.
The remaining two arguments are used to write or read data for interchange with another program or another platform. By default binary data is transferred directly from memory to the connection or *vice versa*. This will not suffice if the data are to be transferred to a machine with a different architecture, but between almost all R platforms the only change needed is that of byte-order. Common PCs (‘`ix86`’-based and ‘`x86\_64`’-based machines), Compaq Alpha and Vaxen are *little-endian*, whereas Sun Sparc, mc680x0 series, IBM R6000, SGI and most others are *big-endian*. (Network byte-order (as used by XDR, eXternal Data Representation) is big-endian.) To transfer to or from other programs we may need to do more, for example to read 16-bit integers or write single-precision real numbers. This can be done using the `size` argument, which (usually) allows sizes 1, 2, 4, 8 for integers and logicals, and sizes 4, 8 and perhaps 12 or 16 for reals. Transferring at different sizes can lose precision, and should not be attempted for vectors containing `NA`’s.
Character strings are read and written in C format, that is as a string of bytes terminated by a zero byte. Functions `readChar` and `writeChar` provide greater flexibility.
#### 7.5.1 Special values
Functions `readBin` and `writeBin` will pass missing and special values, although this should not be attempted if a size change is involved.
The missing value for R logical and integer types is `INT_MIN`, the smallest representable `int` defined in the C header `limits.h`, normally corresponding to the bit pattern `0x80000000`.
The representation of the special values for R numeric and complex types is machine-dependent, and possibly also compiler-dependent. The simplest way to make use of them is to link an external application against the standalone `Rmath` library which exports double constants `NA_REAL`, `R_PosInf` and `R_NegInf`, and include the header `Rmath.h` which defines the macros `ISNAN` and `R_FINITE`.
If that is not possible, on all current platforms IEC 60559 (aka IEEE 754) arithmetic is used, so standard C facilities can be used to test for or set `Inf`, `-Inf` and `NaN` values. On such platforms `NA` is represented by the `NaN` value with low-word `0x7a2` (1954 in decimal).
Character missing values are written as `NA`, and there are no provision to recognize character values as missing (as this can be done by re-assigning them once read).
8 Network interfaces
--------------------
Some limited facilities are available to exchange data at a lower level across network connections.
### 8.1 Reading from sockets
Base R comes with some facilities to communicate *via* BSD sockets on systems that support them (including the common Linux, Unix and Windows ports of R). One potential problem with using sockets is that these facilities are often blocked for security reasons or to force the use of Web caches, so these functions may be more useful on an intranet than externally. For new projects it is suggested that socket connections are used instead.
The earlier low-level interface is given by functions `make.socket`, `read.socket`, `write.socket` and `close.socket`.
### 8.2 Using `download.file`
Function `download.file` is provided to read a file from a Web resource via FTP or HTTP (including HTTPS) and write it to a file. Often this can be avoided, as functions such as `read.table` and `scan` can read directly from a URL, either by explicitly using `url` to open a connection, or implicitly using it by giving a URL as the `file` argument.
9 Reading Excel spreadsheets
----------------------------
The most common R data import/export question seems to be ‘how do I read an Excel spreadsheet’. This chapter collects together advice and options given earlier. Note that most of the advice is for pre-Excel 2007 spreadsheets and not the later `.xlsx` format.
The first piece of advice is to avoid doing so if possible! If you have access to Excel, export the data you want from Excel in tab-delimited or comma-separated form, and use `read.delim` or `read.csv` to import it into R. (You may need to use `read.delim2` or `read.csv2` in a locale that uses comma as the decimal point.) Exporting a DIF file and reading it using `read.DIF` is another possibility.
If you do not have Excel, many other programs are able to read such spreadsheets and export in a text format on both Windows and Unix, for example Gnumeric (<http://www.gnumeric.org>) and OpenOffice (<https://www.openoffice.org>). You can also cut-and-paste between the display of a spreadsheet in such a program and R: `read.table` will read from the R console or, under Windows, from the clipboard (via `file = "clipboard"` or `readClipboard`). The `read.DIF` function can also read from the clipboard.
Note that an Excel `.xls` file is not just a spreadsheet: such files can contain many sheets, and the sheets can contain formulae, macros and so on. Not all readers can read other than the first sheet, and may be confused by other contents of the file.
Windows users (of 32-bit R) can use `odbcConnectExcel` in package [**RODBC**](https://CRAN.R-project.org/package=RODBC). This can select rows and columns from any of the sheets in an Excel spreadsheet file (at least from Excel 97–2003, depending on your ODBC drivers: by calling `odbcConnect` directly versions back to Excel 3.0 can be read). The version `odbcConnectExcel2007` will read the Excel 2007 formats as well as earlier ones (provided the drivers are installed, including with 64-bit Windows R: see [RODBC](#RODBC)). macOS users can also use [**RODBC**](https://CRAN.R-project.org/package=RODBC) if they have a suitable driver (e.g. that from Actual Technologies).
`Perl` users have contributed a module `OLE::SpreadSheet::ParseExcel` and a program `xls2csv.pl` to convert Excel 95–2003 spreadsheets to CSV files. Package [**gdata**](https://CRAN.R-project.org/package=gdata) provides a basic wrapper in its `read.xls` function. With suitable `Perl` modules installed this function can also read Excel 2007 spreadsheets.
Packages [**dataframes2xls**](https://CRAN.R-project.org/package=dataframes2xls) and [**WriteXLS**](https://CRAN.R-project.org/package=WriteXLS) each contain a function to *write* one or more data frames to an `.xls` file, using Python and Perl respectively.
Packages [**xlsx**](https://CRAN.R-project.org/package=xlsx) can read and and manipulate Excel 2007 and later spreadsheets: it requires Java.
Package [**XLConnect**](https://CRAN.R-project.org/package=XLConnect) can read, write and manipulate both Excel 97–2003 and Excel 2007/10 spreadsheets, using Java.
Package [**readxl**](https://CRAN.R-project.org/package=readxl) can read both Excel 97–2003 and Excel 2007/10 spreadsheets, using an included C library.
Appendix A References
---------------------
R. A. Becker, J. M. Chambers and A. R. Wilks (1988) *The New S Language. A Programming Environment for Data Analysis and Graphics.* Wadsworth & Brooks/Cole.
J. Bowman, S. Emberson and M. Darnovsky (1996) *The Practical SQL Handbook. Using Structured Query Language.* Addison-Wesley.
J. M. Chambers (1998) *Programming with Data. A Guide to the S Language.* Springer-Verlag.
P. Dubois (2000) *MySQL.* New Riders.
M. Henning and S. Vinoski (1999) *Advanced CORBA Programming with C++.* Addison-Wesley.
K. Kline and D. Kline (2001) *SQL in a Nutshell.* O’Reilly.
B. Momjian (2000) *PostgreSQL: Introduction and Concepts.* Addison-Wesley. Also available at <https://momjian.us/main/writings/pgsql/aw_pgsql_book/>.
B. D. Ripley (2001) Connections. *R News*, **1/1**, 16–7. <https://www.r-project.org/doc/Rnews/Rnews_2001-1.pdf>
T. M. Therneau and P. M. Grambsch (2000) *Modeling Survival Data. Extending the Cox Model.* Springer-Verlag.
E. J. Yarger, G. Reese and T. King (1999) *MySQL & mSQL*. O’Reilly.
#### Footnotes
**(1)** the distinction is subtle, <https://en.wikipedia.org/wiki/UTF-16/UCS-2>, and the use of surrogate pairs is very rare.
**(2)** Even then, Windows applications may expect a Byte Order Mark which the implementation of `iconv` used by R may or may not add depending on the platform.
**(3)** This is normally fast as looking at the first entry rules out most of the possibilities.
**(4)** and forks, notably MariaDB.
| programming_docs |
javascript Lexical grammar Lexical grammar
===============
This page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters — in order for the interpreter to understand it, the string has to be *parsed* to a more structured representation. The initial step of parsing is called [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis), in which the text gets scanned from left to right and is converted into a sequence of individual, atomic input elements. Some input elements are insignificant to the interpreter, and will be stripped after this step — they include [white space](#white_space) and [comments](#comments). The others, including [identifiers](#identifiers), [keywords](#keywords), [literals](#literals), and punctuators (mostly [operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators)), will be used for further syntax analysis. [Line terminators](#line_terminators) and multiline comments are also syntactically insignificant, but they guide the process for [automatic semicolons insertion](#automatic_semicolon_insertion) to make certain invalid token sequences become valid.
Format-control characters
-------------------------
Format-control characters have no visual representation but are used to control the interpretation of the text.
| Code point | Name | Abbreviation | Description |
| --- | --- | --- | --- |
| U+200C | Zero width non-joiner | <ZWNJ> | Placed between characters to prevent being connected into ligatures in certain languages ([Wikipedia](https://en.wikipedia.org/wiki/Zero-width_non-joiner)). |
| U+200D | Zero width joiner | <ZWJ> | Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages ([Wikipedia](https://en.wikipedia.org/wiki/Zero-width_joiner)). |
| U+FEFF | Byte order mark | <BOM> | Used at the start of the script to mark it as Unicode and the text's byte order ([Wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark)). |
In JavaScript source text, <ZWNJ> and <ZWJ> are treated as [identifier](#identifiers) parts, while <BOM> (also called a zero-width no-break space <ZWNBSP> when not at the start of text) is treated as [white space](#white_space).
White space
-----------
[White space](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) characters improve the readability of source text and separate tokens from each other. These characters are usually unnecessary for the functionality of the code. [Minification tools](https://en.wikipedia.org/wiki/Minification_%28programming%29) are often used to remove whitespace in order to reduce the amount of data that needs to be transferred.
| Code point | Name | Abbreviation | Description | Escape sequence |
| --- | --- | --- | --- | --- |
| U+0009 | Character tabulation | <TAB> | Horizontal tabulation | \t |
| U+000B | Line tabulation | <VT> | Vertical tabulation | \v |
| U+000C | Form feed | <FF> | Page breaking control character ([Wikipedia](https://en.wikipedia.org/wiki/Page_break#Form_feed)). | \f |
| U+0020 | Space | <SP> | Normal space | |
| U+00A0 | No-break space | <NBSP> | Normal space, but no point at which a line may break | |
| U+FEFF | Zero-width no-break space | <ZWNBSP> | When not at the start of a script, the BOM marker is a normal whitespace character. | |
| Others | Other Unicode space characters | <USP> | [Characters in the "Space\_Separator" general category](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BGeneral_Category%3DSpace_Separator%7D) | |
**Note:** Of those [characters with the "White\_Space" property but are not in the "Space\_Separator" general category](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BWhite_Space%7D%26%5CP%7BGeneral_Category%3DSpace_Separator%7D), U+0009, U+000B, and U+000C are still treated as white space in JavaScript; U+0085 NEXT LINE has no special role; others become the set of [line terminators](#line_terminators).
**Note:** Changes to the Unicode standard used by the JavaScript engine may affect programs' behavior. For example, ES2016 upgraded the reference Unicode standard from 5.1 to 8.0.0, which caused U+180E MONGOLIAN VOWEL SEPARATOR to be moved from the "Space\_Separator" category to the "Format (Cf)" category, and made it a non-whitespace. Subsequently, the result of [`"\u180E".trim().length`](global_objects/string/trim) changed from `0` to `1`.
Line terminators
----------------
In addition to [white space](#white_space) characters, line terminator characters are used to improve the readability of the source text. However, in some cases, line terminators can influence the execution of JavaScript code as there are a few places where they are forbidden. Line terminators also affect the process of [automatic semicolon insertion](#automatic_semicolon_insertion).
Outside the context of lexical grammar, white space and line terminators are often conflated. For example, [`String.prototype.trim()`](global_objects/string/trim) removes all white space and line terminators from the beginning and end of a string. The `\s` [character class escape](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) in regular expressions matches all white space and line terminators.
Only the following Unicode code points are treated as line terminators in ECMAScript, other line breaking characters are treated as white space (for example, Next Line, NEL, U+0085 is considered as white space).
| Code point | Name | Abbreviation | Description | Escape sequence |
| --- | --- | --- | --- | --- |
| U+000A | Line Feed | <LF> | New line character in UNIX systems. | \n |
| U+000D | Carriage Return | <CR> | New line character in Commodore and early Mac systems. | \r |
| U+2028 | Line Separator | <LS> | [Wikipedia](https://en.wikipedia.org/wiki/Newline) | |
| U+2029 | Paragraph Separator | <PS> | [Wikipedia](https://en.wikipedia.org/wiki/Newline) | |
Comments
--------
Comments are used to add hints, notes, suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool.
JavaScript has two long-standing ways to add comments to code: line comments and block comments. In addition, there's a special hashbang comment syntax.
### Line comments
The first way is the `//` comment; this makes all text following it on the same line into a comment. For example:
```
function comment() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
comment();
```
### Block comments
The second way is the `/* */` style, which is much more flexible.
For example, you can use it on a single line:
```
function comment() {
/\* This is a one line JavaScript comment \*/
console.log("Hello world!");
}
comment();
```
You can also make multiple-line comments, like this:
```
function comment() {
/\* This comment spans multiple lines. Notice
that we don't need to end the comment until we're done. \*/
console.log("Hello world!");
}
comment();
```
You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:
```
function comment(x) {
console.log("Hello " + x /\* insert the value of x \*/ + " !");
}
comment("world");
```
In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:
```
function comment() {
/\* console.log("Hello world!"); \*/
}
comment();
```
In this case, the `console.log()` call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.
Block comments that contain at least one line terminator behave like [line terminators](#line_terminators) in [automatic semicolon insertion](#automatic_semicolon_insertion).
### Hashbang comments
There's a special third comment syntax, the **hashbang comment**. A hashbang comment behaves exactly like a single line-only (`//`) comment, except that it begins with `#!` and **is only valid at the absolute start of a script or module**. Note also that no whitespace of any kind is permitted before the `#!`. The comment consists of all the characters after `#!` up to the end of the first line; only one such comment is permitted.
Hashbang comments in JavaScript resemble [shebangs in Unix](https://en.wikipedia.org/wiki/Shebang_(Unix)) which provide the path to a specific JavaScript interpreter that you want to use to execute the script. Before the hashbang comment became standardized, it had already been de-facto implemented in non-browser hosts like Node.js, where it was stripped from the source text before being passed to the engine. An example is as follows:
```
#!/usr/bin/env node
console.log("Hello world");
```
The JavaScript interpreter will treat it as a normal comment — it only has semantic meaning to the shell if the script is directly run in a shell.
**Warning:** If you want scripts to be runnable directly in a shell environment, encode them in UTF-8 without a [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). Although a BOM will not cause any problems for code running in a browser — because it's stripped during UTF-8 decoding, before the source text is analyzed — a Unix/Linux shell will not recognize the hashbang if it's preceded by a BOM character.
You must only use the `#!` comment style to specify a JavaScript interpreter. In all other cases just use a `//` comment (or multiline comment).
Identifiers
-----------
An *identifier* is used to link a value with a name. Identifiers can be used in various places:
```
const decl = 1; // Variable declaration (may also be `let` or `var`)
function fn() {} // Function declaration
const obj = { key: "value" }; // Object keys
// Class declaration
class C {
#priv = "value"; // Private property
}
lbl: console.log(1); // Label
```
In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (`_`), and dollar signs (`$`). Identifiers are not allowed to start with numbers. However, JavaScript identifiers are not only limited to ASCII — many Unicode codepoints are allowed as well. Namely, any character in the [ID\_Start](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BID_Start%7D) category can start an identifier, while any character in the [ID\_Continue](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BID_Continue%7D) category can appear after the first character.
**Note:** If, for some reason, you need to parse some JavaScript source yourself, do not assume all identifiers follow the pattern `/[A-Za-z_$][\w$]*/` (i.e. ASCII-only)! The range of identifiers can be described by the regex `/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u` (excluding unicode escape sequences).
In addition, JavaScript allows using [Unicode escape sequences](#unicode_escape_sequences) in the form of `\u0000` or `\u{000000}` in identifiers, which encode the same string value as the actual Unicode characters. For example, `你好` and `\u4f60\u597d` are the same identifiers:
```
const 你好 = "Hello";
console.log(\u4f60\u597d); // Hello
```
Not all places accept the full range of identifiers. Certain syntaxes, such as function declarations, function expressions, and variable declarations require using identifiers names that are not [reserved words](#reserved_words).
```
function import() {} // Illegal: import is a reserved word.
```
Most notably, private properties and object properties allow reserved words.
```
const obj = { import: "value" }; // Legal despite `import` being reserved
class C {
#import = "value";
}
```
Keywords
--------
*Keywords* are tokens that look like identifiers but have special meanings in JavaScript. For example, the keyword [`async`](statements/async_function) before a function declaration indicates that the function is asynchronous.
Some keywords are *reserved*, meaning that cannot be used as an identifier for variable declarations, function declarations, etc. They are often called *reserved words*. [A list of these reserved words](#reserved_words) is provided below. Not all keywords are reserved — for example, `async` can be used as an identifier anywhere. Some keywords are only *contextually reserved* — for example, `await` is only reserved within the body of an async function, and `let` is only reserved in strict mode code, or `const` and `let` declarations.
Identifiers are always compared by *string value*, so escape sequences are interpreted. For example, this is still a syntax error:
```
const els\u{65} = 1;
// `els\u{65}` encodes the same identifier as `else`
```
### Reserved words
These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.
* [`break`](statements/break)
* [`case`](statements/switch)
* [`catch`](statements/try...catch)
* [`class`](statements/class)
* [`const`](statements/const)
* [`continue`](statements/continue)
* [`debugger`](statements/debugger)
* [`default`](statements/switch)
* [`delete`](operators/delete)
* [`do`](statements/do...while)
* [`else`](statements/if...else)
* [`export`](statements/export)
* [`extends`](classes/extends)
* [`false`](#boolean_literal)
* [`finally`](statements/try...catch)
* [`for`](statements/for)
* [`function`](statements/function)
* [`if`](statements/if...else)
* [`import`](statements/import)
* [`in`](operators/in)
* [`instanceof`](operators/instanceof)
* [`new`](operators/new)
* [`null`](operators/null)
* [`return`](statements/return)
* [`super`](operators/super)
* [`switch`](statements/switch)
* [`this`](operators/this)
* [`throw`](statements/throw)
* [`true`](#boolean_literal)
* [`try`](statements/try...catch)
* [`typeof`](operators/typeof)
* [`var`](statements/var)
* [`void`](operators/void)
* [`while`](statements/while)
* [`with`](statements/with)
The following are only reserved when they are found in strict mode code:
* [`let`](statements/let) (also reserved in `const`, `let`, and class declarations)
* [`static`](classes/static)
* [`yield`](operators/yield) (also reserved in generator function bodies)
The following are only reserved when they are found in module code or async function bodies:
* [`await`](operators/await)
### Future reserved words
The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.
These are always reserved:
* `enum`
The following are only reserved when they are found in strict mode code:
* `implements`
* `interface`
* `package`
* `private`
* `protected`
* `public`
#### Future reserved words in older standards
The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
* `abstract`
* `boolean`
* `byte`
* `char`
* `double`
* `final`
* `float`
* `goto`
* `int`
* `long`
* `native`
* `short`
* `synchronized`
* `throws`
* `transient`
* `volatile`
### Identifiers with special meanings
A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:
* [`arguments`](functions/arguments) (not a keyword, but cannot be declared as identifier in strict mode)
* `as` ([`import * as ns from "mod"`](statements/import#namespace_import))
* [`async`](statements/async_function)
* [`eval`](global_objects/eval) (not a keyword, but cannot be declared as identifier in strict mode)
* `from` ([`import x from "mod"`](statements/import))
* [`get`](functions/get)
* [`of`](statements/for...of)
* [`set`](functions/set)
Literals
--------
**Note:** This section discusses literals that are atomic tokens. [Object literals](operators/object_initializer) and [array literals](global_objects/array/array#array_literal_notation) are [expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) that consist of a series of tokens.
### Null literal
See also [`null`](operators/null) for more information.
```
null
```
### Boolean literal
See also [boolean type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type) for more information.
```
true
false
```
### Numeric literals
The [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type) and [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type) types use numeric literals.
#### Decimal
```
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](strict_mode#legacy_octal_literals) — so, use the `0o` prefix instead.
```
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal
```
##### Exponential
The decimal exponential literal is specified by the following format: `beN`; where `b` is a base number (integer or floating), followed by an `E` or `e` character (which serves as separator or *exponent indicator*) and `N`, which is *exponent* or *power* number – a signed integer.
```
0e-5 // 0
0e+5 // 0
5e1 // 50
175e-2 // 1.75
1e3 // 1000
1e-3 // 0.001
1E3 // 1000
```
#### Binary
Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (`0b` or `0B`). Any character after the `0b` that is not 0 or 1 will terminate the literal sequence.
```
0b10000000000000000000000000000000 // 2147483648
0b01111111100000000000000000000000 // 2139095040
0B00000000011111111111111111111111 // 8388607
```
#### Octal
Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (`0o` or `0O)`. Any character after the `0o` that is outside the range (01234567) will terminate the literal sequence.
```
0O755 // 493
0o644 // 420
```
#### Hexadecimal
Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (`0x` or `0X`). Any character after the `0x` that is outside the range (0123456789ABCDEF) will terminate the literal sequence.
```
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF // 81985529216486900
0XA // 10
```
#### BigInt literal
The [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type) type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending `n` to the end of an integer.
```
123456789123456789n // 123456789123456789
0o777777777777n // 68719476735
0x123456789ABCDEFn // 81985529216486895
0b11101001010101010101n // 955733
```
BigInt literals cannot start with `0` to avoid confusion with legacy octal literals.
```
0755n;
// SyntaxError: invalid BigInt syntax
```
For octal `BigInt` numbers, always use zero followed by the letter "o" (uppercase or lowercase):
```
0o755n;
```
For more information about `BigInt`, see also [JavaScript data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type).
#### Numeric separators
To improve readability for numeric literals, underscores (`_`, `U+005F`) can be used as separators:
```
1\_000\_000\_000\_000
1\_050.95
0b1010\_0001\_1000\_0101
0o2\_2\_5\_6
0xA0\_B0\_C0
1\_000\_000\_000\_000\_000\_000\_000n
```
Note these limitations:
```
// More than one underscore in a row is not allowed
100__000; // SyntaxError
// Not allowed at the end of numeric literals
100_; // SyntaxError
// Can not be used after leading 0
0\_1; // SyntaxError
```
### String literals
A [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these closing quote code points:
* U+005C \ (backslash),
* U+000D <CR>,
* and U+000A <LF>.
Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.
```
'foo'
"bar"
```
#### Hexadecimal escape sequences
Hexadecimal escape sequences consist of `\x` followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.
```
"\xA9"; // "©"
```
#### Unicode escape sequences
A Unicode escape sequence consists of exactly four hexadecimal digits following `\u`. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.
See also [`String.fromCharCode()`](global_objects/string/fromcharcode) and [`String.prototype.charCodeAt()`](global_objects/string/charcodeat).
```
"\u00A9"; // "©" (U+A9)
```
#### Unicode code point escapes
A Unicode code point escape consists of `\u{`, followed by a code point in hexadecimal base, followed by `}`. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair.
See also [`String.fromCodePoint()`](global_objects/string/fromcodepoint) and [`String.prototype.codePointAt()`](global_objects/string/codepointat).
```
"\u{2F804}"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)
// the same character represented as a surrogate pair
"\uD87E\uDC04";
```
### Regular expression literals
Regular expression literals are enclosed by two forward slashes (`/`). The lexer consumes all characters up to the next unescaped forward slash or the end of the line, unless the forward slash appears within a character class (`[]`). Some characters (namely, those that are [identifier parts](#identifiers)) can appear after the closing slash, denoting flags.
The lexical grammar is very lenient: not all regular expression literals that get identified as one token are valid regular expressions.
See also [`RegExp`](global_objects/regexp) for more information.
```
/ab+c/g
/[/]/
```
A regular expression literal cannot start with two forward slashes (`//`), because that would be a line comment. To specify an empty regular expression, use `/(?:)/`.
### Template literals
One template literal consists of several tokens: ``xxx${` (template head), `}xxx${` (template middle), and `}xxx`` (template tail) are individual tokens, while any expression may come between them.
See also [template literals](template_literals) for more information.
```
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag`string text ${expression} string text`
```
Automatic semicolon insertion
-----------------------------
Some [JavaScript statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements)' syntax definitions require semicolons (`;`) at the end. They include:
* [`var`](statements/var), [`let`](statements/let), [`const`](statements/const)
* [Expression statements](statements/expression_statement)
* [`do...while`](statements/do...while)
* [`continue`](statements/continue), [`break`](statements/break), [`return`](statements/return), [`throw`](statements/throw)
* [`debugger`](statements/debugger)
* Class field declarations ([public](classes/public_class_fields) or [private](classes/private_class_fields))
* [`import`](statements/import), [`export`](statements/export)
However, to make the language more approachable and convenient, JavaScript is able to automatically insert semicolons when consuming the token stream, so that some invalid token sequences can be "fixed" to valid syntax. This step happens after the program text has been parsed to tokens according to the lexical grammar. There are three cases when semicolons are automatically inserted:
1. When a token not allowed by the grammar is encountered, and it's separated from the previous token by at least one [line terminator](#line_terminators) (including a block comment that includes at least one line terminator), or the token is "}", then a semicolon is inserted before the token.
```
{ 1
2 } 3
// is transformed by ASI into:
{ 1
;2 ;} 3;
// Which is valid grammar encoding three statements,
// each consisting of a number literal
```
The ending ")" of [`do...while`](statements/do...while) is taken care of as a special case by this rule as well.
```
do {
// ...
} while (condition) /\* ; \*/ // ASI here
const a = 1
```
However, semicolons are not inserted if the semicolon would then become the separator in the [`for`](statements/for) statement's head.
```
for (
let a = 1 // No ASI here
a < 10 // No ASI here
a++
) {}
```
Semicolons are also never inserted as [empty statements](statements/empty). For example, in the code below, if a semicolon is inserted after ")", then the code would be valid, with an empty statement as the `if` body and the `const` declaration being a separate statement. However, because automatically inserted semicolons cannot become empty statements, this causes a [declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations) to become the body of the `if` statement, which is not valid.
```
if (Math.random() > 0.5)
const x = 1 // SyntaxError: Unexpected token 'const'
```
2. When the end of the input stream of tokens is reached, and the parser is unable to parse the single input stream as a complete program, a semicolon is inserted at the end.
```
const a = 1 /\* ; \*/ // ASI here
```
This rule is a complement to the previous rule, specifically for the case where there's no "offending token" but the end of input stream.
3. When the grammar forbids line terminators in some place but a line terminator is found, a semicolon is inserted. These places include:
* `expr <here> ++`, `expr <here> --`
* `continue <here> lbl`
* `break <here> lbl`
* `return <here> expr`
* `throw <here> expr`
* `yield <here> expr`
* `yield <here> * expr`
* `(param) <here> => {}`
* `async <here> function`, `async <here> prop()`, `async <here> function*`, `async <here> *prop()`, `async <here> (param) <here> => {}`
Here [`++`](operators/increment) is not treated as a postfix operator applying to variable `b`, because a line terminator occurs between `b` and `++`.
```
a = b
++c
// is transformed by ASI into
a = b;
++c;
```
Here, the `return` statement returns `undefined`, and the `a + b` becomes an unreachable statement.
```
return
a + b
// is transformed by ASI into
return;
a + b;
```
Note that ASI would only be triggered if a line break separates tokens that would otherwise produce invalid syntax. If the next token can be parsed as part of a valid structure, semicolons would not be inserted. For example:
```
const a = 1
(1).toString()
const b = 1
[1, 2, 3].forEach(console.log)
```
Because `()` can be seen as a function call, it would usually not trigger ASI. Similarly, `[]` may be a member access. The code above is equivalent to:
```
const a = 1(1).toString();
const b = 1[1, 2, 3].forEach(console.log);
```
This happens to be valid syntax. `1[1, 2, 3]` is a [property accessor](operators/property_accessors) with a [comma](operators/comma_operator)-joined expression. Therefore, you would get errors like "1 is not a function" and "Cannot read properties of undefined (reading 'forEach')" when running the code.
Within classes, class fields and generator methods can be a pitfall as well.
```
class A {
a = 1
\*gen() {}
}
```
It is seen as:
```
class A {
a = 1 \* gen() {}
}
```
And therefore will be a syntax error around `{`.
There are the following rules-of-thumb for dealing with ASI, if you want to enforce semicolon-less style:
* Write postfix `++` and `--` on the same line as their operands.
* The expressions after `return`, `throw`, or `yield` should be on the same line as the keyword.
* Similarly, the label identifier after `break` or `continue` should be on the same line as the keyword.
* The `=>` of an arrow function should be on the same line as the end of its parameters.
* The `async` of async functions, methods, etc. cannot be directly followed by a line terminator.
* If a line starts with one of `(`, `[`, ```, `+`, `-`, `/` (as in regex literals), prefix it with a semicolon, or end the previous line with a semicolon.
* Class fields should preferably always be ended with semicolons — in addition to the previous rule (which includes a field declaration followed by a [computed property](operators/object_initializer#computed_property_names), since the latter starts with `[`), semicolons are also required between a field declaration and a generator method.
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `array_literals` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `binary_numeric_literals` | 41 | 12 | 25 | No | 28 | 9 | 41 | 41 | 25 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `boolean_literals` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `decimal_numeric_literals` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `hashbang_comments` | 74 | 79 | 67 | No | 62 | 13.1 | 74 | 74 | 67 | 53 | 13.4 | 11.0 | 1.0 | 0.10.0 |
| `hexadecimal_escape_sequences` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `hexadecimal_numeric_literals` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `null_literal` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `numeric_separators` | 75 | 79 | 70 | No | 62 | 13 | 75 | 75 | 79 | No | 13 | 11.0 | 1.2 | 12.5.0
10.4.0 |
| `octal_numeric_literals` | 41 | 12 | 25 | No | 28 | 9 | 41 | 41 | 25 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `regular_expression_literals` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `shorthand_object_literals` | 43 | 12 | 33 | No | 30 | 9 | 43 | 43 | 33 | 30 | 9 | 4.0 | 1.0 | 4.0.0 |
| `string_literals` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `template_literals` | 41 | 12 | 34 | No | 28 | 9 | 41 | 41 | 34 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
| `trailing_commas` | 1 | 12 | 1 | 9 | 9.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `unicode_escape_sequences` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `unicode_point_escapes` | 44 | 12 | 40 | No | 31 | 9 | 44 | 44 | 40 | 32 | 9 | 4.0 | 1.0 | 4.0.0 |
See also
--------
* [Lexical grammar in the ECMAScript specification](https://tc39.es/ecma262/#sec-ecmascript-language-lexical-grammar)
* [Jeff Walden: Binary and octal numbers](https://whereswalden.com/2013/08/12/micro-feature-from-es6-now-in-firefox-aurora-and-nightly-binary-and-octal-numbers/)
* [Mathias Bynens: JavaScript character escape sequences](https://mathiasbynens.be/notes/javascript-escapes)
* [Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type)
* [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type)
* [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type)
* [`RegExp`](global_objects/regexp)
| programming_docs |
javascript Iteration protocols Iteration protocols
===================
**Iteration protocols** aren't new built-ins or syntax, but *protocols*. These protocols can be implemented by any object by following some conventions.
There are two protocols: The [iterable protocol](#the_iterable_protocol) and the [iterator protocol](#the_iterator_protocol).
The iterable protocol
---------------------
**The iterable protocol** allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a [`for...of`](statements/for...of) construct. Some built-in types are [built-in iterables](#built-in_iterables) with a default iteration behavior, such as [`Array`](global_objects/array) or [`Map`](global_objects/map), while other types (such as [`Object`](global_objects/object)) are not.
In order to be **iterable**, an object must implement the `@@iterator` method, meaning that the object (or one of the objects up its [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)) must have a property with a `@@iterator` key which is available via constant [`Symbol.iterator`](global_objects/symbol/iterator):
`[Symbol.iterator]` A zero-argument function that returns an object, conforming to the [iterator protocol](#the_iterator_protocol).
Whenever an object needs to be iterated (such as at the beginning of a [`for...of`](statements/for...of) loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated.
Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the `this` keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.
This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using `yield`.
The iterator protocol
---------------------
**The iterator protocol** defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.
An object is an iterator when it implements a `next()` method with the following semantics:
`next()` A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface (see below). If a non-object value gets returned (such as `false` or `undefined`) when a built-in language feature (such as `for...of`) is using the iterator, a [`TypeError`](global_objects/typeerror) (`"iterator.next() returned a non-object value"`) will be thrown.
All iterator protocol methods (`next()`, `return()`, and `throw()`) are expected to return an object implementing the `IteratorResult` interface. It must have the following properties:
`done` Optional
A boolean that's `false` if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the `done` property altogether.)
Has the value `true` if the iterator has completed its sequence. In this case, `value` optionally specifies the return value of the iterator.
`value` Optional
Any JavaScript value returned by the iterator. Can be omitted when `done` is `true`.
In practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to `{ done: false, value: undefined }`.
If an iterator returns a result with `done: true`, any subsequent calls to `next()` are expected to return `done: true` as well, although this is not enforced on the language level.
The `next` method can receive a value which will be made available to the method body. No built-in language feature will pass any value. The value passed to the `next` method of [generators](global_objects/generator) will become the value of the corresponding `yield` expression.
Optionally, the iterator can also implement the `return(value)` and `throw(exception)` methods, which, when called, tells the iterator that the caller is done with iterating it and can perform any necessary cleanup (such as closing database connection).
`return(value)` Optional
A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface, typically with `value` equal to the `value` passed in and `done` equal to `true`. Calling this method tells the iterator that the caller does not intend to make any more `next()` calls and can perform any cleanup actions.
`throw(exception)` Optional
A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface, typically with `done` equal to `true`. Calling this method tells the iterator that the caller detects an error condition, and `exception` is typically an [`Error`](global_objects/error) instance.
**Note:** It is not possible to know reflectively (i.e. without actually calling `next()` and validating the returned result) whether a particular object implements the iterator protocol.
It is very easy to make an iterator also iterable: just implement an `[@@iterator]()` method that returns `this`.
```
// Satisfies both the Iterator Protocol and Iterable
const myIterator = {
next() {
// ...
},
[Symbol.iterator]() {
return this;
},
};
```
Such object is called an *iterable iterator*. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables — therefore, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. (In fact, almost all syntaxes and APIs expect *iterables*, not *iterators*.) The [generator object](global_objects/generator) is an example:
```
const aGeneratorObject = (function\* () {
yield 1;
yield 2;
yield 3;
})();
console.log(typeof aGeneratorObject.next);
// "function" — it has a next method (which returns the right result), so it's an iterator
console.log(typeof aGeneratorObject[Symbol.iterator]);
// "function" — it has an @@iterator method (which returns the right iterator), so it's an iterable
console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
// true — its @@iterator method returns itself (an iterator), so it's an iterable iterator
```
However, when possible, it's better for `iterable[Symbol.iterator]` to return different iterators that always start from the beginning, like [`Set.prototype[@@iterator]()`](global_objects/set/@@iterator) does.
The async iterator and async iterable protocols
-----------------------------------------------
There are another pair of protocols used for async iteration, named **async iterator** and **async iterable** protocols. They have very similar interfaces compared to the iterable and iterator protocols, except that each return value from the calls to the iterator methods is wrapped in a promise.
An object implements the async iterable protocol when it implements the following methods:
[`[Symbol.asyncIterator]`](global_objects/symbol/asynciterator) A zero-argument function that returns an object, conforming to the async iterator protocol.
An object implements the async iterator protocol when it implements the following methods:
`next()` A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
`return(value)` Optional
A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
`throw(exception)` Optional
A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
Interactions between the language and iteration protocols
---------------------------------------------------------
The language specifies APIs that either produce or consume iterables and iterators.
### Built-in iterables
[`String`](global_objects/string), [`Array`](global_objects/array), [`TypedArray`](global_objects/typedarray), [`Map`](global_objects/map), [`Set`](global_objects/set), and [`Segments`](global_objects/intl/segmenter/segment/segments) (returned by [`Intl.Segmenter.prototype.segment()`](global_objects/intl/segmenter/segment)) are all built-in iterables, because each of their `prototype` objects implements an `@@iterator` method. In addition, the [`arguments`](functions/arguments) object and some DOM collection types such as [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) are also iterables. There are no built-in async iterables currently.
[Generator functions](statements/function*) return [generator objects](global_objects/generator), which are iterable iterators. [Async generator functions](statements/async_function*) return [async generator objects](global_objects/asyncgenerator), which are async iterable iterators.
The iterators returned from built-in iterables actually all inherit from a common class (currently unexposed), which implements the aforementioned `[Symbol.iterator]() { return this; }` method, making them all iterable iterators. In the future, these built-in iterators may have additional [helper methods](https://github.com/tc39/proposal-iterator-helpers) in addition to the `next()` method required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.
```
console.log([][Symbol.iterator]());
Array Iterator {}
[[Prototype]]: Array Iterator ==> This is the prototype shared by all array iterators
next: ƒ next()
Symbol(Symbol.toStringTag): "Array Iterator"
[[Prototype]]: Object ==> This is the prototype shared by all built-in iterators
Symbol(Symbol.iterator): ƒ [Symbol.iterator]()
[[Prototype]]: Object ==> This is Object.prototype
```
### Built-in APIs accepting iterables
There are many APIs that accept iterables. Some examples include:
* [`Map()`](global_objects/map/map)
* [`WeakMap()`](global_objects/weakmap/weakmap)
* [`Set()`](global_objects/set/set)
* [`WeakSet()`](global_objects/weakset/weakset)
* [`Promise.all()`](global_objects/promise/all)
* [`Promise.allSettled()`](global_objects/promise/allsettled)
* [`Promise.race()`](global_objects/promise/race)
* [`Promise.any()`](global_objects/promise/any)
* [`Array.from()`](global_objects/array/from)
```
const myObj = {};
new WeakSet(
(function\* () {
yield {};
yield myObj;
yield {};
})()
).has(myObj); // true
```
### Syntaxes expecting iterables
Some statements and expressions expect iterables, for example the [`for...of`](statements/for...of) loops, [array and parameter spreading](operators/spread_syntax), [`yield*`](operators/yield*), and [array destructuring](operators/destructuring_assignment):
```
for (const value of ["a", "b", "c"]) {
console.log(value);
}
// "a"
// "b"
// "c"
console.log([..."abc"]); // ["a", "b", "c"]
function\* gen() {
yield\* ["a", "b", "c"];
}
console.log(gen().next()); // { value: "a", done: false }
[a, b, c] = new Set(["a", "b", "c"]);
console.log(a); // "a"
```
When built-in syntaxes are iterating an iterator, and the last result's `done` is `false` (i.e. the iterator is able to produce more values) but no more values are needed, the `return` method will get called if present. This can happen, for example, if a `break` or `return` is encountered in a `for...of` loop, or if all identifiers are already bound in an array destructuring.
```
const obj = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
i++;
console.log("Returning", i);
if (i === 3) return { done: true, value: i };
return { done: false, value: i };
},
return() {
console.log("Closing");
return { done: true };
},
};
},
};
const [b] = obj;
// Returning 1
// Closing
const [a, b, c] = obj;
// Returning 1
// Returning 2
// Returning 3
// Already reached the end (the last call returned `done: true`),
// so `return` is not called
for (const b of obj) {
break;
}
// Returning 1
// Closing
```
The [`for await...of`](statements/for-await...of) loop and [`yield*`](operators/yield*) in [async generator functions](statements/async_function*) (but not [sync generator functions](statements/function*)) are the only ways to interact with async iterables. Using `for...of`, array spreading, etc. on an async iterable that's not also a sync iterable (i.e. it has `[@@asyncIterator]()` but no `[@@iterator]()`) will throw a TypeError: x is not iterable.
### Non-well-formed iterables
If an iterable's `@@iterator` method doesn't return an iterator object, then it's considered a *non-well-formed* iterable.
Using one is likely to result in runtime errors or buggy behavior:
```
const nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
```
Examples
--------
### User-defined iterables
You can make your own iterables like this:
```
const myIterable = {
\*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log([...myIterable]); // [1, 2, 3]
```
### Simple iterator
Iterators are stateful by nature. If you don't define it as a [generator function](statements/function*) (as the example above shows), you would likely want to encapsulate the state in a closure.
```
function makeIterator(array) {
let nextIndex = 0;
return {
next() {
return nextIndex < array.length
? {
value: array[nextIndex++],
done: false,
}
: {
done: true,
};
},
};
}
const it = makeIterator(["yo", "ya"]);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
```
### Infinite iterator
```
function idMaker() {
let index = 0;
return {
next() {
return {
value: index++,
done: false,
};
},
};
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// ...
```
### Defining an iterable with a generator
```
function\* makeSimpleGenerator(array) {
let nextIndex = 0;
while (nextIndex < array.length) {
yield array[nextIndex++];
}
}
const gen = makeSimpleGenerator(["yo", "ya"]);
console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done); // true
function\* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// ...
```
### Defining an iterable with a class
State encapsulation can be done with [private properties](classes/private_class_fields) as well.
```
class SimpleClass {
#data;
constructor(data) {
this.#data = data;
}
[Symbol.iterator]() {
// Use a new index for each iterator. This makes multiple
// iterations over the iterable safe for non-trivial cases,
// such as use of break or nested looping over the same iterable.
let index = 0;
return {
// Note: using an arrow function allows `this` to point to the
// one of `[@@iterator]()` instead of `next()`
next: () => {
if (index < this.#data.length) {
return { value: this.#data[index++], done: false };
} else {
return { done: true };
}
},
};
}
}
const simple = new SimpleClass([1, 2, 3, 4, 5]);
for (const val of simple) {
console.log(val); // 1 2 3 4 5
}
```
### Overriding built-in iterables
For example, a [`String`](global_objects/string) is a built-in iterable object:
```
const someString = "hi";
console.log(typeof someString[Symbol.iterator]); // "function"
```
`String`'s [default iterator](global_objects/string/@@iterator) returns the string's code points one by one:
```
const iterator = someString[Symbol.iterator]();
console.log(`${iterator}`); // "[object String Iterator]"
console.log(iterator.next()); // { value: "h", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
```
You can redefine the iteration behavior by supplying our own `@@iterator`:
```
// need to construct a String object explicitly to avoid auto-boxing
const someString = new String("hi");
someString[Symbol.iterator] = function () {
return {
// this is the iterator object, returning a single element (the string "bye")
next() {
return this._first
? { value: "bye", done: (this._first = false) }
: { done: true };
},
\_first: true,
};
};
```
Notice how redefining `@@iterator` affects the behavior of built-in constructs that use the iteration protocol:
```
console.log([...someString]); // ["bye"]
console.log(`${someString}`); // "hi"
```
See also
--------
* [`function*` declaration](statements/function*)
* [Iteration in the ECMAScript specification](https://tc39.es/ecma262/#sec-iteration)
javascript JavaScript reference JavaScript reference
====================
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](https://developer.mozilla.org/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects), along with their methods and properties.
### Value properties
* [`globalThis`](global_objects/globalthis)
* [`Infinity`](global_objects/infinity)
* [`NaN`](global_objects/nan)
* [`undefined`](global_objects/undefined)
### Function properties
* [`eval()`](global_objects/eval)
* [`isFinite()`](global_objects/isfinite)
* [`isNaN()`](global_objects/isnan)
* [`parseFloat()`](global_objects/parsefloat)
* [`parseInt()`](global_objects/parseint)
* [`decodeURI()`](global_objects/decodeuri)
* [`decodeURIComponent()`](global_objects/decodeuricomponent)
* [`encodeURI()`](global_objects/encodeuri)
* [`encodeURIComponent()`](global_objects/encodeuricomponent)
* [`escape()`](global_objects/escape) Deprecated
* [`unescape()`](global_objects/unescape) Deprecated
### Fundamental objects
* [`Object`](global_objects/object)
* [`Function`](global_objects/function)
* [`Boolean`](global_objects/boolean)
* [`Symbol`](global_objects/symbol)
### Error objects
* [`Error`](global_objects/error)
* [`AggregateError`](global_objects/aggregateerror)
* [`EvalError`](global_objects/evalerror)
* [`RangeError`](global_objects/rangeerror)
* [`ReferenceError`](global_objects/referenceerror)
* [`SyntaxError`](global_objects/syntaxerror)
* [`TypeError`](global_objects/typeerror)
* [`URIError`](global_objects/urierror)
* [`InternalError`](global_objects/internalerror) Non-standard
### Numbers and dates
* [`Number`](global_objects/number)
* [`BigInt`](global_objects/bigint)
* [`Math`](global_objects/math)
* [`Date`](global_objects/date)
### Text processing
* [`String`](global_objects/string)
* [`RegExp`](global_objects/regexp)
### Indexed collections
* [`Array`](global_objects/array)
* [`Int8Array`](global_objects/int8array)
* [`Uint8Array`](global_objects/uint8array)
* [`Uint8ClampedArray`](global_objects/uint8clampedarray)
* [`Int16Array`](global_objects/int16array)
* [`Uint16Array`](global_objects/uint16array)
* [`Int32Array`](global_objects/int32array)
* [`Uint32Array`](global_objects/uint32array)
* [`BigInt64Array`](global_objects/bigint64array)
* [`BigUint64Array`](global_objects/biguint64array)
* [`Float32Array`](global_objects/float32array)
* [`Float64Array`](global_objects/float64array)
### Keyed collections
* [`Map`](global_objects/map)
* [`Set`](global_objects/set)
* [`WeakMap`](global_objects/weakmap)
* [`WeakSet`](global_objects/weakset)
### Structured data
* [`ArrayBuffer`](global_objects/arraybuffer)
* [`SharedArrayBuffer`](global_objects/sharedarraybuffer)
* [`DataView`](global_objects/dataview)
* [`Atomics`](global_objects/atomics)
* [`JSON`](global_objects/json)
### Managing memory
* [`WeakRef`](global_objects/weakref)
* [`FinalizationRegistry`](global_objects/finalizationregistry)
### Control abstraction objects
* [`Promise`](global_objects/promise)
* [`GeneratorFunction`](global_objects/generatorfunction)
* [`AsyncGeneratorFunction`](global_objects/asyncgeneratorfunction)
* [`Generator`](global_objects/generator)
* [`AsyncGenerator`](global_objects/asyncgenerator)
* [`AsyncFunction`](global_objects/asyncfunction)
### Reflection
* [`Reflect`](global_objects/reflect)
* [`Proxy`](global_objects/proxy)
### Internationalization
* [`Intl`](global_objects/intl)
* [`Intl.Collator`](global_objects/intl/collator)
* [`Intl.DateTimeFormat`](global_objects/intl/datetimeformat)
* [`Intl.DisplayNames`](global_objects/intl/displaynames)
* [`Intl.ListFormat`](global_objects/intl/listformat)
* [`Intl.Locale`](global_objects/intl/locale)
* [`Intl.NumberFormat`](global_objects/intl/numberformat)
* [`Intl.PluralRules`](global_objects/intl/pluralrules)
* [`Intl.RelativeTimeFormat`](global_objects/intl/relativetimeformat)
* [`Intl.Segmenter`](global_objects/intl/segmenter)
Statements
----------
[JavaScript statements and declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements)
### Control flow
* [`return`](statements/return)
* [`break`](statements/break)
* [`continue`](statements/continue)
* [`throw`](statements/throw)
* [`if...else`](statements/if...else)
* [`switch`](statements/switch)
* [`try...catch`](statements/try...catch)
### Declaring variables
* [`var`](statements/var)
* [`let`](statements/let)
* [`const`](statements/const)
### Functions and classes
* [`function`](statements/function)
* [`function*`](statements/function*)
* [`async function`](statements/async_function)
* [`async function*`](statements/async_function*)
* [`class`](statements/class)
### Iterations
* [`do...while`](statements/do...while)
* [`for`](statements/for)
* [`for...in`](statements/for...in)
* [`for...of`](statements/for...of)
* [`for await...of`](statements/for-await...of)
* [`while`](statements/while)
### Others
* [Empty](statements/empty)
* [Block](statements/block)
* [Expression statement](statements/expression_statement)
* [`debugger`](statements/debugger)
* [`export`](statements/export)
* [`import`](statements/import)
* [label](statements/label)
* [`with`](statements/with) Deprecated
Expressions and operators
-------------------------
[JavaScript expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators).
### Primary expressions
* [`this`](operators/this)
* [Literals](lexical_grammar#literals)
* [`[]`](global_objects/array)
* [`{}`](operators/object_initializer)
* [`function`](operators/function)
* [`class`](operators/class)
* [`function*`](operators/function*)
* [`async function`](operators/async_function)
* [`async function*`](operators/async_function*)
* [`/ab+c/i`](global_objects/regexp)
* [``string``](template_literals)
* [`( )`](operators/grouping)
### Left-hand-side expressions
* [Property accessors](operators/property_accessors)
* [`?.`](operators/optional_chaining)
* [`new`](operators/new)
* [`new.target`](operators/new.target)
* [`import.meta`](operators/import.meta)
* [`super`](operators/super)
* [`import()`](operators/import)
### Increment and decrement
* [`A++`](operators/increment)
* [`A--`](operators/decrement)
* [`++A`](operators/increment)
* [`--A`](operators/decrement)
### Unary operators
* [`delete`](operators/delete)
* [`void`](operators/void)
* [`typeof`](operators/typeof)
* [`+`](operators/unary_plus)
* [`-`](operators/unary_negation)
* [`~`](operators/bitwise_not)
* [`!`](operators/logical_not)
* [`await`](operators/await)
### Arithmetic operators
* [`**`](operators/exponentiation)
* [`*`](operators/multiplication)
* [`/`](operators/division)
* [`%`](operators/remainder)
* [`+`](operators/addition) (Plus)
* [`-`](operators/subtraction)
### Relational operators
* [`<`](operators/less_than) (Less than)
* [`>`](operators/greater_than) (Greater than)
* [`<=`](operators/less_than_or_equal)
* [`>=`](operators/greater_than_or_equal)
* [`instanceof`](operators/instanceof)
* [`in`](operators/in)
### Equality operators
* [`==`](operators/equality)
* [`!=`](operators/inequality)
* [`===`](operators/strict_equality)
* [`!==`](operators/strict_inequality)
### Bitwise shift operators
* [`<<`](operators/left_shift)
* [`>>`](operators/right_shift)
* [`>>>`](operators/unsigned_right_shift)
### Binary bitwise operators
* [`&`](operators/bitwise_and)
* [`|`](operators/bitwise_or)
* [`^`](operators/bitwise_xor)
### Binary logical operators
* [`&&`](operators/logical_and)
* [`||`](operators/logical_or)
* [`??`](operators/nullish_coalescing)
### Conditional (ternary) operator
* [`(condition ? ifTrue : ifFalse)`](operators/conditional_operator)
### Assignment operators
* [`=`](operators/assignment)
* [`*=`](operators/multiplication_assignment)
* [`/=`](operators/division_assignment)
* [`%=`](operators/remainder_assignment)
* [`+=`](operators/addition_assignment)
* [`-=`](operators/subtraction_assignment)
* [`<<=`](operators/left_shift_assignment)
* [`>>=`](operators/right_shift_assignment)
* [`>>>=`](operators/unsigned_right_shift_assignment)
* [`&=`](operators/bitwise_and_assignment)
* [`^=`](operators/bitwise_xor_assignment)
* [`|=`](operators/bitwise_or_assignment)
* [`**=`](operators/exponentiation_assignment)
* [`&&=`](operators/logical_and_assignment)
* [`||=`](operators/logical_or_assignment)
* [`??=`](operators/nullish_coalescing_assignment)
* [`[a, b] = arr`, `{ a, b } = obj`](operators/destructuring_assignment)
### Yield operators
* [`yield`](operators/yield)
* [`yield*`](operators/yield*)
### Spread syntax
* [`...obj`](operators/spread_syntax)
### Comma operator
* [`,`](operators/comma_operator)
Functions
---------
[JavaScript functions.](functions)
* [Arrow Functions](functions/arrow_functions)
* [Default parameters](functions/default_parameters)
* [Rest parameters](functions/rest_parameters)
* [`arguments`](functions/arguments)
* [Method definitions](functions/method_definitions)
* [getter](functions/get)
* [setter](functions/set)
Classes
-------
[JavaScript classes.](classes)
* [`constructor`](classes/constructor)
* [`extends`](classes/extends)
* [Private class features](classes/private_class_fields)
* [Public class fields](classes/public_class_fields)
* [`static`](classes/static)
* [Static initialization blocks](classes/static_initialization_blocks)
Additional reference pages
--------------------------
* [Lexical grammar](lexical_grammar)
* [Data types and data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
* [Iteration protocols](iteration_protocols)
* [Trailing commas](trailing_commas)
* [Errors](errors)
* [Strict mode](strict_mode)
* [Deprecated features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features)
| programming_docs |
javascript Functions Functions
=========
Generally speaking, a function is a "subprogram" that can be *called* by code external (or internal, in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the *function body*. Values can be *passed* to a function as parameters, and the function will *return* a value.
In JavaScript, functions are [first-class objects](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function), because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.
For more examples and explanations, see the [JavaScript guide about functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions).
Description
-----------
Function values are typically instances of [`Function`](global_objects/function). See [`Function`](global_objects/function) for information on properties and methods of `Function` objects. Callable values cause [`typeof`](operators/typeof) to return `"function"` instead of `"object"`.
**Note:** Not all callable values are `instanceof Function`. For example, the `Function.prototype` object is callable but not an instance of `Function`. You can also manually set the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of your function so it no longer inherits from `Function.prototype`. However, such cases are extremely rare.
By default, if a function's execution doesn't end at a [`return`](statements/return) statement, or if the `return` keyword doesn't have an expression after it, then the return value is [`undefined`](global_objects/undefined). The `return` statement allows you to return an arbitrary value from the function. One function call can only return one value, but you can simulate the effect of returning multiple values by returning an object or array and [destructuring](operators/destructuring_assignment) the result.
**Note:** Constructors called with [`new`](operators/new) have a different set of logic to determine their return values.
[Parameters and arguments](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments) have slightly different meanings, but in MDN web docs, we often use them interchangeably. For a quick reference:
```
function formatNumber(num) {
return num.toFixed(2);
}
formatNumber(2);
```
In this example, the `num` variable is called the function's *parameter*: it's declared in the bracket-enclosed list of the function's definition. The function expects the `num` parameter to be a number — although this is not enforceable in JavaScript without writing runtime validation code. In the `formatNumber(2)` call, the number `2` is the function's *argument*: it's the value that is actually passed to the function in the function call. The argument value can be accessed inside the function body through the corresponding parameter name or the [`arguments`](functions/arguments) object.
Arguments are always [*passed by value*](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference) and never *passed by reference*. This means that if a function reassigns a parameter, the value won't change outside the function. More precisely, object arguments are [*passed by sharing*](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), which means if the object's properties are mutated, the change will impact the outside of the function. For example:
```
function updateBrand(obj) {
// Mutating the object is visible outside the function
obj.brand = "Toyota";
// Try to reassign the parameter, but this won't affect
// the variable's value outside the function
obj = null;
}
const car = {
brand: "Honda",
model: "Accord",
year: 1998,
};
console.log(car.brand); // Honda
// Pass object reference to the function
updateBrand(car);
// updateBrand mutates car
console.log(car.brand); // Toyota
```
The [`this`](operators/this) keyword refers to the object that the function is accessed on — it does not refer to the currently executing function, so you must refer to the function value by name, even within the function body.
### Defining functions
Broadly speaking, JavaScript has four kinds of functions:
* Regular function: can return anything; always runs to completion after invocation
* Generator function: returns a [`Generator`](global_objects/generator) object; can be paused and resumed with the [`yield`](operators/yield) operator
* Async function: returns a [`Promise`](global_objects/promise); can be paused and resumed with the [`await`](operators/await) operator
* Async generator function: returns an [`AsyncGenerator`](global_objects/asyncgenerator) object; both the `await` and `yield` operators can be used
For every kind of function, there are three ways to define it:
Declaration [`function`](statements/function), [`function*`](statements/function*), [`async function`](statements/async_function), [`async function*`](statements/async_function*)
Expression [`function`](operators/function), [`function*`](operators/function*), [`async function`](operators/async_function), [`async function*`](operators/async_function*)
Constructor [`Function()`](global_objects/function/function), [`GeneratorFunction()`](global_objects/generatorfunction/generatorfunction), [`AsyncFunction()`](global_objects/asyncfunction/asyncfunction), [`AsyncGeneratorFunction()`](global_objects/asyncgeneratorfunction/asyncgeneratorfunction)
In addition, there are special syntaxes for defining [arrow functions](functions/arrow_functions) and [methods](functions/method_definitions), which provide more precise semantics for their usage. [Classes](classes) are conceptually not functions (because they throw an error when called without `new`), but they also inherit from `Function.prototype` and have `typeof MyClass === "function"`.
```
// Constructor
const multiply = new Function("x", "y", "return x \* y");
// Declaration
function multiply(x, y) {
return x \* y;
} // No need for semicolon here
// Expression; the function is anonymous but assigned to a variable
const multiply = function (x, y) {
return x \* y;
};
// Expression; the function has its own name
const multiply = function funcName(x, y) {
return x \* y;
};
// Arrow function
const multiply = (x, y) => x \* y;
// Method
const obj = {
multiply(x, y) {
return x \* y;
},
};
```
All syntaxes do approximately the same thing, but there are some subtle behavior differences.
* The `Function()` constructor, `function` expression, and `function` declaration syntaxes create full-fledged function objects, which can be constructed with [`new`](operators/new). However, arrow functions and methods cannot be constructed. Async functions, generator functions, and async generator functions are not constructible regardless of syntax.
* The `function` declaration creates functions that are [*hoisted*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_hoisting). Other syntaxes do not hoist the function and the function value is only visible after the definition.
* The arrow function and `Function()` constructor always create *anonymous* functions, which means they can't easily call themselves recursively. One way to call an arrow function recursively is by assigning it to a variable.
* The arrow function syntax does not have access to `arguments` or `this`.
* The `Function()` constructor cannot access any local variables — it only has access to the global scope.
* The `Function()` constructor causes runtime compilation and is often slower than other syntaxes.
For `function` expressions, there is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be different from the variable the function is assigned to — they have no relation to each other. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or gets another value, if the same name is declared elsewhere). For example:
```
const y = function x() {};
console.log(x); // ReferenceError: x is not defined
```
On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.
A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in, as well as in their own body.
A function defined by `new Function` will dynamically have its source assembled, which is observable when you serialize it. For example, `console.log(new Function().toString())` gives:
```
function anonymous(
) {
}
```
This is the actual source used to compile the function. However, although the `Function()` constructor will create the function with name `anonymous`, this name is not added to the scope of the body. The body only ever has access to global variables. For example, the following would result in an error:
```
new Function("alert(anonymous);")();
```
A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a `Function` constructor does not inherit any scope other than the global scope (which all functions inherit).
```
// p is a global variable
globalThis.p = 5;
function myFunc() {
// p is a local variable
const p = 9;
function decl() {
console.log(p);
}
const expr = function () {
console.log(p);
};
const cons = new Function("\tconsole.log(p);");
decl();
expr();
cons();
}
myFunc();
// Logs:
// 9 (for 'decl' by function declaration (current scope))
// 9 (for 'expr' by function expression (current scope))
// 5 (for 'cons' by Function constructor (global scope))
```
Functions defined by function expressions and function declarations are parsed only once, while a function defined by the `Function` constructor parses the string passed to it each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than `new Function(...)`. Therefore the `Function` constructor should generally be avoided whenever possible.
A function declaration may be unintentionally turned into a function expression when it appears in an expression context.
```
// A function declaration
function foo() {
console.log("FOO!");
}
doSomething(
// A function expression passed as an argument
function foo() {
console.log("FOO!");
}
);
```
On the other hand, a function expression may also be turned into a function declaration. An expression statement cannot begin with the `function` or `async function` keywords, which is a common mistake when implementing [IIFEs](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expressions).
```
function () { // SyntaxError: Function statements require a function name
console.log("FOO!");
}();
function foo() {
console.log("FOO!");
}(); // SyntaxError: Unexpected token ')'
```
Instead, start the expression statement with something else, so that the `function` keyword unambiguously starts a function expression. Common options include [grouping](operators/grouping) and using [`void`](operators/void).
```
(function () {
console.log("FOO!");
})();
void function () {
console.log("FOO!");
}();
```
### Function parameters
Each function parameter is a simple identifier that you can access in the local scope.
```
function myFunc(a, b, c) {
// You can access the values of a, b, and c here
}
```
There are three special parameter syntaxes:
* [*Default parameters*](functions/default_parameters) allow formal parameters to be initialized with default values if no value or `undefined` is passed.
* The [*rest parameter*](functions/rest_parameters) allows representing an indefinite number of arguments as an array.
* [*Destructuring*](operators/destructuring_assignment) allows unpacking elements from arrays, or properties from objects, into distinct variables.
```
function myFunc({ a, b }, c = 1, ...rest) {
// You can access the values of a, b, c, and rest here
}
```
There are some consequences if one of the above non-simple parameter syntaxes is used:
* You cannot apply `"use strict"` to the function body — this causes a [syntax error](errors/strict_non_simple_params).
* Even if the function is not in [strict mode](strict_mode), the [`arguments`](functions/arguments) object stops syncing with the named parameters, and [`arguments.callee`](functions/arguments/callee) throws an error when accessed.
### The arguments object
You can refer to a function's arguments within the function by using the [`arguments`](functions/arguments) object.
[`arguments`](functions/arguments) An array-like object containing the arguments passed to the currently executing function.
[`arguments.callee`](functions/arguments/callee) The currently executing function.
[`arguments.length`](functions/arguments/length) The number of arguments passed to the function.
### Getter and setter functions
You can define accessor properties on any standard built-in object or user-defined object that supports the addition of new properties. Within [object literals](operators/object_initializer) and <classes>, you can use special syntaxes to define the getter and setter of an accessor property.
[get](functions/get) Binds an object property to a function that will be called when that property is looked up.
[set](functions/set) Binds an object property to a function to be called when there is an attempt to set that property.
Note that these syntaxes create an *object property*, not a *method*. The getter and setter functions themselves can only be accessed using reflective APIs such as [`Object.getOwnPropertyDescriptor()`](global_objects/object/getownpropertydescriptor).
### Block-level functions
In [strict mode](strict_mode), functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.
```
"use strict";
function f() {
return 1;
}
{
function f() {
return 2;
}
}
f() === 1; // true
// f() === 2 in non-strict mode
```
### Block-level functions in non-strict code
In a word: **Don't.**
In non-strict code, function declarations inside blocks behave strangely. For example:
```
if (shouldDefineZero) {
function zero() {
// DANGER: compatibility risk
console.log("This is zero.");
}
}
```
The semantics of this in strict mode are well-specified — `zero` only ever exists within that scope of the `if` block. If `shouldDefineZero` is false, then `zero` should never be defined, since the block never executes. However, historically, this was left unspecified, so different browsers implemented it differently in non-strict mode. For more information, see the [`function` declaration](statements/function#block-level_function_declaration) reference.
A safer way to define functions conditionally is to assign a function expression to a variable:
```
// Using a var makes it available as a global variable,
// with closer behavior to a top-level function declaration
var zero;
if (shouldDefineZero) {
zero = function () {
console.log("This is zero.");
};
}
```
Examples
--------
### Returning a formatted number
The following function returns a string containing the formatted representation of a number padded with leading zeros.
```
// This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
let numStr = num.toString(); // Initialize return value as string
const numZeros = totalLen - numStr.length; // Calculate no. of zeros
for (let i = 1; i <= numZeros; i++) {
numStr = `0${numStr}`;
}
return numStr;
}
```
The following statements call the `padZeros` function.
```
let result;
result = padZeros(42, 4); // returns "0042"
result = padZeros(42, 2); // returns "42"
result = padZeros(5, 4); // returns "0005"
```
### Determining whether a function exists
You can determine whether a function exists by using the [`typeof`](operators/typeof) operator. In the following example, a test is performed to determine if the `window` object has a property called `noFunc` that is a function. If so, it is used; otherwise, some other action is taken.
```
if (typeof window.noFunc === "function") {
// use noFunc()
} else {
// do something else
}
```
Note that in the `if` test, a reference to `noFunc` is used — there are no brackets `()` after the function name so the actual function is not called.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Functions` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `arguments` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `arrow_functions` | 45 | 12 | 22
["The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of `'use strict';` is now required.", "Before Firefox 39, a line terminator (`\\n`) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like `() \\n => {}` will now throw a `SyntaxError` in this and later versions."] | No | 32 | 10 | 45 | 45 | 22
["The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of `'use strict';` is now required.", "Before Firefox 39, a line terminator (`\\n`) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like `() \\n => {}` will now throw a `SyntaxError` in this and later versions."] | 32 | 10 | 5.0 | 1.0 | 4.0.0
0.12.0
The arrow function syntax is supported, but not the correct lexical binding of the `this` value. |
| `block_level_functions` | 49 | 12 | 46 | 11 | 36 | 10 | 49 | 49 | 46 | 36 | 10 | 5.0 | 1.0 | 4.0.0
0.10.0 |
| `default_parameters` | 49 | 14 | 15 | No | 36 | 10 | 49 | 49 | 15 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `get` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
| `method_definitions` | 39 | 12 | 34 | No | 26 | 9 | 39 | 39 | 34 | 26 | 9 | 4.0 | 1.0 | 4.0.0 |
| `rest_parameters` | 47 | 12 | 15 | No | 34 | 10 | 47 | 47 | 15 | 34 | 10 | 5.0 | 1.0 | 6.0.0
4.0.0 |
| `set` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`function` declaration](statements/function)
* [`function` expression](operators/function)
* [`function*` declaration](statements/function*)
* [`function*` expressions](operators/function*)
* [`Function`](global_objects/function)
* [`GeneratorFunction`](global_objects/generatorfunction)
* [Arrow functions](functions/arrow_functions)
* [Rest parameters](functions/rest_parameters)
* [Default parameters](functions/default_parameters)
* [Method definitions](functions/method_definitions)
* [getter](functions/get)
* [setter](functions/set)
* [The `arguments` object](functions/arguments)
| programming_docs |
javascript Trailing commas Trailing commas
===============
**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](https://developer.mozilla.org/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.
```
[
"foo",
+ "baz",
"bar",
- "baz",
]
```
Examples
--------
### Trailing commas in literals
#### Arrays
JavaScript ignores trailing commas in arrays literals:
```
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*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) (a *dense* array has no holes). When iterating arrays for example with [`Array.prototype.forEach()`](global_objects/array/foreach) or [`Array.prototype.map()`](global_objects/array/map), array holes are skipped. Sparse arrays are generally unfavorable, so you should avoid having multiple trailing commas.
```
const arr = [1, 2, 3, , ,];
arr.length; // 5
```
#### Objects
Trailing commas in object literals are legal as well:
```
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`](global_objects/function/length) property of function declarations or their [`arguments`](functions/arguments) object.
```
function f(p) {}
function f(p,) {}
(p) => {};
(p,) => {};
```
The trailing comma also works with [method definitions](functions/method_definitions) for classes or objects:
```
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.
```
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 [`SyntaxError`](global_objects/syntaxerror). Furthermore, when using [rest parameters](functions/rest_parameters), trailing commas are not allowed:
```
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](operators/destructuring_assignment):
```
// 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 [`SyntaxError`](global_objects/syntaxerror) will be thrown:
```
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`:
```
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:
```
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](statements/import#named_import) and [named exports](statements/export).
#### Named imports
```
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
```
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers) actually changes its semantics from matching "exactly `n`" to matching "at least `n`".
```
/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
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-Elision](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-Elision) |
| [ECMAScript Language Specification # prod-ObjectLiteral](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-ObjectLiteral) |
| [ECMAScript Language Specification # prod-ArrayLiteral](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-ArrayLiteral) |
| [ECMAScript Language Specification # prod-Arguments](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-Arguments) |
| [ECMAScript Language Specification # prod-FormalParameters](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#prod-FormalParameters) |
| [ECMAScript Language Specification # prod-CoverParenthesizedExpressionAndArrowParameterList](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-CoverParenthesizedExpressionAndArrowParameterList) |
| [ECMAScript Language Specification # prod-NamedImports](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#prod-NamedImports) |
| [ECMAScript Language Specification # prod-NamedExports](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#prod-NamedExports) |
| [ECMAScript Language Specification # prod-QuantifierPrefix](https://tc39.es/ecma262/multipage/text-processing.html#prod-QuantifierPrefix) |
| [ECMAScript Language Specification # prod-annexB-InvalidBracedQuantifier](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#prod-annexB-InvalidBracedQuantifier) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Trailing_commas` | 1 | 12 | 1 | 9 | 9.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `trailing_commas_in_dynamic_import` | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | No | 15 | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | 15 | 16.0 | 1.17 | 17.5.0
17.0.0-17.5.0
16.15.0-17.0.0
16.14.0-16.15.0
The second parameter no longer throws a parser error, but the `--experimental-json-modules` flag is still needed to load JSON modules.
16.0.0-16.14.0 |
| `trailing_commas_in_functions` | 58 | 14 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
| `trailing_commas_in_object_literals` | 1 | 12 | 1 | 9 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* Initial ECMAScript proposal: [trailing function commas](https://github.com/tc39/proposal-trailing-function-commas) by Jeff Morrison
javascript Classes 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](https://developer.mozilla.org/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_Classes) guide.
Description
-----------
### Defining classes
Classes are in fact "special <functions>", and just as you can define [function expressions](operators/function) and [function declarations](statements/function), a class can be defined in two ways: a [class expression](operators/class) or a [class declaration](statements/class).
```
// 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](statements/let#temporal_dead_zone_tdz) restrictions as `let` or `const` and behave as if they are [not hoisted](https://developer.mozilla.org/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 brackets `{}`. This is where you define class members, such as methods or constructor.
The body of a class is executed in [strict mode](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](functions/method_definitions) Public instance method
[getter](functions/get) Public instance getter
[setter](functions/set) Public instance setter
[Public class fields](classes/public_class_fields) Public instance field
[`static`](classes/static) Public static method, getter, setter, and field
[Private class features](classes/private_class_fields) Everything that's private
In addition, there are two special class element syntaxes: [`constructor`](#constructor) and [static initialization blocks](#static_initialization_blocks), with their own references.
#### Constructor
The [`constructor`](classes/constructor) method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class — a [`SyntaxError`](global_objects/syntaxerror) is thrown if the class contains more than one occurrence of a `constructor` method.
A constructor can use the [`super`](operators/super) keyword to call the constructor of the super class.
You can create instance properties inside the constructor:
```
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](#public_field_declarations).
#### Static initialization blocks
[Static initialization blocks](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](functions/method_definitions).
```
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 [`static`](classes/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 you don't need to be replicated across instances.
```
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:
```
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 fields](#private_field_declarations) 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](classes/public_class_fields) for more information.
#### Private class features
Using private fields, the definition can be refined as below.
```
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 class features](classes/private_class_fields).
### Inheritance
The [`extends`](classes/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).
```
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 [`super`](operators/super) keyword can also be used to call corresponding methods of super class.
```
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.
```
Examples
--------
### Binding this with instance and static methods
When a static or instance method is called without a value for [`this`](operators/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"`](strict_mode) directive isn't present, because code within the `class` body is always executed in strict mode.
```
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 [`globalThis`](global_objects/globalthis). In strict mode, the value of `this` remains as `undefined`.
```
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
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-class-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Classes` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
| `constructor` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
| `extends` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
| `private_class_fields` | 74 | 79 | 90 | No | 62 | 14.1 | 74 | 74 | 90 | 53 | 14.5 | 11.0 | 1.0 | 12.0.0 |
| `private_class_fields_in` | 91 | 91 | 90 | No | 77 | 15 | 91 | 91 | 90 | 64 | 15 | 16.0 | 1.9 | 16.4.0 |
| `private_class_methods` | 84 | 84 | 90 | No | 70 | 15 | 84 | 84 | 90 | 60 | 15 | 14.0 | 1.0 | 14.6.0 |
| `public_class_fields` | 72 | 79 | 69 | No | 60 | 14.1
14-14.1
Doesn't support public static fields. See WebKit bug [194095](https://webkit.org/b/194095). | 72 | 72 | 79 | 51 | 14.5
14-14.5
Doesn't support public static fields. See WebKit bug [194095](https://webkit.org/b/194095). | 11.0 | 1.0 | 12.0.0 |
| `static` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
| `static_class_fields` | 72 | 79 | 75 | No | 60 | 14.1 | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.0 | 12.0.0 |
| `static_initialization_blocks` | 94 | 94 | 93 | No | 80 | No | 94 | 94 | 93 | 66 | No | 17.0 | 1.14 | 16.11.0 |
See also
--------
* [Functions](functions)
* [class declaration](statements/class)
* [class expression](operators/class)
* [Public class fields](classes/public_class_fields)
* [Private class features](classes/private_class_fields)
* [`super`](operators/super)
* [Blog post: "ES6 In Depth: Classes"](https://hacks.mozilla.org/2015/07/es6-in-depth-classes/)
* [Fields and public/private class properties proposal (stage 3)](https://github.com/tc39/proposal-class-fields)
| programming_docs |
javascript JavaScript error reference JavaScript error reference
==========================
Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the [`Error`](global_objects/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](https://developer.mozilla.org/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!
* [Error: Permission denied to access property "x"](errors/property_access_denied)
* [InternalError: too much recursion](errors/too_much_recursion)
* [RangeError: BigInt division by zero](errors/bigint_division_by_zero)
* [RangeError: BigInt negative exponent](errors/bigint_negative_exponent)
* [RangeError: argument is not a valid code point](errors/not_a_codepoint)
* [RangeError: invalid array length](errors/invalid_array_length)
* [RangeError: invalid date](errors/invalid_date)
* [RangeError: precision is out of range](errors/precision_range)
* [RangeError: radix must be an integer](errors/bad_radix)
* [RangeError: repeat count must be less than infinity](errors/resulting_string_too_large)
* [RangeError: repeat count must be non-negative](errors/negative_repetition_count)
* [RangeError: x can't be converted to BigInt because it isn't an integer](errors/cant_be_converted_to_bigint_because_it_isnt_an_integer)
* [ReferenceError: "x" is not defined](errors/not_defined)
* [ReferenceError: assignment to undeclared variable "x"](errors/undeclared_var)
* [ReferenceError: can't access lexical declaration 'X' before initialization](errors/cant_access_lexical_declaration_before_init)
* [ReferenceError: deprecated caller or arguments usage](errors/deprecated_caller_or_arguments_usage)
* [ReferenceError: reference to undefined property "x"](errors/undefined_prop)
* [SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated](errors/deprecated_octal)
* [SyntaxError: "use strict" not allowed in function with non-simple parameters](errors/strict_non_simple_params)
* [SyntaxError: "x" is a reserved identifier](errors/reserved_identifier)
* [SyntaxError: JSON.parse: bad parsing](errors/json_bad_parse)
* [SyntaxError: Malformed formal parameter](errors/malformed_formal_parameter)
* [SyntaxError: Unexpected '#' used outside of class body](errors/hash_outside_class)
* [SyntaxError: Unexpected token](errors/unexpected_token)
* [SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead](errors/deprecated_source_map_pragma)
* [SyntaxError: a declaration in the head of a for-of loop can't have an initializer](errors/invalid_for-of_initializer)
* [SyntaxError: applying the 'delete' operator to an unqualified name is deprecated](errors/delete_in_strict_mode)
* [SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions](errors/cant_use_nullish_coalescing_unparenthesized)
* [SyntaxError: for-in loop head declarations may not have initializers](errors/invalid_for-in_initializer)
* [SyntaxError: function statement requires a name](errors/unnamed_function_statement)
* [SyntaxError: identifier starts immediately after numeric literal](errors/identifier_after_number)
* [SyntaxError: illegal character](errors/illegal_character)
* [SyntaxError: invalid BigInt syntax](errors/invalid_bigint_syntax)
* [SyntaxError: invalid assignment left-hand side](errors/invalid_assignment_left-hand_side)
* [SyntaxError: invalid regular expression flag "x"](errors/bad_regexp_flag)
* [SyntaxError: missing ) after argument list](errors/missing_parenthesis_after_argument_list)
* [SyntaxError: missing ) after condition](errors/missing_parenthesis_after_condition)
* [SyntaxError: missing : after property id](errors/missing_colon_after_property_id)
* [SyntaxError: missing ; before statement](errors/missing_semicolon_before_statement)
* [SyntaxError: missing = in const declaration](errors/missing_initializer_in_const)
* [SyntaxError: missing ] after element list](errors/missing_bracket_after_list)
* [SyntaxError: missing formal parameter](errors/missing_formal_parameter)
* [SyntaxError: missing name after . operator](errors/missing_name_after_dot_operator)
* [SyntaxError: missing variable name](errors/no_variable_name)
* [SyntaxError: missing } after function body](errors/missing_curly_after_function_body)
* [SyntaxError: missing } after property list](errors/missing_curly_after_property_list)
* [SyntaxError: redeclaration of formal parameter "x"](errors/redeclared_parameter)
* [SyntaxError: return not in function](errors/bad_return_or_yield)
* [SyntaxError: test for equality (==) mistyped as assignment (=)?](errors/equal_as_assign)
* [SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '\*\*'](errors/unparenthesized_unary_expr_lhs_exponentiation)
* [SyntaxError: unterminated string literal](errors/unterminated_string_literal)
* [TypeError: "x" has no properties](errors/no_properties)
* [TypeError: "x" is (not) "y"](errors/unexpected_type)
* [TypeError: "x" is not a constructor](errors/not_a_constructor)
* [TypeError: "x" is not a function](errors/not_a_function)
* [TypeError: "x" is not a non-null object](errors/no_non-null_object)
* [TypeError: "x" is read-only](errors/read-only)
* [TypeError: 'x' is not iterable](errors/is_not_iterable)
* [TypeError: More arguments needed](errors/more_arguments_needed)
* [TypeError: Reduce of empty array with no initial value](errors/reduce_of_empty_array_with_no_initial_value)
* [TypeError: X.prototype.y called on incompatible type](errors/called_on_incompatible_type)
* [TypeError: can't access dead object](errors/dead_object)
* [TypeError: can't assign to property "x" on "y": not an object](errors/cant_assign_to_property)
* [TypeError: can't convert BigInt to number](errors/cant_convert_bigint_to_number)
* [TypeError: can't convert x to BigInt](errors/cant_convert_x_to_bigint)
* [TypeError: can't define property "x": "obj" is not extensible](errors/cant_define_property_object_not_extensible)
* [TypeError: can't delete non-configurable array element](errors/non_configurable_array_element)
* [TypeError: can't redefine non-configurable property "x"](errors/cant_redefine_property)
* [TypeError: cannot use 'in' operator to search for 'x' in 'y'](errors/in_operator_no_object)
* [TypeError: cyclic object value](errors/cyclic_object_value)
* [TypeError: invalid 'instanceof' operand 'x'](errors/invalid_right_hand_side_instanceof_operand)
* [TypeError: invalid Array.prototype.sort argument](errors/array_sort_argument)
* [TypeError: invalid assignment to const "x"](errors/invalid_const_assignment)
* [TypeError: property "x" is non-configurable and can't be deleted](errors/cant_delete)
* [TypeError: setting getter-only property "x"](errors/getter_only)
* [URIError: malformed URI sequence](errors/malformed_uri)
* [Warning: 08/09 is not a legal ECMA-262 octal constant](errors/bad_octal)
* [Warning: -file- is being assigned a //# sourceMappingURL, but already has one](errors/already_has_pragma)
* [Warning: Date.prototype.toLocaleFormat is deprecated](errors/deprecated_tolocaleformat)
* [Warning: String.x is deprecated; use String.prototype.x instead](errors/deprecated_string_generics)
* [Warning: expression closures are deprecated](errors/deprecated_expression_closures)
* [Warning: unreachable code after return statement](errors/stmt_after_return)
javascript Strict mode Strict mode
===========
**Note:** Sometimes you'll see the default, non-strict mode referred to as *[sloppy mode](https://developer.mozilla.org/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](https://developer.mozilla.org/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](statements/block) enclosed in `{}` braces; attempting to apply it to such contexts does nothing. [`eval`](global_objects/eval) code, [`Function`](global_objects/function/function) code, [event handler](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#event_handler_attributes) attributes, strings passed to [`setTimeout()`](https://developer.mozilla.org/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.
```
// 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.
```
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](functions/rest_parameters), [default](functions/default_parameters), or [destructured](operators/destructuring_assignment) parameters is a [syntax error](errors/strict_non_simple_params).
```
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) are automatically in strict mode, with no statement needed to initiate it.
```
function myStrictFunction() {
// because this is a module, I'm strict by default
}
export default myStrictFunction;
```
### Strict mode for classes
All parts of a [class](classes)'s body are strict mode code, including both [class declarations](classes#class_declarations) and [class expressions](classes#class_expressions).
```
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:
```
"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](global_objects/object/isextensible) object
For example, [`NaN`](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.
```
"use strict";
// Assignment to a non-writable global
var undefined = 5; // TypeError
var 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](operators/delete) a non-configurable or otherwise undeletable (e.g. it's intercepted by a proxy's [`deleteProperty`](global_objects/proxy/proxy/deleteproperty) handler which returns `false`) property throw in strict mode (where before the attempt would have no effect):
```
"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:
```
"use strict";
var x;
delete x; // syntax error
```
If the name is a configurable global property, prefix it with [`globalThis`](global_objects/globalthis) to delete it.
```
"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`](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:
```
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](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:
```
"use strict";
const sum =
015 + // syntax error
197 +
142;
```
The standardized way to denote octal literals is via the `0o` prefix. For example:
```
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-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](https://developer.mozilla.org/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 [`TypeError`](global_objects/typeerror) is thrown.
```
"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 [`SyntaxError`](global_objects/syntaxerror) in strict mode. With the introduction of [computed property names](operators/object_initializer), making duplication possible at runtime, this restriction was removed in ES2015.
```
"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`](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:
```
"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:
```
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](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](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`](functions/arguments) and [`eval`](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:
```
"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]`.
```
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`](global_objects/function/call), [`apply`](global_objects/function/apply), or [`bind`](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`](global_objects/globalthis):
```
"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)());
```
#### 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`](global_objects/function/caller) is the function that most recently called `fun`, and [`fun.arguments`](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:
```
function restricted() {
"use strict";
restricted.caller; // throws a TypeError
restricted.arguments; // throws a TypeError
}
function privilegedInvoker() {
return restricted();
}
privilegedInvoker();
```
Similarly, [`arguments.callee`](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:
```
"use strict";
const f = function () {
return arguments.callee;
};
f(); // throws a TypeError
```
### Future-proofing JavaScript
#### Extra reserved words
[Reserved words](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`](statements/let)
* `package`
* `private`
* `protected`
* `public`
* [`static`](classes/static)
* [`yield`](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 [`SyntaxError`](global_objects/syntaxerror) before the script is executing:
* Octal syntax `const n = 023;`
* [`with`](statements/with) statement
* Using [`delete`](operators/delete) on a variable name `delete myVariable`;
* Using [`eval`](global_objects/eval) or [`arguments`](functions/arguments) as variable or function argument name
* Using one of the newly [reserved keywords](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://bugzilla.mozilla.org/show_bug.cgi?id=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 [`ReferenceError`](global_objects/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 [`TypeError`](global_objects/typeerror). In sloppy mode, this would silently fail.
* Deleting a non-deletable property throws a [`TypeError`](global_objects/typeerror). In sloppy mode, this would silently fail.
* Accessing [`arguments.callee`](functions/arguments/callee), [`strictFunction.caller`](global_objects/function/caller), or [`strictFunction.arguments`](global_objects/function/arguments) throws a [`TypeError`](global_objects/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`](global_objects/function/call) or [`apply`](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.
See also
--------
* [Strict Mode Code in the ECMAScript specification](https://tc39.es/ecma262/#sec-strict-mode-code)
* [Strict mode compatibility table](https://kangax.github.io/compat-table/es5/#Strict_mode)
| programming_docs |
javascript Template literals (Template strings) Template literals (Template strings)
====================================
Template literals are literals delimited with backtick (```) characters, allowing for [multi-line strings](#multi-line_strings), [string interpolation](#string_interpolation) with embedded expressions, and special constructs called [tagged templates](#tagged_templates).
Template literals are sometimes informally called *template strings*, because they are used most commonly for [string interpolation](#string_interpolation) (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom [tag function](#tagged_templates) to perform whatever operations you want on the different parts of the template literal.
Syntax
------
```
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tagFunction`string text ${expression} string text`
```
### Parameters
`string text` The string text that will become part of the template literal. Almost all characters are allowed literally, including [line breaks](lexical_grammar#line_terminators) and other [whitespace characters](lexical_grammar#white_space). However, invalid escape sequences will cause a syntax error, unless a [tag function](#tagged_templates_and_escape_sequences) is used.
`expression` An expression to be inserted in the current position, whose value is converted to a string or passed to `tagFunction`.
`tagFunction` If specified, it will be called with the template strings array and substitution expressions, and the return value becomes the value of the template literal. See [tagged templates](#tagged_templates).
Description
-----------
Template literals are enclosed by backtick (```) characters instead of double or single quotes.
Along with having normal strings, template literals can also contain other parts called *placeholders*, which are embedded expressions delimited by a dollar sign and curly braces: `${expression}`. The strings and placeholders get passed to a function — either a default function, or a function you supply. The default function (when you don't supply your own) just performs [string interpolation](#string_interpolation) to do substitution of the placeholders and then concatenate the parts into a single string.
To supply a function of your own, precede the template literal with a function name; the result is called a [**tagged template**](#tagged_templates). In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal.
To escape a backtick in a template literal, put a backslash (`\`) before the backtick.
```
`\`` === "`"; // true
```
Dollar signs can be escaped as well to prevent interpolation.
```
`\${1}` === "${1}"; // true
```
### Multi-line strings
Any newline characters inserted in the source are part of the template literal.
Using normal strings, you would have to use the following syntax in order to get multi-line strings:
```
console.log("string text line 1\n" + "string text line 2");
// "string text line 1
// string text line 2"
```
Using template literals, you can do the same with this:
```
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
```
### String interpolation
Without template literals, when you want to combine output from expressions with strings, you'd [concatenate them](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Strings#concatenation_using_) using the [addition operator](operators/addition) `+`:
```
const a = 5;
const b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 \* a + b) + ".");
// "Fifteen is 15 and
// not 20."
```
That can be hard to read – especially when you have multiple expressions.
With template literals, you can avoid the concatenation operator — and improve the readability of your code — by using placeholders of the form `${expression}` to perform substitutions for embedded expressions:
```
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 \* a + b}.`);
// "Fifteen is 15 and
// not 20."
```
Note that there's a mild difference between the two syntaxes. Template literals [coerce their expressions directly to strings](global_objects/string#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](operators/addition).
### Nesting templates
In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backtick-delimited template, it is simple to allow inner backticks by using them inside an `${expression}` placeholder within the template.
For example, without template literals, if you wanted to return a certain value based on a particular condition, you could do something like the following:
```
let classes = "header";
classes += isLargeScreen()
? ""
: item.isCollapsed
? " icon-expander"
: " icon-collapser";
```
With a template literal but without nesting, you could do this:
```
const classes = `header ${
isLargeScreen() ? "" : item.isCollapsed ? "icon-expander" : "icon-collapser"
}`;
```
With nesting of template literals, you can do this:
```
const classes = `header ${
isLargeScreen() ? "" : `icon-${item.isCollapsed ? "expander" : "collapser"}`
}`;
```
### Tagged templates
A more advanced form of template literals are *tagged* templates.
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something completely different, as described in one of the following examples.)
The name of the function used for the tag can be whatever you want.
```
const person = "Mike";
const age = 28;
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp > 99 ? "centenarian" : "youngster";
// We can even return a string built using a template literal
return `${str0}${personExp}${str1}${ageStr}${str2}`;
}
const output = myTag`That ${person} is a ${age}.`;
console.log(output);
// That Mike is a youngster.
```
The tag does not have to be a plain identifier. You can use any expression with [precedence](operators/operator_precedence#table) greater than 16, which includes [property access](operators/property_accessors), function call, [new expression](operators/new), or even another tagged template literal.
```
console.log`Hello`; // [ 'Hello' ]
console.log.bind(1, 2)`Hello`; // 2 [ 'Hello' ]
new Function("console.log(arguments)")`Hello`; // [Arguments] { '0': [ 'Hello' ] }
function recursive(strings, ...values) {
console.log(strings, values);
return recursive;
}
recursive`Hello``World`;
// [ 'Hello' ] []
// [ 'World' ] []
```
While technically permitted by the syntax, *untagged* template literals are strings and will throw a [`TypeError`](global_objects/typeerror) when chained.
```
console.log(`Hello``World`); // TypeError: "Hello" is not a function
```
The only exception is optional chaining, which will throw a syntax error.
```
console.log?.`Hello`; // SyntaxError: Invalid tagged template on optional chain
console?.log`Hello`; // SyntaxError: Invalid tagged template on optional chain
```
Note that these two expressions are still parsable. This means they would not be subject to [automatic semicolon insertion](lexical_grammar#automatic_semicolon_insertion), which will only insert semicolons to fix code that's otherwise unparsable.
```
// Still a syntax error
const a = console?.log
`Hello`
```
Tag functions don't even need to return a string!
```
function template(strings, ...keys) {
return (...values) => {
const dict = values[values.length - 1] || {};
const result = [strings[0]];
keys.forEach((key, i) => {
const value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join("");
};
}
const t1Closure = template`${0}${1}${0}!`;
// const t1Closure = template(["","","","!"],0,1,0);
t1Closure("Y", "A"); // "YAY!"
const t2Closure = template`${0}${"foo"}!`;
// const t2Closure = template([""," ","!"],0,"foo");
t2Closure("Hello", { foo: "World" }); // "Hello World!"
const t3Closure = template`I'm ${"name"}. I'm almost ${"age"} years old.`;
// const t3Closure = template(["I'm ", ". I'm almost ", " years old."], "name", "age");
t3Closure("foo", { name: "MDN", age: 30 }); // "I'm MDN. I'm almost 30 years old."
t3Closure({ name: "MDN", age: 30 }); // "I'm MDN. I'm almost 30 years old."
```
The first argument received by the tag function is an array of strings. For any template literal, its length is equal to the number of substitutions (occurrences of `${…}`) plus one, and is therefore always non-empty.
For any particular tagged template literal expression, the tag function will always be called with the exact same literal array, no matter how many times the literal is evaluated.
```
const callHistory = [];
function tag(strings, ...values) {
callHistory.push(strings);
// Return a freshly made object
return {};
}
function evaluateLiteral() {
return tag`Hello, ${"world"}!`;
}
console.log(evaluateLiteral() === evaluateLiteral()); // false; each time `tag` is called, it returns a new object
console.log(callHistory[0] === callHistory[1]); // true; all evaluations of the same tagged literal would pass in the same strings array
```
This allows the tag to cache the result based on the identity of its first argument. To further ensure the array value's stability, the first argument and its [`raw` property](#raw_strings) are both [frozen](global_objects/object/isfrozen), so you can't mutate them in any way.
### Raw strings
The special `raw` property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing [escape sequences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings).
```
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// Logs "string text line 1 \n string text line 2" ,
// including the two characters '\' and 'n'
```
In addition, the [`String.raw()`](global_objects/string/raw) method exists to create raw strings just like the default template function and string concatenation would create.
```
const str = String.raw`Hi\n${2 + 3}!`;
// "Hi\\n5!"
str.length;
// 6
Array.from(str).join(",");
// "H,i,\\,n,5,!"
```
`String.raw` functions like an "identity" tag if the literal doesn't contain any escape sequences. In case you want an actual identity tag that always works as if the literal is untagged, you can make a custom function that passes the "cooked" (i.e. escape sequences are processed) literal array to `String.raw`, pretending they are raw strings.
```
const identity = (strings, ...values) =>
String.raw({ raw: strings }, ...values);
console.log(identity`Hi\n${2 + 3}!`);
// Hi
// 5!
```
This is useful for many tools which give special treatment to literals tagged by a particular name.
```
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>`;
```
### Tagged templates and escape sequences
In normal template literals, [the escape sequences in string literals](global_objects/string#escape_sequences) are all allowed. Any other non-well-formed escape sequence is a syntax error. This includes:
* `\` followed by any decimal digit other than `0`, or `\0` followed by a decimal digit; for example `\9` and `\07` (which is a [deprecated syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences))
* `\x` followed by fewer than two hex digits (including none); for example `\xz`
* `\u` not followed by `{` and followed by fewer than four hex digits (including none); for example `\uz`
* `\u{}` enclosing an invalid Unicode code point — it contains a non-hex digit, or its value is greater than `10FFFF`; for example `\u{110000}` and `\u{z}`
**Note:** `\` followed by other characters, while they may be useless since nothing is escaped, are not syntax errors.
However, this is problematic for tagged templates, which, in addition to the "cooked" literal, also have access to the raw literals (escape sequences are preserved as-is).
Tagged templates should allow the embedding of languages (for example [DSLs](https://en.wikipedia.org/wiki/Domain-specific_language), or [LaTeX](https://en.wikipedia.org/wiki/LaTeX)), where other escapes sequences are common. Therefore, the syntax restriction of well-formed escape sequences is removed from tagged templates.
```
latex`\unicode`;
// Throws in older ECMAScript versions (ES2016 and earlier)
// SyntaxError: malformed Unicode character escape sequence
```
However, illegal escape sequences must still be represented in the "cooked" representation. They will show up as [`undefined`](global_objects/undefined) element in the "cooked" array:
```
function latex(str) {
return { cooked: str[0], raw: str.raw[0] };
}
latex`\unicode`;
// { cooked: undefined, raw: "\\unicode" }
```
Note that the escape-sequence restriction is only dropped from *tagged* templates, but not from *untagged* template literals:
```
const bad = `bad escape sequence: \unicode`;
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-template-literals](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-template-literals) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Template_literals` | 41 | 12 | 34 | No | 28 | 9 | 41 | 41 | 34 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
| `template_literal_revision` | 62 | 79 | 53 | No | 49 | 11 | 62 | 62 | 53 | 46 | 11 | 8.0 | 1.0 | 8.10.0
8.0.0 |
See also
--------
* [`String`](global_objects/string)
* [`String.raw()`](global_objects/string/raw)
* [Lexical grammar](lexical_grammar)
* [Template-like strings in ES3 compatible syntax](https://gist.github.com/WebReflection/8f227532143e63649804)
* ["ES6 in Depth: Template strings" on hacks.mozilla.org](https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/)
javascript Bitwise NOT (~) Bitwise NOT (~)
===============
The `~` operator inverts the bits of its operand. Like other bitwise operators, it converts the operand to a 32-bit signed integer
Try it
------
Syntax
------
```
~a
```
Description
-----------
The operand is converted to a 32-bit signed integer and expressed as a series of bits (zeroes 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 signed integer:
```
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
Each bit in the operand is inverted in the result.
The truth table for the `NOT` operation is:
| a | NOT a |
| --- | --- |
| 0 | 1 |
| 1 | 0 |
```
9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
```
The 32-bit signed integer operand is inverted according to [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement). That is, the presence of the most significant bit is used to express negative integers.
Bitwise NOTing any number `x` yields `-(x + 1)`. For example, `~-5` yields `4`.
Note that due to using 32-bit representation for numbers both `~-1` and `~4294967295` (232 - 1) results in `0`.
Examples
--------
### Using bitwise NOT
```
~0; // -1
~-1; // 0
~1; // -2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bitwise-not-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-bitwise-not-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_NOT` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
javascript super super
=====
The `super` keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.
The `super.prop` and `super[expr]` expressions are valid in any [method definition](../functions/method_definitions) in both [classes](../classes) and [object literals](object_initializer). The `super(...args)` expression is valid in class constructors.
Syntax
------
```
super([arguments]) // calls the parent constructor.
super.propertyOnParent
super[expression]
```
Description
-----------
The `super` keyword can be used in two ways: as a "function call" (`super(...args)`), or as a "property lookup" (`super.prop` and `super[expr]`).
**Note:** `super` is a keyword and these are special syntactic constructs. `super` is not a variable that points to the prototype object. Attempting to read `super` itself is a [`SyntaxError`](../global_objects/syntaxerror).
```
const child = {
myParent() {
console.log(super); // SyntaxError: 'super' keyword unexpected here
},
};
```
In the [constructor](../classes/constructor) body of a derived class (with `extends`), the `super` keyword may appear as a "function call" (`super(...args)`), which must be called before the `this` keyword is used, and before the constructor returns. It calls the parent class's constructor and binds the parent class's public fields, after which the derived class's constructor can further access and modify `this`.
The "property lookup" form can be used to access methods and properties of an object literal's or class's [[Prototype]]. Within a class's body, the reference of `super` can be either the superclass's constructor itself, or the constructor's `prototype`, depending on whether the execution context is instance creation or class initialization. See the Examples section for more details.
Note that the reference of `super` is determined by the class or object literal `super` was declared in, not the object the method is called on. Therefore, unbinding or re-binding a method doesn't change the reference of `super` in it (although they do change the reference of [`this`](this)). You can see `super` as a variable in the class or object literal scope, which the methods create a closure over. (But also beware that it's not actually not a variable, as explained above.)
When setting properties through `super`, the property is set on `this` instead.
Examples
--------
### Using super in classes
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)). Here `super()` is called to avoid duplicating the constructor parts' that are common between `Rectangle` and `Square`.
```
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log(`Hi, I am a ${this.name}.`);
}
get area() {
return this.height \* this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle'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';
}
}
```
### Super-calling static methods
You are also able to call super on [static](../classes/static) methods.
```
class Rectangle {
static logNbSides() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
static logDescription() {
return `${super.logNbSides()} which are all equal`;
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
```
### Accessing super in class field declaration
`super` can also be accessed during class field initialization. The reference of `super` depends on whether the current field is an instance field or a static field.
```
class Base {
static baseStaticField = 90;
baseMethod() {
return 10;
}
}
class Extended extends Base {
extendedField = super.baseMethod(); // 10
static extendedStaticField = super.baseStaticField; // 90
}
```
Note that instance fields are set on the instance instead of the constructor's `prototype`, so you can't use `super` to access the instance field of a superclass.
```
class Base {
baseField = 10;
}
class Extended extends Base {
extendedField = super.baseField; // undefined
}
```
Here, `extendedField` is `undefined` instead of 10, because `baseField` is defined as an own property of the `Base` instance, instead of `Base.prototype`. `super`, in this context, only looks up properties on `Base.prototype`, because that's the [[Prototype]] of `Extended.prototype`.
### Deleting super properties will throw an error
You cannot use the [`delete` operator](delete) and `super.prop` or `super[expr]` to delete a parent class' property — it will throw a [`ReferenceError`](../global_objects/referenceerror).
```
class Base {
foo() {}
}
class Derived extends Base {
delete() {
delete super.foo; // this is bad
}
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'.
```
### Using super.prop in object literals
Super can also be used in the [object initializer](object_initializer) notation. In this example, two objects define a method. In the second object, `super` calls the first object's method. This works with the help of [`Object.setPrototypeOf()`](../global_objects/object/setprototypeof) with which we are able to set the prototype of `obj2` to `obj1`, so that `super` is able to find `method1` on `obj1`.
```
const obj1 = {
method1() {
console.log('method 1');
}
}
const obj2 = {
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // Logs "method 1"
```
### Methods that read super.prop do not behave differently when bound to other objects
Accessing `super.x` behaves like `Reflect.get(Object.getPrototypeOf(objectLiteral), "x", this)`, which means the property is always seeked on the object literal/class declaration's prototype, and unbinding and re-binding a method won't change the reference of `super`.
```
class Base {
baseGetX() {
return 1;
}
}
class Extended extends Base {
getX() {
return super.baseGetX();
}
}
const e = new Extended();
console.log(e.getX()); // 1
const { getX } = e;
console.log(getX()); // 1
```
The same happens in object literals.
```
const parent1 = { prop: 1 };
const parent2 = { prop: 2 };
const child = {
myParent() {
console.log(super.prop);
},
};
Object.setPrototypeOf(child, parent1);
child.myParent(); // Logs "1"
const myParent = child.myParent;
myParent(); // Still logs "1"
const anotherChild = { \_\_proto\_\_: parent2, myParent };
anotherChild.myParent(); // Still logs "1"
```
Only resetting the entire inheritance chain will change the reference of `super`.
```
class Base {
baseGetX() { return 1; }
static staticBaseGetX() { return 3; }
}
class AnotherBase {
baseGetX() { return 2; }
static staticBaseGetX() { return 4; }
}
class Extended extends Base {
getX() { return super.baseGetX(); }
static staticGetX() { return super.staticBaseGetX(); }
}
const e = new Extended();
// Reset instance inheritance
Object.setPrototypeOf(Extended.prototype, AnotherBase.prototype);
console.log(e.getX()); // Logs "2" instead of "1", because the prototype chain has changed
console.log(Extended.staticGetX()); // Still logs "3", because we haven't modified the static part yet
// Reset static inheritance
Object.setPrototypeOf(Extended, AnotherBase);
console.log(Extended.staticGetX()); // Now logs "4"
```
### Calling methods from super
When calling `super.prop` as a function, the `this` value inside the `prop` function is the current `this`, not the object that `super` points to. For example, the `super.getName()` call logs `"Extended"`, despite the code looking like it's equivalent to `Base.getName()`.
```
class Base {
static getName() {
console.log(this.name);
}
}
class Extended extends Base {
static getName() {
super.getName();
}
}
Extended.getName(); // Logs "Extended"
```
This is especially important when interacting with [static private properties](../classes/private_class_fields#private_static_fields).
### Setting super.prop sets the property on this instead
Setting properties of `super`, such as `super.x = 1`, behaves like `Reflect.set(Object.getPrototypeOf(objectLiteral), "x", 1, this)`. This is one of the cases where understanding `super` as simply "reference of the prototype object" falls short, because it actually sets the property on `this` instead.
```
class A {}
class B extends A {
setX() {
super.x = 1;
}
}
const b = new B();
b.setX();
console.log(b); // B { x: 1 }
console.log(Object.hasOwn(b, "x")); // true
```
`super.x = 1` will look for the property descriptor of `x` on `A.prototype` (and invoke the setters defined there), but the `this` value will be set to `this`, which is `b` in this context. You can read [`Reflect.set`](../global_objects/reflect/set) for more details on the case when `target` and `receiver` differ.
This means that while methods that *get* `super.prop` are usually not susceptible to changes in the `this` context, those that *set* `super.prop` are.
```
/\* Reusing same declarations as above \*/
const b2 = new B();
b2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'
```
However, `super.x = 1` still consults the property descriptor of the prototype object, which means you cannot rewrite non-writable properties, and setters will be invoked.
```
class X {
constructor() {
// Create a non-writable property
Object.defineProperty(this, 'prop', {
configurable: true,
writable: false,
value: 1,
});
}
}
class Y extends X {
constructor() {
super();
}
foo() {
super.prop = 2; // Cannot overwrite the value.
}
}
const y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-super-keyword](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-super-keyword) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `super` | 42 | 13 | 45 | No | 29 | 7 | 42 | 42 | 45 | 29 | 7 | 4.0 | 1.0 | 6.0.0 |
See also
--------
* [Classes](../classes)
| programming_docs |
javascript Multiplication assignment (*=) Multiplication assignment (\*=)
===============================
The `*=` operator multiplies a variable by the value of the right operand and assigns the result to the variable.
Try it
------
Syntax
------
```
x \*= y // x = x \* y
```
Examples
--------
### Using multiplication assignment
```
let bar = 5;
bar \*= 2; // 10
bar \*= 'foo'; // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Multiplication_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Multiplication operator](multiplication)
javascript Optional chaining (?.) Optional chaining (?.)
======================
The `?.` operator accesses an object's property or calls a function. If the object accessed or function called is [`undefined`](../global_objects/undefined) or [`null`](null), it returns [`undefined`](../global_objects/undefined) instead of throwing an error.
Try it
------
Syntax
------
```
obj.val?.prop
obj.val?.[expr]
obj.func?.(args)
```
Description
-----------
The `?.` operator is like the `.` chaining operator, except that instead of causing an error if a reference is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) ([`null`](null) or [`undefined`](../global_objects/undefined)), the expression short-circuits with a return value of `undefined`. When used with function calls, it returns `undefined` if the given function does not exist.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
For example, consider an object `obj` which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:
```
const nestedProp = obj.first && obj.first.second;
```
The value of `obj.first` is confirmed to be non-`null` (and non-`undefined`) before then accessing the value of `obj.first.second`. This prevents the error that would occur if you accessed `obj.first.second` directly without testing `obj.first`.
This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if `obj.first` is a [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value that's not `null` or `undefined`, such as `0`, it would still short-circuit and make `nestedProp` become `0`, which may not be desirable.
With the optional chaining operator (`?.`), however, you don't have to explicitly test and short-circuit based on the state of `obj.first` before trying to access `obj.first.second`:
```
const nestedProp = obj.first?.second;
```
By using the `?.` operator instead of just `.`, JavaScript knows to implicitly check to be sure `obj.first` is not `null` or `undefined` before attempting to access `obj.first.second`. If `obj.first` is `null` or `undefined`, the expression automatically short-circuits, returning `undefined`.
This is equivalent to the following, except that the temporary variable is in fact not created:
```
const temp = obj.first;
const nestedProp =
temp === null || temp === undefined ? undefined : temp.second;
```
Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value `undefined`.
```
undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined
```
### Optional chaining with function calls
You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.
Using optional chaining with function calls causes the expression to automatically return `undefined` instead of throwing an exception if the method isn't found:
```
const result = someInterface.customMethod?.();
```
However, if there is a property with such a name which is not a function, using `?.` will still raise a [`TypeError`](../global_objects/typeerror) exception "someInterface.customMethod is not a function".
**Note:** If `someInterface` itself is `null` or `undefined`, a [`TypeError`](../global_objects/typeerror) exception will still be raised ("someInterface is null"). If you expect that `someInterface` itself may be `null` or `undefined`, you have to use `?.` at this position as well: `someInterface?.customMethod?.()`.
`eval?.()` is the shortest way to enter [*indirect eval*](../global_objects/eval#direct_and_indirect_eval) mode.
### Optional chaining with expressions
You can also use the optional chaining operator with [bracket notation](property_accessors#bracket_notation), which allows passing an expression as the property name:
```
const nestedProp = obj?.["prop" + "Name"];
```
This is particularly useful for arrays, since array indices must be accessed with brackets.
```
function printMagicIndex(arr) {
console.log(arr?.[42]);
}
printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined
printMagicIndex(); // undefined; if not using ?., this would throw
```
### Optional chaining not valid on the left-hand side of an assignment
It is invalid to try to assign to the result of an optional chaining expression:
```
const object = {};
object?.property = 1; // SyntaxError: Invalid left-hand side in assignment
```
### Short-circuiting
When using optional chaining with expressions, if the left operand is `null` or `undefined`, the expression will not be evaluated. For instance:
```
const potentiallyNullObj = null;
let x = 0;
const prop = potentiallyNullObj?.[x++];
console.log(x); // 0 as x was not incremented
```
Subsequent property accesses will not be evaluated either.
```
const potentiallyNullObj = null;
const prop = potentiallyNullObj?.a.b;
// This does not throw, because evaluation has already stopped at
// the first optional chain
```
This is equivalent to:
```
const potentiallyNullObj = null;
const prop =
potentiallyNullObj === null || potentiallyNullObj === undefined
? undefined
: potentiallyNullObj.a.b;
```
However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you [group](grouping) one part of the chain, then subsequent property accesses will still be evaluated.
```
const potentiallyNullObj = null;
const prop = (potentiallyNullObj?.a).b;
// TypeError: Cannot read properties of undefined (reading 'b')
```
This is equivalent to:
```
const potentiallyNullObj = null;
const temp = potentiallyNullObj?.a;
const prop = temp.b;
```
Except the `temp` variable isn't created.
Examples
--------
### Basic example
This example looks for the value of the `name` property for the member `bar` in a map when there is no such member. The result is therefore `undefined`.
```
const myMap = new Map();
myMap.set("foo", { name: "baz", desc: "inga" });
const nameBar = myMap.get("bar")?.name;
```
### Dealing with optional callbacks or event handlers
If you use callbacks or fetch methods from an object with [a destructuring assignment](destructuring_assignment#object_destructuring), you may have non-existent values that you cannot call as functions unless you have tested their existence. Using `?.`, you can avoid this extra test:
```
// Code written without optional chaining
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
// Testing if onError really exists
if (onError) {
onError(err.message);
}
}
}
```
```
// Using optional chaining with function calls
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
onError?.(err.message); // No exception if onError is undefined
}
}
```
### Stacking the optional chaining operator
With nested structures, it is possible to use optional chaining multiple times:
```
const customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls", // Detailed address is unknown
},
};
const customerCity = customer.details?.address?.city;
// This also works with optional chaining function call
const customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined
```
### Combining with the nullish coalescing operator
The [nullish coalescing operator](nullish_coalescing) may be used after optional chaining in order to build a default value when none was found:
```
function printCustomerCity(customer) {
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity);
}
printCustomerCity({
name: "Nathan",
city: "Paris",
}); // "Paris"
printCustomerCity({
name: "Carl",
details: { age: 82 },
}); // "Unknown city"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-OptionalExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-OptionalExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Optional_chaining` | 80 | 80 | 74 | No | 67 | 13.1 | 80 | 80 | 79 | 57 | 13.4 | 13.0 | 1.0 | 14.0.0 |
See also
--------
* The [nullish coalescing operator](nullish_coalescing)
javascript Property accessors Property accessors
==================
**Property accessors** provide access to an object's properties by using the dot notation or the bracket notation.
Try it
------
Syntax
------
```
object.propertyName
object[expression]
```
Description
-----------
One can think of an object as an *associative array* (a.k.a. *map*, *dictionary*, *hash*, *lookup table*). The *keys* in this array are the names of the object's [properties](https://developer.mozilla.org/en-US/docs/Glossary/Property/JavaScript).
There are two ways to access properties: *dot notation* and *bracket notation*.
### Dot notation
In the `object.propertyName` syntax, the `propertyName` must be a valid JavaScript [identifier](../lexical_grammar#identifiers) which can also be a [reserved word](../lexical_grammar#keywords). For example, `object.$1` is valid, while `object.1` is not.
```
const variable = object.propertyName;
object.propertyName = value;
```
```
const object = {};
object.$1 = "foo";
console.log(object.$1); // 'foo'
```
```
const object = {};
object.1 = 'bar'; // SyntaxError
console.log(object.1); // SyntaxError
```
Here, the method named `createElement` is retrieved from `document` and is called.
```
document.createElement("pre");
```
If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave [white-space(s)](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
```
77 .toExponential();
// or
77
.toExponential();
// or
(77).toExponential();
// or
77..toExponential();
// or
77.0.toExponential();
// because 77. === 77.0, no ambiguity
```
### Bracket notation
In the `object[expression]` syntax, the `expression` should evaluate to a string or [Symbol](../global_objects/symbol) that represents the property's name. So, it can be any string literal, for example, including `'1foo'`, `'!bar!'`, or even `' '` (a space).
```
const variable = object[propertyName];
object[propertyName] = value;
```
This does the exact same thing as the previous example.
```
document["createElement"]("pre");
```
A space before bracket notation is allowed.
```
document ["createElement"]("pre");
```
Passing expressions that evaluate to property name will do the same thing as directly passing the property name.
```
const key = "name";
const getKey = () => "name";
const Obj = { name: "Michel" };
Obj["name"]; // returns "Michel"
Obj[key]; // evaluates to Obj["name"], and returns "Michel"
Obj[getKey()]; // evaluates to Obj["name"], and returns "Michel"
```
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).
### Property names
Property names are string or [Symbol](../global_objects/symbol). Any other value, including a number, is coerced to a string. This outputs `'value'`, since `1` is coerced into `'1'`.
```
const object = {};
object["1"] = "value";
console.log(object[1]);
```
This also outputs `'value'`, since both `foo` and `bar` are converted to the same string.
```
const foo = { uniqueProp: 1 };
const bar = { uniqueProp: 2 };
const object = {};
object[foo] = "value";
console.log(object[bar]);
```
### Method binding
It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a [`Function`](../global_objects/function) instance as its value).
A method is not bound to the object that it is a property of. Specifically, `this` is not fixed in a method and does not necessarily refer to the object containing the method. Instead, `this` is "passed" by the function call. See [the reference for `this`](this).
Examples
--------
### Bracket notation vs. eval()
JavaScript novices often make the mistake of using [`eval()`](../global_objects/eval) where the bracket notation can be used instead.
For example, the following syntax is often seen in many scripts.
```
const x = eval(`document.forms.form\_name.elements.${strFormControl}.value`);
```
`eval()` is slow and should be avoided whenever possible. Also, `strFormControl` would have to hold an identifier, which is not required for names and `id`s of form controls. It is better to use bracket notation instead:
```
const x = document.forms.form_name.elements[strFormControl].value;
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-property-accessors](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-property-accessors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Property_Accessors` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Object`](../global_objects/object)
* [`Object.defineProperty()`](../global_objects/object/defineproperty)
* [Optional chaining](optional_chaining)
javascript Addition (+) Addition (+)
============
The `+` operator produces the sum of numeric operands or string concatenation.
Try it
------
Syntax
------
```
x + y
```
Description
-----------
The addition operator (`+`) is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it first [coerces both operands to primitives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion). Then, the two operands' types are tested:
* If one side is a string, the other operand is also [converted to a string](../global_objects/string#string_coercion) and they are concatenated.
* If they are both [BigInts](../global_objects/bigint), BigInt addition is performed. If one side is a BigInt but the other is not, a [`TypeError`](../global_objects/typeerror) is thrown.
* Otherwise, both sides are [converted to numbers](../global_objects/number#number_coercion), and numeric addition is performed.
String concatenation is often thought to be equivalent with [template literals](../template_literals) or [`String.prototype.concat()`](../global_objects/string/concat), but they are not. Addition coerces the expression to a *primitive*, which calls [`valueOf()`](../global_objects/object/valueof) in priority; on the other hand, template literals and `concat()` coerce the expression to a *string*, which calls [`toString()`](../global_objects/object/tostring) in priority. If the expression has a [`@@toPrimitive`](../global_objects/symbol/toprimitive) method, string concatenation calls it with `"default"` as hint, while template literals use `"string"`. This is important for objects that have different string and primitive representations — such as [Temporal](https://github.com/tc39/proposal-temporal), whose `valueOf()` method throws.
```
const t = Temporal.Now.instant();
"" + t; // Throws TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'
```
You are advised to not use `"" + x` to perform [string coercion](../global_objects/string#string_coercion).
Examples
--------
### Numeric addition
```
// Number + Number -> addition
1 + 2 // 3
// Boolean + Number -> addition
true + 1 // 2
// Boolean + Boolean -> addition
false + false // 0
```
### String concatenation
```
// String + String -> concatenation
'foo' + 'bar' // "foobar"
// Number + String -> concatenation
5 + 'foo' // "5foo"
// String + Boolean -> concatenation
'foo' + false // "foofalse"
// String + Number -> concatenation
'2' + 2 // "22"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-addition-operator-plus](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-addition-operator-plus) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Addition` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript Subtraction assignment (-=) Subtraction assignment (-=)
===========================
The `-=` operator subtracts the value of the right operand from a variable and assigns the result to the variable.
Try it
------
Syntax
------
```
x -= y // x = x - y
```
Examples
--------
### Using subtraction assignment
```
let bar = 5;
bar -= 2; // 3
bar -= 'foo'; // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Subtraction_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Subtraction operator](subtraction)
| programming_docs |
javascript Decrement (--) Decrement (--)
==============
The `--` operator decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Try it
------
Syntax
------
```
x--
--x
```
Description
-----------
If used postfix, with operator after operand (for example, `x--`), the decrement operator decrements and returns the value before decrementing.
If used prefix, with operator before operand (for example, `--x`), the decrement operator decrements and returns the value after decrementing.
The decrement operator can only be applied on operands that are references (variables and object properties; i.e. valid [assignment targets](assignment)). `--x` itself evaluates to a value, not a reference, so you cannot chain multiple decrement operators together.
```
--(--x); // SyntaxError: Invalid left-hand side expression in prefix operation
```
Examples
--------
### Postfix decrement
```
let x = 3;
const y = x--;
// x = 2
// y = 3
```
### Prefix decrement
```
let x = 3;
const y = --x;
// x = 2
// y = 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-postfix-decrement-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-postfix-decrement-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Decrement` | 2 | 12 | 1 | 3 | 3 | 4 | 4.4 | 18 | 4 | 10.1 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript Multiplication (*) Multiplication (\*)
===================
The `*` operator produces the product of the operands.
Try it
------
Syntax
------
```
x \* y
```
Examples
--------
### Multiplication using numbers
```
2 \* 2 // 4
-2 \* 2 // -4
```
### Multiplication with Infinity
```
Infinity \* 0 // NaN
Infinity \* Infinity // Infinity
```
### Multiplication with non-numbers
```
'foo' \* 2 // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-multiplicative-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-multiplicative-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Multiplication` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript Unsigned right shift assignment (>>>=) Unsigned right shift assignment (>>>=)
======================================
The `>>>=` operator moves the specified amount of bits to the right and assigns the result to the variable.
Try it
------
Syntax
------
```
x >>>= y // x = x >>> y
```
Examples
--------
### Using unsigned right shift assignment
```
let a = 5; // (00000000000000000000000000000101)
a >>>= 2; // 1 (00000000000000000000000000000001)
let b = -5; // (-00000000000000000000000000000101)
b >>>= 2; // 1073741822 (00111111111111111111111111111110)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Unsigned_right_shift_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Unsigned right shift operator](unsigned_right_shift)
javascript this this
====
A function's `this` keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between [strict mode](../strict_mode) and non-strict mode.
In most cases, the value of `this` is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. The [`bind()`](../global_objects/function/bind) method can [set the value of a function's `this` regardless of how it's called](#the_bind_method), and [arrow functions](../functions/arrow_functions) don't provide their own `this` binding (it retains the `this` value of the enclosing lexical context).
Try it
------
Syntax
------
```
this
```
### Value
In non–strict mode, `this` is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.
Description
-----------
The value of `this` depends on in which context it appears: function, class, or global.
### Function context
Inside a function, the value of `this` depends on how the function is called. Think about `this` as a hidden parameter of a function — just like the parameters declared in the function definition, `this` is a binding that the language creates for you when the function body is evaluated.
For a typical function, the value of `this` is the object that the function is accessed on. In other words, if the function call is in the form `obj.f()`, then `this` refers to `obj`. For example:
```
function getThis() {
return this;
}
const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };
obj1.getThis = getThis;
obj2.getThis = getThis;
console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }
console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }
```
Note how the function is the same, but based on how it's invoked, the value of `this` is different. This is analogous to how function parameters work.
The value of `this` is not the object that has the function as an own property, but the object that is used to call the function. You can prove this by calling a method of an object up in the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
```
const obj3 = {
\_\_proto\_\_: obj1,
name: "obj3",
};
console.log(obj3.getThis()); // { name: 'obj3' }
```
The value of `this` always changes based on how a function is called, even when the function was defined on an object at creation:
```
const obj4 = {
name: "obj4",
getThis() {
return this;
},
};
const obj5 = { name: "obj5" };
obj5.getThis = obj4.getThis;
console.log(obj5.getThis()); // { name: 'obj5', getThis: [Function: getThis] }
```
If the value that the method is accessed on is a primitive, `this` will be a primitive value as well — but only if the function is in strict mode.
```
function getThisStrict() {
"use strict"; // Enter strict mode
return this;
}
// Only for demonstration — you should not mutate built-in prototypes
Number.prototype.getThisStrict = getThisStrict;
console.log(typeof (1).getThisStrict()); // "number"
```
If the function is called without being accessed on anything, `this` will be `undefined` — but only if the function is in strict mode.
```
console.log(typeof getThisStrict()); // "undefined"
```
In non-strict mode, a special process called [`this` substitution](../strict_mode#no_this_substitution) ensures that the value of `this` is always an object. This means:
* If a function is called with `this` set to `undefined` or `null`, `this` gets substituted with [`globalThis`](../global_objects/globalthis).
* If the function is called with `this` set to a primitive value, `this` gets substituted with the primitive value's wrapper object.
```
function getThis() {
return this;
}
// Only for demonstration — you should not mutate built-in prototypes
Number.prototype.getThis = getThis;
console.log(typeof (1).getThis()); // "object"
console.log(getThis() === globalThis); // true
```
In typical function calls, `this` is implicitly passed like a parameter through the function's prefix (the part before the dot). You can also explicitly set the value of `this` using the [`Function.prototype.call()`](../global_objects/function/call), [`Function.prototype.apply()`](../global_objects/function/apply), or [`Reflect.apply()`](../global_objects/reflect/apply) methods. Using [`Function.prototype.bind()`](../global_objects/function/bind), you can create a new function with a specific value of `this` that doesn't change regardless of how the function is called. When using these methods, the `this` substitution rules above still apply if the function is non-strict.
#### Callbacks
When a function is passed as a callback, the value of `this` depends on how the callback is called, which is determined by the implementor of the API. Callbacks are *typically* called with a `this` value of `undefined` (calling it directly without attaching it to any object), which means if the function is non–strict, the value of `this` is the global object ([`globalThis`](../global_objects/globalthis)). This is the case for [iterative array methods](../global_objects/array#iterative_methods), the [`Promise()`](../global_objects/promise/promise) constructor, [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), etc.
```
function logThis() {
"use strict";
console.log(this);
}
[1, 2, 3].forEach(logThis); // undefined, undefined, undefined
setTimeout(logThis, 1000); // undefined
```
Some APIs allow you to set a `this` value for invocations of the callback. For example, all iterative array methods and related ones like [`Set.prototype.forEach()`](../global_objects/set/foreach) accept an optional `thisArg` parameter.
```
[1, 2, 3].forEach(logThis, { name: "obj" });
// { name: 'obj' }, { name: 'obj' }, { name: 'obj' }
```
Occasionally, a callback is called with a `this` value other than `undefined`. For example, the `reviver` parameter of [`JSON.parse()`](../global_objects/json/parse) and the `replacer` parameter of [`JSON.stringify()`](../global_objects/json/stringify) are both called with `this` set to the object that the property being parsed/serialized belongs to.
#### Arrow functions
In [arrow functions](../functions/arrow_functions), `this` retains the value of the enclosing lexical context's `this`. In other words, when evaluating an arrow function's body, the language does not create a new `this` binding.
For example, in global code, `this` is always `globalThis` regardless of strictness, because of the [global context](#global_context) binding:
```
const globalObject = this;
const foo = () => this;
console.log(foo() === globalObject); // true
```
Arrow functions create a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) over the `this` value of its surrounding scope, which means arrow functions behave as if they are "auto-bound" — no matter how it's invoked, `this` is set to what it was when the function was created (in the example above, the global object). The same applies to arrow functions created inside other functions: their `this` remains that of the enclosing lexical context. [See example below](#this_in_arrow_functions).
Furthermore, when invoking arrow functions using `call()`, `bind()`, or `apply()`, the `thisArg` parameter is ignored. You can still pass other arguments using these methods, though.
```
const obj = { name: "obj" };
// Attempt to set this using call
console.log(foo.call(obj) === globalObject); // true
// Attempt to set this using bind
const boundFoo = foo.bind(obj);
console.log(boundFoo() === globalObject); // true
```
#### Constructors
When a function is used as a constructor (with the [`new`](new) keyword), its `this` is bound to the new object being constructed, no matter which object the constructor function is accessed on. The value of `this` becomes the value of the `new` expression unless the constructor returns another non–primitive value.
```
function C() {
this.a = 37;
}
let o = new C();
console.log(o.a); // 37
function C2() {
this.a = 37;
return { a: 38 };
}
o = new C2();
console.log(o.a); // 38
```
In the second example (`C2`), because an object was returned during construction, the new object that `this` was bound to gets discarded. (This essentially makes the statement `this.a = 37;` dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)
#### super
When a function is invoked in the `super.method()` form, the `this` inside the `method` function is the same value as the `this` value around the `super.method()` call, and is generally not equal to the object that `super` refers to. This is because `super.method` is not an object member access like the ones above — it's a special syntax with different binding rules. For examples, see the [`super` reference](super#calling_methods_from_super).
### Class context
A [class](../classes) can be split into two contexts: static and instance. [Constructors](../classes/constructor), methods, and instance field initializers ([public](../classes/public_class_fields) or [private](../classes/private_class_fields)) belong to the instance context. [Static](../classes/static) methods, static field initializers, and [static initialization blocks](../classes/static_initialization_blocks) belong to the static context. The `this` value is different in each context.
Class constructors are always called with `new`, so their behavior is the same as [function constructors](#constructors): the `this` value is the new instance being created. Class methods behave like methods in object literals — the `this` value is the object that the method was accessed on. If the method is not transferred to another object, `this` is generally an instance of the class.
Static methods are not properties of `this`. They are properties of the class itself. Therefore, they are generally accessed on the class, and `this` is the value of the class (or a subclass). Static initialization blocks are also evaluated with `this` set to the current class.
Field initializers are also evaluated in the context of the class. Instance fields are evaluated with `this` set to the instance being constructed. Static fields are evaluated with `this` set to the current class. This is why arrow functions in field initializers are [bound to the class](../functions/arrow_functions#cannot_be_used_as_methods).
```
class C {
instanceField = this;
static staticField = this;
}
const c = new C();
console.log(c.instanceField === c); // true
console.log(C.staticField === C); // true
```
#### Derived class constructors
Unlike base class constructors, derived constructors have no initial `this` binding. Calling [`super()`](super) creates a `this` binding within the constructor and essentially has the effect of evaluating the following line of code, where `Base` is the base class:
```
this = new Base();
```
**Warning:** Referring to `this` before calling `super()` will throw an error.
Derived classes must not return before calling `super()`, unless the constructor returns an object (so the `this` value is overridden) or the class has no constructor at all.
```
class Base {}
class Good extends Base {}
class AlsoGood extends Base {
constructor() {
return { a: 5 };
}
}
class Bad extends Base {
constructor() {}
}
new Good();
new AlsoGood();
new Bad(); // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
```
### Global context
In the global execution context (outside of any functions or classes; may be inside [blocks](../statements/block) or [arrow functions](#arrow_functions) defined in the global scope), the `this` value depends on what execution context the script runs in. Like [callbacks](#callbacks), the `this` value is determined by the runtime environment (the caller).
At the top level of a script, `this` refers to [`globalThis`](../global_objects/globalthis) whether in strict mode or not. This is generally the same as the global object — for example, if the source is put inside an HTML [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element and executed as a script, `this === window`.
**Note:** `globalThis` is generally the same concept as the global object (i.e. adding properties to `globalThis` makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for `globalThis` that's unrelated to the global object.
```
// In web browsers, the window object is also the global object:
console.log(this === window); // true
this.b = "MDN";
console.log(window.b); // "MDN"
console.log(b); // "MDN"
```
If the source is loaded as a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) (for HTML, this means adding `type="module"` to the `<script>` tag), `this` is always `undefined` at the top level.
If the source is executed with [`eval()`](../global_objects/eval), `this` is the same as the enclosing context for [direct eval](../global_objects/eval#direct_and_indirect_eval), or `globalThis` (as if it's run in a separate global script) for indirect eval.
```
function test() {
// Direct eval
console.log(eval("this") === this);
// Indirect eval, non-strict
console.log(eval?.("this") === globalThis);
// Indirect eval, strict
console.log(eval?.("'use strict'; this") === globalThis);
}
test.call({ name: "obj" }); // Logs 3 "true"
```
Note that some source code, while looking like the global scope, is actually wrapped in a function when executed. For example, Node.js CommonJS modules are wrapped in a function and executed with the `this` value set to `module.exports`. [Event handler attributes](#this_in_inline_event_handlers) are executed with `this` set to the element they are attached to.
Object literals don't create a `this` scope — only functions (methods) defined within the object do. Using `this` in an object literal inherits the value from the surrounding scope.
```
const obj = {
a: this,
};
console.log(obj.a === window); // true
```
Examples
--------
### this in function contexts
The value of `this` depends on how the function is called, not how it's defined.
```
// An object can be passed as the first argument to call
// or apply and this will be bound to it.
const obj = { a: "Custom" };
// Variables declared with var become properties of the global object.
var a = "Global";
function whatsThis() {
return this.a; // The value of this is dependent on how the function is called
}
whatsThis(); // 'Global'; this in the function isn't set, so it defaults to the global/window object in non–strict mode
obj.whatsThis = whatsThis;
obj.whatsThis(); // 'Custom'; this in the function is set to obj
```
Using `call()` and `apply()`, you can pass the value of `this` as if it's an actual parameter.
```
function add(c, d) {
return this.a + this.b + c + d;
}
const o = { a: 1, b: 3 };
// The first parameter is the object to use as 'this'; subsequent
// parameters are used as arguments in the function call
add.call(o, 5, 7); // 16
// The first parameter is the object to use as 'this', the second is an
// array whose members are used as arguments in the function call
add.apply(o, [10, 20]); // 34
```
### this and object conversion
In non–strict mode, if a function is called with a `this` value that's not an object, the `this` value is substituted with an object. `null` and `undefined` become `globalThis`. Primitives like `7` or `'foo'` are converted to an object using the related constructor, so the primitive number `7` is converted to a [`Number`](../global_objects/number) wrapper class and the string `'foo'` to a [`String`](../global_objects/string) wrapper class.
```
function bar() {
console.log(Object.prototype.toString.call(this));
}
bar.call(7); // [object Number]
bar.call("foo"); // [object String]
bar.call(undefined); // [object Window]
```
### The bind() method
Calling [`f.bind(someObject)`](../global_objects/function/bind) creates a new function with the same body and scope as `f`, but the value of `this` is permanently bound to the first argument of `bind`, regardless of how the function is being called.
```
function f() {
return this.a;
}
const g = f.bind({ a: "azerty" });
console.log(g()); // azerty
const h = g.bind({ a: "yoo" }); // bind only works once!
console.log(h()); // azerty
const o = { a: 37, f, g, h };
console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty
```
### this in arrow functions
Arrow functions create closures over the `this` value of the enclosing execution context. In the following example, we create `obj` with a method `getThisGetter` that returns a function that returns the value of `this`. The returned function is created as an arrow function, so its `this` is permanently bound to the `this` of its enclosing function. The value of `this` inside `getThisGetter` can be set in the call, which in turn sets the return value of the returned function.
```
const obj = {
getThisGetter() {
const getter = () => this;
return getter;
},
};
```
We can call `getThisGetter` as a method of `obj`, which sets `this` inside the body to `obj`. The returned function is assigned to a variable `fn`. Now, when calling `fn`, the value of `this` returned is still the one set by the call to `getThisGetter`, which is `obj`. If the returned function is not an arrow function, such calls would cause the `this` value to be `globalThis` or `undefined` in strict mode.
```
const fn = obj.getThisGetter();
console.log(fn() === obj); // true
```
But be careful if you unbind the method of `obj` without calling it, because `getThisGetter` is still a method that has a varying `this` value. Calling `fn2()()` in the following example returns `globalThis`, because it follows the `this` from `fn2`, which is `globalThis` since it's called without being attached to any object.
```
const fn2 = obj.getThisGetter;
console.log(fn2()() === globalThis); // true
```
This behavior is very useful when defining callbacks. Usually, each function expression creates its own `this` binding, which shadows the `this` value of the upper scope. Now, you can define functions as arrow functions if you don't care about the `this` value, and only create `this` bindings where you do (e.g. in class methods). See [example with `setTimeout()`](../functions/arrow_functions#using_call_bind_and_apply).
### this with a getter or setter
`this` in getters and setters is based on which object the property is accessed on, not which object the property is defined on. A function used as getter or setter has its `this` bound to the object from which the property is being set or gotten.
```
function sum() {
return this.a + this.b + this.c;
}
const o = {
a: 1,
b: 2,
c: 3,
get average() {
return (this.a + this.b + this.c) / 3;
},
};
Object.defineProperty(o, "sum", {
get: sum,
enumerable: true,
configurable: true,
});
console.log(o.average, o.sum); // 2, 6
```
### As a DOM event handler
When a function is used as an event handler, its `this` is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)).
```
// When called as a listener, turns the related element blue
function bluify(e) {
// Always true
console.log(this === e.currentTarget);
// true when currentTarget and target are the same object
console.log(this === e.target);
this.style.backgroundColor = "#A5D9F3";
}
// Get a list of every element in the document
const elements = document.getElementsByTagName("\*");
// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for (const element of elements) {
element.addEventListener("click", bluify, false);
}
```
### this in inline event handlers
When the code is called from an inline [event handler attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#event_handler_attributes), its `this` is set to the DOM element on which the listener is placed:
```
<button onclick="alert(this.tagName.toLowerCase());">Show this</button>
```
The above alert shows `button`. Note, however, that only the outer code has its `this` set this way:
```
<button onclick="alert((function () { return this; })());">
Show inner this
</button>
```
In this case, the inner function's `this` isn't set, so it returns the global/window object (i.e. the default object in non–strict mode where `this` isn't set by the call).
### Bound methods in classes
Just like with regular functions, the value of `this` within methods depends on how they are called. Sometimes it is useful to override this behavior so that `this` within classes always refers to the class instance. To achieve this, bind the class methods in the constructor:
```
class Car {
constructor() {
// Bind sayBye but not sayHi to show the difference
this.sayBye = this.sayBye.bind(this);
}
sayHi() {
console.log(`Hello from ${this.name}`);
}
sayBye() {
console.log(`Bye from ${this.name}`);
}
get name() {
return "Ferrari";
}
}
class Bird {
get name() {
return "Tweety";
}
}
const car = new Car();
const bird = new Bird();
// The value of 'this' in methods depends on their caller
car.sayHi(); // Hello from Ferrari
bird.sayHi = car.sayHi;
bird.sayHi(); // Hello from Tweety
// For bound methods, 'this' doesn't depend on the caller
bird.sayBye = car.sayBye;
bird.sayBye(); // Bye from Ferrari
```
**Note:** Classes are always in strict mode. Calling methods with an undefined `this` will throw an error if the method tries to access properties on `this`.
Note, however, that auto-bound methods suffer from the same problem as [using arrow functions for class properties](../functions/arrow_functions#cannot_be_used_as_methods): each instance of the class will have its own copy of the method, which increases memory usage. Only use it where absolutely necessary. You can also mimic the implementation of [`Intl.NumberFormat.prototype.format()`](../global_objects/intl/datetimeformat/format#using_format_with_map): define the property as a getter that returns a bound function when accessed and saves it, so that the function is only created once and only created when necessary.
### this in with statements
Although [`with`](../statements/with) statements are deprecated and not available in strict mode, they still serve as an exception to the normal `this` binding rules. If a function is called within a `with` statement and that function is a property of the scope object, the `this` value is set to the scope object, as if the `obj1.` prefix exists.
```
const obj1 = {
foo() {
return this;
},
};
with (obj1) {
console.log(foo() === obj1); // true
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-this-keyword](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-this-keyword) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `this` | 1 | 12 | 1 | 4 | 9.5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Strict mode](../strict_mode)
* [Gentle explanation of 'this' keyword in JavaScript](https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/)
* Getting the global context: [`globalThis`](../global_objects/globalthis)
| programming_docs |
javascript Remainder (%) Remainder (%)
=============
The `%` operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Try it
------
Syntax
------
```
x % y
```
Description
-----------
For the operation `n % d`, `n` is called the dividend and `d` is called the divisor. The operation returns `NaN` if one of the operands is `NaN`, `n` is ±Infinity, or if `d` is ±0. Otherwise, if `d` is ±Infinity or if `n` is ±0, the dividend `n` is returned.
When both operands are non-zero and finite, the remainder `r` is calculated as `r := n - d * q` where `q` is the integer such that `r` has the same sign as the dividend `n` while being as close to 0 as possible.
Note that while in most languages, '%' is a remainder operator, in some (e.g. [Python, Perl](https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages)) it is a modulo operator. Modulo is defined as `k := n - d * q` where `q` is the integer such that `k` has the same sign as the divisor `d` while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the *divisor*, while the remainder has the same sign as the *dividend*, which can make them differ by one unit of `d`. To obtain a modulo in JavaScript, in place of `n % d`, use `((n % d) + d) % d`. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators ([`<<`](left_shift), [`>>`](right_shift), etc.), making the offset always a positive value.
Examples
--------
### Remainder with positive dividend
```
13 % 5 // 3
1 % -2 // 1
1 % 2 // 1
2 % 3 // 2
5.5 % 2 // 1.5
```
### Remainder with negative dividend
```
-13 % 5 // -3
-1 % 2 // -1
-4 % 2 // -0
```
### Remainder with NaN
```
NaN % 2 // NaN
```
### Remainder with Infinity
```
Infinity % 2 // NaN
Infinity % 0 // NaN
Infinity % Infinity // NaN
2 % Infinity // 2
0 % Infinity // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-multiplicative-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-multiplicative-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Remainder` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
* [Remainder operator vs. modulo operator](https://2ality.com/2019/08/remainder-vs-modulo.html)
javascript yield* yield\*
=======
The `yield*` operator is used to delegate to another [`generator`](../statements/function*) or iterable object.
Try it
------
Syntax
------
```
yield\* expression
```
`expression` The expression which returns an iterable object.
Description
-----------
The `yield*` expression iterates over the operand and `yield`s each value returned by it.
The value of `yield*` expression itself is the value returned by that iterator when it's closed (i.e., when `done` is `true`).
Examples
--------
### Delegating to another generator
In following code, values yielded by `g1()` are returned from `next()` calls just like those which are yielded by `g2()`.
```
function\* g1() {
yield 2;
yield 3;
yield 4;
}
function\* g2() {
yield 1;
yield\* g1();
yield 5;
}
const iterator = g2();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: 5, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
```
### Other Iterable objects
Besides generator objects, `yield*` can also `yield` other kinds of iterables (e.g., arrays, strings, or [`arguments`](../functions/arguments) objects).
```
function\* g3(...args) {
yield\* [1, 2];
yield\* "34";
yield\* args;
}
const iterator = g3(5, 6);
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: "3", done: false}
console.log(iterator.next()); // {value: "4", done: false}
console.log(iterator.next()); // {value: 5, done: false}
console.log(iterator.next()); // {value: 6, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
```
### The value of yield\* expression itself
`yield*` is an expression, not a statement—so it evaluates to a value.
```
function\* g4() {
yield\* [1, 2, 3];
return "foo";
}
function\* g5() {
const g4ReturnValue = yield\* g4();
console.log(g4ReturnValue); // 'foo'
return g4ReturnValue;
}
const iterator = g5();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false} done is false because g5 generator isn't finished, only g4
console.log(iterator.next()); // {value: 'foo', done: true}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator-function-definitions-runtime-semantics-evaluation](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-generator-function-definitions-runtime-semantics-evaluation) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `yield*` | 39 | 12 | 27
Starting with Firefox 33, the parsing of the `yield` expression has been updated to conform with the ES2015 specification. | No | 26 | 10 | 39 | 39 | 27
Starting with Firefox 33, the parsing of the `yield` expression has been updated to conform with the ES2015 specification. | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [The Iterator protocol](../iteration_protocols)
* [`function*`](../statements/function*)
* [`function*` expression](function*)
* [`yield`](yield)
javascript Unary plus (+) Unary plus (+)
==============
The `+` operator precedes its operand and evaluates to its operand but attempts to [convert it into a number](../global_objects/number#number_coercion), if it isn't already.
Try it
------
Syntax
------
```
+x
```
Description
-----------
Although unary negation (`-`) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values `true`, `false`, and `null`. Integers in both decimal and hexadecimal (`0x`-prefixed) formats are supported. Negative numbers are supported (though not for hex). Using the operator on BigInt values throws a TypeError. If it cannot parse a particular value, it will evaluate to [`NaN`](../global_objects/nan).
Examples
--------
### Usage with numbers
```
const x = 1;
const y = -1;
console.log(+x);
// 1
console.log(+y);
// -1
```
### Usage with non-numbers
```
+true // 1
+false // 0
+null // 0
+function (val) { return val; } // NaN
+1n // throws TypeError: Cannot convert BigInt value to number
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-unary-plus-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-unary-plus-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Unary_plus` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
javascript Bitwise OR assignment (|=) Bitwise OR assignment (|=)
==========================
The `|=` operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.
Try it
------
Syntax
------
```
x |= y // x = x | y
```
Examples
--------
### Using bitwise OR assignment
```
let a = 5;
a |= 2; // 7
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
// -----------------------------------
// 7: 00000000000000000000000000000111
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_OR_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Bitwise OR operator](bitwise_or)
* [Logical OR assignment (`||=`)](logical_or_assignment)
javascript Operator precedence Operator precedence
===================
**Operator precedence** determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.
Try it
------
Precedence And Associativity
----------------------------
Consider an expression describable by the representation below, where both `OP1` and `OP2` are fill-in-the-blanks for OPerators.
```
a OP1 b OP2 c
```
The combination above has two possible interpretations:
```
(a OP1 b) OP2 c
a OP1 (b OP2 c)
```
Which one the language decides to adopt depends on the identity of `OP1` and `OP2`.
If `OP1` and `OP2` have different precedence levels (see the table below), the operator with the higher *precedence* goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.
```
console.log(3 + 10 \* 2); // 23
console.log(3 + (10 \* 2)); // 23, because parentheses here are superfluous
console.log((3 + 10) \* 2); // 26, because the parentheses change the order
```
Within operators of the same precedence, the language groups them by *associativity*. *Left-associativity* (left-to-right) means that it is interpreted as `(a OP1 b) OP2 c`, while *right-associativity* (right-to-left) means it is interpreted as `a OP1 (b OP2 c)`. Assignment operators are right-associative, so you can write:
```
a = b = 5; // same as writing a = (b = 5);
```
with the expected result that `a` and `b` get the value 5. This is because the assignment operator returns the value that is assigned. First, `b` is set to 5. Then the `a` is also set to 5 — the return value of `b = 5`, a.k.a. right operand of the assignment.
As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.
```
const a = 4 \*\* 3 \*\* 2; // Same as 4 \*\* (3 \*\* 2); evaluates to 262144
const b = 4 / 3 / 2; // Same as (4 / 3) / 2; evaluates to 0.6666...
```
Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, `2 ** 3 / 3 ** 2` results in 0.8888888888888888 because it is the same as `(2 ** 3) / (3 ** 2)`.
For prefix unary operators, suppose we have the following pattern:
```
OP1 a OP2 b
```
where `OP1` is a prefix unary operator and `OP2` is a binary operator. If `OP1` has higher precedence than `OP2`, then it would be grouped as `(OP1 a) OP2 b`; otherwise, it would be `OP1 (a OP2 b)`.
```
const a = 1;
const b = 2;
typeof a + b; // Equivalent to (typeof a) + b; result is "number2"
```
If the unary operator is on the second operand:
```
a OP2 OP1 b
```
Then the binary operator `OP2` must have lower precedence than the unary operator `OP1` for it to be grouped as `a OP2 (OP1 b)`. For example, the following is invalid:
```
function\* foo() {
a + yield 1;
}
```
Because `+` has higher precedence than [`yield`](yield), this would become `(a + yield) 1` — but because `yield` is a [reserved word](../lexical_grammar#keywords) in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.
If we have two prefix unary operators:
```
OP1 OP2 a
```
Then the unary operator closer to the operand, `OP2`, must have higher precedence than `OP1` for it to be grouped as `OP1 (OP2 a)`. It's possible to get it the other way and end up with `(OP1 OP2) a`:
```
async function\* foo() {
await yield 1;
}
```
Because [`await`](await) has higher precedence than [`yield`](yield), this would become `(await yield) 1`, which is awaiting an identifier called `yield`, and a syntax error. Similarly, if you have `new !A;`, because `!` has lower precedence than `new`, this would become `(new !) A`, which is obviously invalid. (This code looks nonsensical to write anyway, since `!A` always produces a boolean, not a constructor function.)
For postfix unary operators (namely, `++` and `--`), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because `++` evaluates to a *value*, not a *reference*, you can't chain multiple increments together either, as you may do in C.
```
let a = 1;
a++++; // SyntaxError: Invalid left-hand side in postfix operation.
```
Operator precedence will be handled *recursively*. For example, consider this expression:
```
1 + 2 \*\* 3 \* 4 / 5 >> 6
```
First, we group operators with different precedence by decreasing levels of precedence.
1. The `**` operator has the highest precedence, so it's grouped first.
2. Looking around the `**` expression, it has `*` on the right and `+` on the left. `*` has higher precedence, so it's grouped first. `*` and `/` have the same precedence, so we group them together for now.
3. Looking around the `*`/`/` expression grouped in 2, because `+` has higher precedence than `>>`, the former is grouped.
```
(1 + ( (2 \*\* 3) \* 4 / 5) ) >> 6
// │ │ └─ 1. ─┘ │ │
// │ └────── 2. ───────┘ │
// └────────── 3. ──────────┘
```
Within the `*`/`/` group, because they are both left-associative, the left operand would be grouped.
```
(1 + ( ( (2 \*\* 3) \* 4 ) / 5) ) >> 6
// │ │ │ └─ 1. ─┘ │ │ │
// │ └─│─────── 2. ───│────┘ │
// └──────│───── 3. ─────│──────┘
// └───── 4. ─────┘
```
Note that operator precedence and associativity only affect the order of evaluation of *operators* (the implicit grouping), but not the order of evaluation of *operands*. The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.
```
function echo(name, num) {
console.log(`Evaluating the ${name} side`);
return num;
}
// Exponentiation operator (\*\*) is right-associative,
// but all call expressions (echo()), which have higher precedence,
// will be evaluated before \*\* does
console.log(echo("left", 4) \*\* echo("middle", 3) \*\* echo("right", 2));
// Evaluating the left side
// Evaluating the middle side
// Evaluating the right side
// 262144
// Exponentiation operator (\*\*) has higher precedence than division (/),
// but evaluation always starts with the left operand
console.log(echo("left", 4) / echo("middle", 3) \*\* echo("right", 2));
// Evaluating the left side
// Evaluating the middle side
// Evaluating the right side
// 0.4444444444444444
```
If you are familiar with binary trees, think about it as a [post-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN).
```
/
┌────────┴────────┐
echo("left", 4) **
┌────────┴────────┐
echo("middle", 3) echo("right", 2)
```
After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group — which is the operator with the lowest precedence (`/` in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression `echo("left", 4)`). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes — the `echo()` calls — would be visited left-to-right, regardless of the precedence of operators joining them.
Short-circuiting
----------------
In the previous section, we said "the higher-precedence expressions are always evaluated first" — this is generally true, but it has to be amended with the acknowledgement of *short-circuiting*, in which case an operand may not be evaluated at all.
Short-circuiting is jargon for conditional evaluation. For example, in the expression `a && (b + c)`, if `a` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), then the sub-expression `(b + c)` will not even get evaluated, even if it is grouped and therefore has higher precedence than `&&`. We could say that the logical AND operator (`&&`) is "short-circuited". Along with logical AND, other short-circuited operators include logical OR (`||`), nullish coalescing (`??`), and optional chaining (`?.`).
```
a || (b \* c); // evaluate `a` first, then produce `a` if `a` is "truthy"
a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy"
a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`
```
When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.
**Note:** The behavior of short-circuiting is baked in these operators. Other operators would *always* evaluate both operands, regardless if that's actually useful — for example, `NaN * foo()` will always call `foo`, even when the result would never be something other than `NaN`.
The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of `||` is already truthy), the result is directly returned without visiting the right subtree.
Consider this case:
```
function A() { console.log('called A'); return false; }
function B() { console.log('called B'); return false; }
function C() { console.log('called C'); return true; }
console.log(C() || B() && A());
// called C
// true
```
Only `C()` is evaluated, despite `&&` having higher precedence. This does not mean that `||` has higher precedence in this case — it's exactly *because* `(B() && A())` has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:
```
console.log(A() && C() || B());
// called A
// called B
// false
```
Then the short-circuiting effect of `&&` would only prevent `C()` from being evaluated, but because `A() && C()` as a whole is `false`, `B()` would still be evaluated.
However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of *operands*, not how *operators* are grouped — if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.
The assignment counterparts of these operators ([`&&=`](logical_and_assignment), [`||=`](logical_or_assignment), [`??=`](nullish_coalescing_assignment)) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.
Table
-----
The following table lists operators in order from highest precedence (18) to lowest precedence (1).
Several notes about the table:
1. Not all syntax included here are "operators" in the strict sense. For example, spread `...` and arrow `=>` are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
2. The left operand of an exponentiation `**` (precedence 13) cannot be one of the unary operators with precedence 14 without grouping, or there will be a [`SyntaxError`](../global_objects/syntaxerror). That means, although `-1 ** 2` is technically unambiguous, the language requires you to use `(-1) ** 2` instead.
3. The operands of nullish coalescing `??` (precedence 3) cannot be a logical OR `||` (precedence 3) or logical AND `&&` (precedence 4). That means you have to write `(a ?? b) || c` or `a ?? (b || c)`, instead of `a ?? b || c`.
4. Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access `.` (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow `=>` (precedence 2) must be an arguments list or a single identifier instead of some random expression.
5. Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation `[ … ]` (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is "automatically grouped". In this case we will omit the associativity.
| Precedence | Operator type | Associativity | Individual operators |
| --- | --- | --- | --- |
| 18 | [Grouping](grouping) | n/a | `( … )` |
| 17 | [Member Access](property_accessors#dot_notation) | left-to-right | `… . …` |
| [Optional chaining](optional_chaining) | `… ?. …` |
| [Computed Member Access](property_accessors#bracket_notation) | n/a | `… [ … ]` |
| [`new`](new) (with argument list) | `new … ( … )` |
| [Function Call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions) | `… ( … )` |
| 16 | [`new`](new) (without argument list) | n/a | `new …` |
| 15 | [Postfix Increment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement) | n/a | `… ++` |
| [Postfix Decrement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement) | `… --` |
| 14 | [Logical NOT (!)](logical_not) | n/a | `! …` |
| [Bitwise NOT (~)](bitwise_not) | `~ …` |
| [Unary plus (+)](unary_plus) | `+ …` |
| [Unary negation (-)](unary_negation) | `- …` |
| [Prefix Increment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement) | `++ …` |
| [Prefix Decrement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement) | `-- …` |
| [`typeof`](typeof) | `typeof …` |
| [`void`](void) | `void …` |
| [`delete`](delete) | `delete …` |
| [`await`](await) | `await …` |
| 13 | [Exponentiation (\*\*)](exponentiation) | right-to-left | `… ** …` |
| 12 | [Multiplication (\*)](multiplication) | left-to-right | `… * …` |
| [Division (/)](division) | `… / …` |
| [Remainder (%)](remainder) | `… % …` |
| 11 | [Addition (+)](addition) | left-to-right | `… + …` |
| [Subtraction (-)](subtraction) | `… - …` |
| 10 | [Bitwise Left Shift (<<)](left_shift) | left-to-right | `… << …` |
| [Bitwise Right Shift (>>)](right_shift) | `… >> …` |
| [Bitwise Unsigned Right Shift (>>>)](unsigned_right_shift) | `… >>> …` |
| 9 | [Less Than (<)](less_than) | left-to-right | `… < …` |
| [Less Than Or Equal (<=)](less_than_or_equal) | `… <= …` |
| [Greater Than (>)](greater_than) | `… > …` |
| [Greater Than Or Equal (>=)](greater_than_or_equal) | `… >= …` |
| [`in`](in) | `… in …` |
| [`instanceof`](instanceof) | `… instanceof …` |
| 8 | [Equality (==)](equality) | left-to-right | `… == …` |
| [Inequality (!=)](inequality) | `… != …` |
| [Strict Equality (===)](strict_equality) | `… === …` |
| [Strict Inequality (!==)](strict_inequality) | `… !== …` |
| 7 | [Bitwise AND (&)](bitwise_and) | left-to-right | `… & …` |
| 6 | [Bitwise XOR (^)](bitwise_xor) | left-to-right | `… ^ …` |
| 5 | [Bitwise OR (|)](bitwise_or) | left-to-right | `… | …` |
| 4 | [Logical AND (&&)](logical_and) | left-to-right | `… && …` |
| 3 | [Logical OR (||)](logical_or) | left-to-right | `… || …` |
| [Nullish coalescing operator (??)](nullish_coalescing) | `… ?? …` |
| 2 | [Assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators) | right-to-left | `… = …` |
| `… += …` |
| `… -= …` |
| `… **= …` |
| `… *= …` |
| `… /= …` |
| `… %= …` |
| `… <<= …` |
| `… >>= …` |
| `… >>>= …` |
| `… &= …` |
| `… ^= …` |
| `… |= …` |
| `… &&= …` |
| `… ||= …` |
| `… ??= …` |
| [Conditional (ternary) operator](conditional_operator) | right-to-left(Groups on expressions after `?`) | `… ? … : …` |
| [Arrow (=>)](../functions/arrow_functions) | right-to-left | `… => …` |
| [`yield`](yield) | n/a | `yield …` |
| [`yield*`](yield*) | `yield* …` |
| [Spread (...)](spread_syntax) | `... …` |
| 1 | [Comma / Sequence](comma_operator) | left-to-right | `… , …` |
| programming_docs |
javascript Addition assignment (+=) Addition assignment (+=)
========================
The `+=` operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.
Try it
------
Syntax
------
```
x += y // x = x + y
```
Examples
--------
### Using addition assignment
```
let baz = true;
// Boolean + Number -> addition
baz += 1; // 2
// Number + Boolean -> addition
baz += false; // 2
```
```
let foo = "foo";
// String + Boolean -> concatenation
foo += false; // "foofalse"
// String + String -> concatenation
foo += "bar"; // "foofalsebar"
```
```
let bar = 5;
// Number + Number -> addition
bar += 2; // 7
// Number + String -> concatenation
bar += "foo"; // "7foo"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Addition_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Addition operator](addition)
javascript Destructuring assignment Destructuring assignment
========================
The **destructuring assignment** syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Try it
------
Syntax
------
```
const [a, b] = array;
const [a, , b] = array;
const [a = aDefault, b] = array;
const [a, b, ...rest] = array;
const [a, , b, ...rest] = array;
const [a, b, ...{ pop, push }] = array;
const [a, b, ...[c, d]] = array;
const { a, b } = obj;
const { a: a1, b: b1 } = obj;
const { a: a1 = aDefault, b = bDefault } = obj;
const { a, b, ...rest } = obj;
const { a: a1, b: b1, ...rest } = obj;
const { [key]: a } = obj;
let a, b, a1, b1, c, d, rest, pop, push;
[a, b] = array;
[a, , b] = array;
[a = aDefault, b] = array;
[a, b, ...rest] = array;
[a, , b, ...rest] = array;
[a, b, ...{ pop, push }] = array;
[a, b, ...[c, d]] = array;
({ a, b } = obj); // brackets are required
({ a: a1, b: b1 } = obj);
({ a: a1 = aDefault, b = bDefault } = obj);
({ a, b, ...rest } = obj);
({ a: a1, b: b1, ...rest } = obj);
```
Description
-----------
The object and array literal expressions provide an easy way to create *ad hoc* packages of data.
```
const x = [1, 2, 3, 4, 5];
```
The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.
```
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2
```
Similarly, you can destructure objects on the left-hand side of the assignment.
```
const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;
```
This capability is similar to features present in languages such as Perl and Python.
### Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: *binding pattern* and *assignment pattern*, with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword (`var`, `let`, or `const`). Then, each individual property must either be bound to a variable or further destructured.
```
const obj = { a: 1, b: { c: 2 } };
const { a, b: { c: d } } = obj;
// Two variables are bound: `a` and `d`
```
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with `let`, once with `const`.
```
const obj = { a: 1, b: { c: 2 } };
const { a } = obj; // a is constant
let { b: { c: d } } = obj; // d is re-assignable
```
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with `var` or `let`, or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.
```
const numbers = [];
const obj = { a: 1, b: 2 };
({ a: numbers[0], b: numbers[1] } = obj);
// The properties `a` and `b` are assigned to properties of `numbers`
```
**Note:** The parentheses `( ... )` around the assignment statement are required when using object literal destructuring assignment without a declaration.
`{ a, b } = { a: 1, b: 2 }` is not valid stand-alone syntax, as the `{a, b}` on the left-hand side is considered a block and not an object literal. However, `({ a, b } = { a: 1, b: 2 })` is valid, as is `const { a, b } = { a: 1, b: 2 }`.
If your coding style does not include trailing semicolons, the `( ... )` expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent *binding pattern* of the code above is not valid syntax:
```
const numbers = [];
const obj = { a: 1, b: 2 };
const { a: numbers[0], b: numbers[1] } = obj;
// This is equivalent to:
// const numbers[0] = obj.a;
// const numbers[1] = obj.b;
// Which definitely is not valid.
```
### Default value
Each destructured property can have a *default value*. The default value is used when the property is not present, or has value `undefined`. It is not used if the property has value `null`.
```
const [a = 1] = []; // a is 1
const { b = 2 } = { b: undefined }; // b is 2
const { c = 2 } = { c: null }; // c is null
```
The default value can be any expression. It will only be evaluated when necessary.
```
const { b = console.log("hey") } = { b: 2 };
// Does not log anything, because `b` is defined and there's no need
// to evaluate the default value.
```
### Rest property
You can end a destructuring pattern with a rest property `...rest`. This pattern will store all remaining properties of the object or array into a new object or array.
```
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }
const [first, ...others2] = [1, 2, 3];
console.log(others2); // [2, 3]
```
The rest property must be the last in the pattern, and must not have a trailing comma.
```
const [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
// Always consider using rest operator as the last element
```
### Destructuring patterns with other syntaxes
In many syntaxes where the language binds a variable for you, you can use a destructuring pattern as well. These include:
* The looping variable of [`for...in`](../statements/for...in) and [`for...of`](../statements/for...of) loops;
* [Function](../functions) parameters;
* The [`catch`](../statements/try...catch) binding variable.
For features specific to array or object destructuring, please refer to the individual examples below.
Examples
--------
### Array destructuring
#### Basic variable assignment
```
const foo = ['one', 'two', 'three'];
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
```
#### Destructuring with more elements than the source
In an array destructuring from an array of length *N* specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than *N*, only the first *N* variables are assigned values. The values of the remaining variables will be undefined.
```
const foo = ['one', 'two'];
const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue); //undefined
```
#### Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the [XOR-swap trick](https://en.wikipedia.org/wiki/XOR_swap_algorithm)).
```
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
const arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr); // [1, 3, 2]
```
#### Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, `f()` returns the values `[1, 2]` as its output, which can be parsed in a single line with destructuring.
```
function f() {
return [1, 2];
}
const [a, b] = f();
console.log(a); // 1
console.log(b); // 2
```
#### Ignoring some returned values
You can ignore return values that you're not interested in:
```
function f() {
return [1, 2, 3];
}
const [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
const [c] = f();
console.log(c); // 1
```
You can also ignore all returned values:
```
[,,] = f();
```
#### Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. This allows you to simultaneously unpack the properties and indices of arrays.
```
const [a, b, ...{ pop, push }] = [1, 2];
console.log(a, b); // 1 2
console.log(pop, push); // [Function pop] [Function push]
```
```
const [a, b, ...[c, d]] = [1, 2, 3, 4];
console.log(a, b, c, d); // 1 2 3 4
```
These binding patterns can even be nested, as long as each rest property is the last in the list.
```
const [a, b, ...[c, d, ...[e, f]]] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c, d, e, f); // 1 2 3 4 5 6
```
On the other hand, object destructuring can only have an identifier as the rest property.
```
const { a, ...{ b } } = { a: 1, b: 2 };
// SyntaxError: `...` must be followed by an identifier in declaration contexts
let a, b;
({ a, ...{ b } } = { a: 1, b: 2 });
// SyntaxError: `...` must be followed by an assignable reference in assignment contexts
```
#### Unpacking values from a regular expression match
When the regular expression [`exec()`](../global_objects/regexp/exec) method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
```
function parseProtocol(url) {
const parsedURL = /^(\w+):\/\/([^/]+)\/(.\*)$/.exec(url);
if (!parsedURL) {
return false;
}
console.log(parsedURL);
// ["https://developer.mozilla.org/en-US/docs/Web/JavaScript",
// "https", "developer.mozilla.org", "en-US/docs/Web/JavaScript"]
const [, protocol, fullhost, fullpath] = parsedURL;
return protocol;
}
console.log(parseProtocol('https://developer.mozilla.org/en-US/docs/Web/JavaScript'));
// "https"
```
#### Using array destructuring on any iterable
Array destructuring calls the [iterable protocol](../iteration_protocols) of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
```
const [a, b] = new Map([[1, 2], [3, 4]]);
console.log(a, b); // [1, 2] [3, 4]
```
Non-iterables cannot be destructured as arrays.
```
const obj = { 0: "a", 1: "b", length: 2 };
const [a, b] = obj;
// TypeError: obj is not iterable
```
Iterables are only iterated until all bindings are assigned.
```
const obj = {
\*[Symbol.iterator]() {
for (const v of [0, 1, 2, 3]) {
console.log(v);
yield v;
}
}
}
const [a, b] = obj; // Only logs 0 and 1
```
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
```
const obj = {
\*[Symbol.iterator]() {
for (const v of [0, 1, 2, 3]) {
console.log(v);
yield v;
}
}
}
const [a, b, ...rest] = obj; // Logs 0 1 2 3
console.log(rest); // [2, 3] (an array)
```
### Object destructuring
#### Basic assignment
```
const user = {
id: 42,
isVerified: true,
};
const { id, isVerified } = user;
console.log(id); // 42
console.log(isVerified); // true
```
#### Assigning to new variable names
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
```
const o = { p: 42, q: true };
const { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true
```
Here, for example, `const { p: foo } = o` takes from the object `o` the property named `p` and assigns it to a local variable named `foo`.
#### Assigning to new variable names and providing default values
A property can be both
* Unpacked from an object and assigned to a variable with a different name.
* Assigned a default value in case the unpacked value is `undefined`.
```
const { a: aa = 10, b: bb = 5 } = { a: 3 };
console.log(aa); // 3
console.log(bb); // 5
```
#### Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
```
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'Jane',
lastName: 'Doe',
},
};
```
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value `{ id }` indicates that the `id` property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
```
function userId({ id }) {
return id;
}
console.log(userId(user)); // 42
```
You can define the name of the unpacked variable. Here we unpack the property named `displayName`, and rename it to `dname` for use within the function body.
```
function userDisplayName({ displayName: dname }) {
return dname;
}
console.log(userDisplayName(user)); // `jdoe`
```
Nested objects can also be unpacked. The example below shows the property `fullname.firstName` being unpacked into a variable called `name`.
```
function whois({ displayName, fullName: { firstName: name } }) {
return `${displayName} is ${name}`;
}
console.log(whois(user)); // "jdoe is Jane"
```
#### Setting a function parameter's default value
Default values can be specified using `=`, and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is `'big'`, default co-ordinates are `x: 0, y: 0` and default radius is 25.
```
function drawChart({ size = 'big', coords = { x: 0, y: 0 }, radius = 25 } = {}) {
console.log(size, coords, radius);
// do some chart drawing
}
drawChart({
coords: { x: 18, y: 30 },
radius: 30,
});
```
In the function signature for `drawChart` above, the destructured left-hand side has a default value of an empty object `= {}`.
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call `drawChart()` without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see [Default parameters > Destructured parameter with default value assignment](../functions/default_parameters#destructured_parameter_with_default_value_assignment).
#### Nested object and array destructuring
```
const metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localizationTags: [],
lastEdit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung',
},
],
url: '/en-US/docs/Tools/Scratchpad',
};
const {
title: englishTitle, // rename
translations: [
{
title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
```
#### For of iteration and destructuring
```
const people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith',
},
age: 35,
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones',
},
age: 25,
}
];
for (const { name: n, family: { father: f } } of people) {
console.log(`Name: ${n}, Father: ${f}`);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
```
#### Computed object property names and destructuring
Computed property names, like on [object literals](object_initializer#computed_property_names), can be used with destructuring.
```
const key = 'z';
const { [key]: foo } = { z: 'bar' };
console.log(foo); // "bar"
```
#### Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript [identifiers](https://developer.mozilla.org/en-US/docs/Glossary/Identifier) by providing an alternative identifier that is valid.
```
const foo = { 'fizz-buzz': true };
const { 'fizz-buzz': fizzBuzz } = foo;
console.log(fizzBuzz); // true
```
### Destructuring primitive values
Object destructuring is almost equivalent to [property accessing](property_accessors). This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
```
const { a, toFixed } = 1;
console.log(a, toFixed); // undefined ƒ toFixed() { [native code] }
```
Same as accessing properties, destructuring `null` or `undefined` throws a [`TypeError`](../global_objects/typeerror).
```
const { a } = undefined; // TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.
const { a } = null; // TypeError: Cannot destructure property 'b' of 'null' as it is null.
```
This happens even when the pattern is empty.
```
const {} = null; // TypeError: Cannot destructure 'null' as it is null.
```
#### Combined Array and Object Destructuring
Array and Object destructuring can be combined. Say you want the third element in the array `props` below, and then you want the `name` property in the object, you can do the following:
```
const props = [
{ id: 1, name: 'Fizz'},
{ id: 2, name: 'Buzz'},
{ id: 3, name: 'FizzBuzz'}
];
const [,, { name }] = props;
console.log(name); // "FizzBuzz"
```
#### The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
```
const obj = {
self: '123',
\_\_proto\_\_: {
prot: '456',
},
};
const { self, prot } = obj;
// self "123"
// prot "456" (Access to the prototype chain)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-destructuring-assignment](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-destructuring-assignment) |
| [ECMAScript Language Specification # sec-destructuring-binding-patterns](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-destructuring-binding-patterns) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Destructuring_assignment` | 49 | 14 | 41
Firefox provided a non-standard destructuring implementation from Firefox 2 to 40. | No | 36 | 8 | 49 | 49 | 41
Firefox provided a non-standard destructuring implementation from Firefox 2 to 40. | 36 | 8 | 5.0 | 1.0 | 6.0.0 |
| `computed_property_names` | 49 | 14 | 41 | No | 36 | 10 | 49 | 49 | 41 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `rest_in_arrays` | 49 | 16 | 41 | No | 36 | 9.1 | 49 | 49 | 41 | 36 | 9.3 | 5.0 | 1.0 | 6.0.0 |
| `rest_in_objects` | 60 | 79 | 55 | No | 47 | 11.1 | 60 | 60 | 55 | 44 | 11.3 | 8.0 | 1.0 | 8.3.0 |
See also
--------
* [Assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators)
* ["ES6 in Depth: Destructuring" on hacks.mozilla.org](https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/)
| programming_docs |
javascript void operator void operator
=============
The `void` operator evaluates the given `expression` and then returns [`undefined`](../global_objects/undefined).
Try it
------
Syntax
------
```
void expression
```
Description
-----------
This operator allows evaluating expressions that produce a value into places where an expression that evaluates to [`undefined`](../global_objects/undefined) is desired.
The `void` operator is often used merely to obtain the `undefined` primitive value, usually using `void(0)` (which is equivalent to `void 0`). In these cases, the global variable [`undefined`](../global_objects/undefined) can be used.
It should be noted that [the precedence](operator_precedence) of the `void` operator should be taken into account and that parentheses can help clarify the resolution of the expression following the `void` operator:
```
void 2 === "2"; // (void 2) === '2', returns false
void (2 === "2"); // void (2 === '2'), returns undefined
```
Examples
--------
### Immediately Invoked Function Expressions
When using an [immediately-invoked function expression](https://developer.mozilla.org/en-US/docs/Glossary/IIFE), the `function` keyword cannot be at the immediate start of the [statement](../statements/expression_statement), because that would be parsed as a [function declaration](../statements/function), and would generate a syntax error when the parentheses representing invocation is reached — if the function is unnamed, it would immediately be a syntax error if the function is parsed as a declaration.
```
function iife() {
console.log("Executed!");
}(); // SyntaxError: Unexpected token ')'
function () {
console.log("Executed!");
}(); // SyntaxError: Function statements require a function name
```
In order for the function to be parsed as an [expression](function), the `function` keyword has to appear at a position that only accepts expressions, not statements. This can be achieved be prefixing the keyword with a [unary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#unary_operators), which only accepts expressions as operands. Function invocation has higher [precedence](operator_precedence) than unary operators, so it will be executed first. Its return value (which is almost always `undefined`) will be passed to the unary operator and then immediately discarded.
Of all the unary operators, `void` offers the best semantic, because it clearly signals that the return value of the function invocation should be discarded.
```
void function () {
console.log("Executed!");
}();
// Logs "Executed!"
```
This is a bit longer than wrapping the function expression in parentheses, which has the same effect of forcing the `function` keyword to be parsed as the start of an expression instead of a statement.
```
(function () {
console.log("Executed!");
})();
```
### JavaScript URIs
When a browser follows a `javascript:` URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is [`undefined`](../global_objects/undefined). The `void` operator can be used to return `undefined`. For example:
```
<a href="javascript:void(0);">
Click here to do nothing
</a>
<a href="javascript:void(document.body.style.backgroundColor='green');">
Click here for green background
</a>
```
**Note:** `javascript:` pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.
### Non-leaking Arrow Functions
Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.
```
button.onclick = () => void doSomething();
```
This ensures the return value of `doSomething` changing from `undefined` to `true` will not change the behavior of this code.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-void-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-void-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `void` | 1 | 12 | 1 | 5 | 4 | 3.1 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`undefined`](../global_objects/undefined)
javascript Bitwise AND (&) Bitwise AND (&)
===============
The `&` operator returns a `1` in each bit position for which the corresponding bits of both operands are `1`s.
Try it
------
Syntax
------
```
a & b
```
Description
-----------
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes 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:
```
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
Each bit in the first operand is paired with the corresponding bit in the second operand: *first bit* to *first bit*, *second bit* to *second bit*, and so on.
The operator is applied to each pair of bits, and the result is constructed bitwise.
The truth table for the AND operation is:
| a | b | a AND b |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
```
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
```
Bitwise ANDing any number `x` with `0` yields `0`.
Examples
--------
### Using bitwise AND
```
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
5 & 2; // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-BitwiseANDExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-BitwiseANDExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_AND` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Bitwise AND assignment operator](bitwise_and_assignment)
javascript null null
====
The `null` value represents the intentional absence of any object value. It is one of JavaScript's [primitive values](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) and is treated as [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) for boolean operations.
Try it
------
Syntax
------
```
null
```
Description
-----------
The value `null` is written with a literal: `null`. `null` is not an identifier for a property of the global object, like [`undefined`](../global_objects/undefined) can be. Instead, `null` expresses a lack of identification, indicating that a variable points to no object. In APIs, `null` is often retrieved in a place where an object can be expected but no object is relevant.
```
// foo does not exist. It is not defined and has never been initialized:
foo; //ReferenceError: foo is not defined
```
```
// foo is known to exist now but it has no type or value:
const foo = null;
foo; //null
```
Examples
--------
### Difference between `null` and `undefined`
When checking for `null` or `undefined`, beware of the [differences between equality (==) and identity (===) operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators), as the former performs type-conversion.
```
typeof null // "object" (not "null" for legacy reasons)
typeof undefined // "undefined"
null === undefined // false
null == undefined // true
null === null // true
null == null // true
!null // true
isNaN(1 + null) // false
isNaN(1 + undefined) // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-null-value](https://tc39.es/ecma262/multipage/overview.html#sec-null-value) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `null` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`undefined`](../global_objects/undefined)
* [`NaN`](../global_objects/nan)
* [`void`](void)
javascript Exponentiation assignment (**=) Exponentiation assignment (\*\*=)
=================================
The `**=` operator raises the value of a variable to the power of the right operand.
Try it
------
Syntax
------
```
x \*\*= y // x = x \*\* y
```
Examples
--------
### Using exponentiation assignment
```
let bar = 5;
bar \*\*= 2; // 25
bar \*\*= "foo"; // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Exponentiation_assignment` | 52 | 14 | 52 | No | 39 | 10.1 | 51 | 52 | 52 | 41 | 10.3 | 6.0 | 1.0 | 7.0.0
6.5.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Exponentiation operator](exponentiation)
javascript Bitwise AND assignment (&=) Bitwise AND assignment (&=)
===========================
The `&=` operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable.
Try it
------
Syntax
------
```
x &= y // x = x & y
```
Examples
--------
### Using bitwise AND assignment
```
let a = 5;
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
a &= 2; // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_AND_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Bitwise AND operator](bitwise_and)
javascript Left shift assignment (<<=) Left shift assignment (<<=)
===========================
The `<<=` operator moves the specified amount of bits to the left and assigns the result to the variable.
Try it
------
Syntax
------
```
x <<= y // x = x << y
```
Examples
--------
### Using left shift assignment
```
let a = 5;
// 00000000000000000000000000000101
a <<= 2; // 20
// 00000000000000000000000000010100
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Left_shift_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Left shift operator](left_shift)
javascript Bitwise XOR (^) Bitwise XOR (^)
===============
The `^` operator returns a `1` in each bit position for which the corresponding bits of either but not both operands are `1`s.
Try it
------
Syntax
------
```
a ^ b
```
Description
-----------
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes 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:
```
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
Each bit in the first operand is paired with the corresponding bit in the second operand: *first bit* to *first bit*, *second bit* to *second bit*, and so on.
The operator is applied to each pair of bits, and the result is constructed bitwise.
The truth table for the XOR operation is:
| a | b | a XOR b |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
```
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
```
Bitwise XORing any number `x` with `0` yields `x`.
Examples
--------
### Using bitwise XOR
```
// 9 (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)
14 ^ 9;
// 7 (00000000000000000000000000000111)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-BitwiseXORExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-BitwiseXORExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_XOR` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Bitwise XOR assignment operator](bitwise_xor_assignment)
javascript Strict equality (===) Strict equality (===)
=====================
The `===` operator checks whether its two operands are equal, returning a Boolean result. Unlike the <equality> operator, the strict equality operator always considers operands of different types to be different.
Try it
------
Syntax
------
```
x === y
```
Description
-----------
The strict equality operators (`===` and `!==`) provide the [IsStrictlyEqual](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using) semantic.
* If the operands are of different types, return `false`.
* If both operands are objects, return `true` only if they refer to the same object.
* If both operands are `null` or both operands are `undefined`, return `true`.
* If either operand is `NaN`, return `false`.
* Otherwise, compare the two operand's values:
+ Numbers must have the same numeric values. `+0` and `-0` are considered to be the same value.
+ Strings must have the same characters in the same order.
+ Booleans must be both `true` or both `false`.
The most notable difference between this operator and the <equality> (`==`) operator is that if the operands are of different types, the `==` operator attempts to convert them to the same type before comparing.
Examples
--------
### Comparing operands of the same type
```
"hello" === "hello"; // true
"hello" === "hola"; // false
3 === 3; // true
3 === 4; // false
true === true; // true
true === false; // false
null === null; // true
```
### Comparing operands of different types
```
"3" === 3; // false
true === 1; // false
null === undefined; // false
```
### Comparing objects
```
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 === object2); // false
console.log(object1 === object1); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-equality-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-equality-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Strict_equality` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Equality operator](equality)
* [Inequality operator](inequality)
* [Strict inequality operator](strict_inequality)
javascript typeof typeof
======
The `typeof` operator returns a string indicating the type of the operand's value.
Try it
------
Syntax
------
```
typeof operand
```
### Parameters
`operand` An expression representing the object or [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) whose type is to be returned.
Description
-----------
The following table summarizes the possible return values of `typeof`. For more information about types and primitives, see also the [JavaScript data structure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) page.
| Type | Result |
| --- | --- |
| [Undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined) | `"undefined"` |
| [Null](https://developer.mozilla.org/en-US/docs/Glossary/Null) | `"object"` ([reason](#typeof_null)) |
| [Boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean) | `"boolean"` |
| [Number](https://developer.mozilla.org/en-US/docs/Glossary/Number) | `"number"` |
| [BigInt](https://developer.mozilla.org/en-US/docs/Glossary/BigInt) | `"bigint"` |
| [String](https://developer.mozilla.org/en-US/docs/Glossary/String) | `"string"` |
| [Symbol](../global_objects/symbol) | `"symbol"` |
| [Function](https://developer.mozilla.org/en-US/docs/Glossary/Function) (implements [[Call]] in ECMA-262 terms; [classes](../statements/class) are functions as well) | `"function"` |
| Any other object | `"object"` |
This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed. The old Internet Explorer was the only browser known to [implement additional return values](https://github.com/tc39/ecma262/issues/1440#issuecomment-461963872), before the spec removed the behavior of `typeof` returning implementation-defined strings for non-callable non-standard exotic objects.
Examples
--------
### Basic usage
```
// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number
typeof 42n === "bigint";
// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString
// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";
// Objects
typeof { a: 1 } === "object";
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";
typeof new Date() === "object";
typeof /regex/ === "object";
// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";
// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";
```
### typeof null
```
// This stands since the beginning of JavaScript
typeof null === "object";
```
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was `0`. `null` was represented as the NULL pointer (`0x00` in most platforms). Consequently, `null` had `0` as type tag, hence the `typeof` return value `"object"`. ([reference](https://2ality.com/2013/10/typeof-null.html))
A fix was proposed for ECMAScript (via an opt-in), but [was rejected](https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null). It would have resulted in `typeof null === "null"`.
### Using new operator
All constructor functions called with [`new`](new) will return non-primitives (`"object"` or `"function"`). Most return objects, with the notable exception being [`Function`](../global_objects/function), which returns a function.
```
const str = new String("String");
const num = new Number(100);
typeof str; // "object"
typeof num; // "object"
const func = new Function();
typeof func; // "function"
```
### Need for parentheses in syntax
The `typeof` operator has higher [precedence](operator_precedence) than binary operators like addition (`+`). Therefore, parentheses are needed to evaluate the type of an addition result.
```
// Parentheses can be used for determining the data type of expressions.
const someData = 99;
typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"
```
### Interaction with undeclared and uninitialized variables
`typeof` is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, `typeof` will return `"undefined"` instead of throwing an error.
```
typeof undeclaredVariable; // "undefined"
```
However, using `typeof` on lexical declarations ([`let`](../statements/let) [`const`](../statements/const), and [`class`](../statements/class)) in the same block before the line of declaration will throw a [`ReferenceError`](../global_objects/referenceerror). Block scoped variables are in a *[temporal dead zone](../statements/let#temporal_dead_zone_tdz)* from the start of the block until the initialization is processed, during which it will throw an error if accessed.
```
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = "hello";
class newClass {}
```
### Exceptional behavior of document.all
All current browsers expose a non-standard host object [`document.all`](https://developer.mozilla.org/en-US/docs/Web/API/Document/all) with type `undefined`.
```
typeof document.all === "undefined";
```
Although `document.all` is also [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) and [loosely equal](equality) to `undefined`, it is not [`undefined`](../global_objects/undefined). The case of `document.all` having type `"undefined"` is classified in the web standards as a "willful violation" of the original ECMAScript standard for web compatibility.
### Custom method that gets a more specific type
`typeof` is very useful, but it's not as versatile as might be required. For example, `typeof []` is `"object"`, as well as `typeof new Date()`, `typeof /abc/`, etc.
For greater specificity in checking types, here we present a custom `type(value)` function, which mostly mimics the behavior of `typeof`, but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.
```
function type(value) {
if (value === null) {
return "null";
}
const baseType = typeof value;
// Primitive types
if (!["object", "function"].includes(baseType)) {
return baseType;
}
// Symbol.toStringTag often specifies the "display name" of the
// object's class. It's used in Object.prototype.toString().
const tag = value[Symbol.toStringTag];
if (typeof tag === "string") {
return tag;
}
// If it's a function whose source code starts with the "class" keyword
if (
baseType === "function" &&
Function.prototype.toString.call(value).startsWith("class")
) {
return "class";
}
// The name of the constructor; for example `Array`, `GeneratorFunction`,
// `Number`, `String`, `Boolean` or `MyCustomClass`
const className = value.constructor.name;
if (typeof className === "string" && className !== "") {
return className;
}
// At this point there's no robust way to get the type of value,
// so we use the base implementation.
return baseType;
}
```
For checking potentially non-existent variables that would otherwise throw a [`ReferenceError`](../global_objects/referenceerror), use `typeof nonExistentVar === "undefined"` because this behavior cannot be mimicked with custom code.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typeof-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-typeof-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `typeof` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`instanceof`](instanceof)
* [`document.all` willful violation of the standard](https://github.com/tc39/ecma262/issues/668)
| programming_docs |
javascript in operator in operator
===========
The `in` operator returns `true` if the specified property is in the specified object or its prototype chain.
Try it
------
Syntax
------
```
prop in object
#prop in object
```
### Parameters
`prop` A string or symbol representing a property name (non-symbols will be [coerced to strings](../global_objects/string#string_coercion)). Can also be a [private property identifier](../classes/private_class_fields).
`object` Object to check if it (or its prototype chain) contains the property with specified name (`prop`).
### Exceptions
[`TypeError`](../global_objects/typeerror) Thrown if `object` is not an object (i.e. a primitive).
Description
-----------
The `in` operator tests if a string or symbol property is present in an object or its prototype chain. If you want to check for only *non-inherited* properties, use [`Object.hasOwn()`](../global_objects/object/hasown) instead.
A property may be present in an object but have value `undefined`. Therefore, `x in obj` is not the same as `obj.x === undefined`. To make `in` return `false` after a property is added, use the [`delete`](delete) operator instead of setting that property's value to `undefined`.
You can also use the `in` operator to check whether a particular [private class field or method](../classes/private_class_fields) has been defined in an object. The operator returns `true` if the property is defined, and `false` otherwise. This is known as a *branded check*, because it returns `true` if and only if the object was created with that class constructor, after which you can safely access other private properties as well.
This is a special syntax — the left-hand side of the `in` operator is a property identifier instead of an expression, but unquoted (because otherwise it's a string property, not a private property).
Because accessing private properties on objects unrelated to the current class throws a [`TypeError`](../global_objects/typeerror) instead of returning `undefined`, this syntax allows you to shorten:
```
class C {
#x;
static isC(obj) {
try {
obj.#x;
return true;
} catch {
return false;
}
}
}
```
To:
```
class C {
#x;
static isC(obj) {
return #x in obj;
}
}
```
It also generally avoids the need for dealing with error handling just to access a private property that may be nonexistent.
However, the `in` operator still requires the private property to be declared beforehand in the enclosing class — otherwise, it would throw a [`SyntaxError`](../global_objects/syntaxerror) ("Private field '#x' must be declared in an enclosing class"), the same one as when you try to access an undeclared private property.
```
class C {
foo() {
#x in this;
}
}
new C().foo(); // SyntaxError: Private field '#x' must be declared in an enclosing class
```
Examples
--------
### Basic usage
The following examples show some uses of the `in` operator.
```
// 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)
Symbol.iterator in trees; // returns true
// Predefined objects
"PI" in Math; // returns true
// Custom objects
const mycar = { make: "Honda", model: "Accord", year: 1998 };
"make" in mycar; // returns true
"model" in mycar; // returns true
```
You must specify an object on the right side of the `in` operator. For example, you can specify a string created with the `String` constructor, but you cannot specify a string literal.
```
const color1 = new String("green");
"length" in color1; // returns true
const color2 = "coral";
// generates an error (color2 is not a String object)
"length" in color2;
```
### Using the in operator with deleted or undefined properties
If you delete a property with the [`delete`](delete) operator, the `in` operator returns `false` for that property.
```
const mycar = { make: "Honda", model: "Accord", year: 1998 };
delete mycar.make;
"make" in mycar; // returns false
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
3 in trees; // returns false
```
If you set a property to [`undefined`](../global_objects/undefined) but do not delete it, the `in` operator returns true for that property.
```
const mycar = { make: "Honda", model: "Accord", year: 1998 };
mycar.make = undefined;
"make" in mycar; // returns true
```
```
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees[3] = undefined;
3 in trees; // returns true
```
The `in` operator will return `false` for [empty array slots](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), even if accessing it directly returns `undefined`.
```
const empties = new Array(3);
empties[2]; // returns undefined
2 in empties; // returns false
```
To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array.
```
const empties = new Array(3).fill(undefined);
2 in empties; // returns true
```
### Inherited properties
The `in` operator returns `true` for properties in the prototype chain. This may be undesirable if you are using objects to store arbitrary key-value pairs.
```
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return name in ages;
}
hasPerson("hasOwnProperty"); // true
```
You can use [`Object.hasOwn()`](../global_objects/object/hasown) to check if the object has the key.
```
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return Object.hasOwn(ages, name);
}
hasPerson("hasOwnProperty"); // false
```
Alternatively, you should consider using a [null prototype object](../global_objects/object#null-prototype_objects) or a [`Map`](../global_objects/map) for storing `ages`, to avoid other bugs.
```
const ages = new Map([
["alice", 18],
["bob", 27],
]);
function hasPerson(name) {
return ages.has(name);
}
hasPerson("hasOwnProperty"); // false
```
### Using the in operator to implement branded checks
The code fragment below demonstrates a static function that tells if an object was created with the `Person` constructor and therefore can perform other methods safely.
```
class Person {
#age;
constructor(age) {
this.#age = age;
}
static isPerson(o) {
return #age in o;
}
ageDifference(other) {
return this.#age - other.#age;
}
}
const p1 = new Person(20);
const p2 = new Person(30);
console.log(p1.ageDifference(p2)); // -10
console.log(Person.isPerson(p1)); // true
if (Person.isPerson(p1) && Person.isPerson(p2)) {
console.log(p1.ageDifference(p2)); // -10
}
```
It helps to prevent the following case:
```
const p2 = {};
p1.ageDifference(p2); // TypeError: Cannot read private member #age from an object whose class did not declare it
```
Without the `in` operator, you would have to use a `try...catch` block to check if the object has the private property.
You can also implement this as a [`@@hasInstance`](../global_objects/symbol/hasinstance) method of the class, so that you can use the [`instanceof`](instanceof) operator to perform the same check (which, by default, only checks for the existence of `Person.prototype` in the object's prototype chain).
```
class Person {
#age;
constructor(age) {
this.#age = age;
}
static [Symbol.hasInstance](o) {
// Testing `this` to prevent false-positives when
// calling `instanceof SubclassOfPerson`
return this === Person && #age in o;
}
ageDifference(other) {
return this.#age - other.#age;
}
}
const p1 = new Person(20);
const p2 = new Person(30);
if (p1 instanceof Person && p2 instanceof Person) {
console.log(p1.ageDifference(p2)); // -10
}
```
For more examples, see [Private class features](../classes/private_class_fields) and the [class guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_Classes#private_fields).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `in` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`for...in`](../statements/for...in)
* [`delete`](delete)
* [`Object.hasOwn()`](../global_objects/object/hasown)
* [`Reflect.has()`](../global_objects/reflect/has)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
javascript await await
=====
The `await` operator is used to wait for a [`Promise`](../global_objects/promise) and get its fulfillment value. It can only be used inside an [async function](../statements/async_function) or at the top level of a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).
Syntax
------
```
await expression
```
### Parameters
`expression` A [`Promise`](../global_objects/promise), a [thenable object](../global_objects/promise#thenables), or any value to wait for.
### Return value
The fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value.
### Exceptions
Throws the rejection reason if the promise or thenable object is rejected.
Description
-----------
`await` is usually used to unwrap promises by passing a [`Promise`](../global_objects/promise) as the `expression`. Using `await` pauses the execution of its surrounding `async` function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the `await` expression becomes that of the fulfilled promise.
If the promise is rejected, the `await` expression throws the rejected value. The function containing the `await` expression will [appear in the stack trace](#improving_stack_trace) of the error. Otherwise, if the rejected promise is not awaited or is immediately returned, the caller function will not appear in the stack trace.
The `expression` is resolved in the same way as [`Promise.resolve()`](../global_objects/promise/resolve): it's always converted to a native `Promise` and then awaited. If the `expression` is a:
* Native `Promise` (which means `expression` belongs to `Promise` or a subclass, and `expression.constructor === Promise`): The promise is directly used and awaited natively, without calling `then()`.
* [Thenable object](../global_objects/promise#thenables) (including non-native promises, polyfill, proxy, child class, etc.): A new promise is constructed with the native [`Promise()`](../global_objects/promise/promise) constructor by calling the object's `then()` method and passing in a handler that calls the `resolve` callback.
* Non-thenable value: An already-fulfilled `Promise` is constructed and used.
Even when the used promise is already fulfilled, the async function's execution still pauses until the next tick. In the meantime, the caller of the async function resumes execution. [See example below.](#control_flow_effects_of_await)
Because `await` is only valid inside async functions and modules, which themselves are asynchronous and return promises, the `await` expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the `await` expression.
Examples
--------
### Awaiting a promise to be fulfilled
If a `Promise` is passed to an `await` expression, it waits for the `Promise` to be fulfilled and returns the fulfilled value.
```
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
const x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
```
### Thenable objects
[Thenable objects](../global_objects/promise#thenables) are resolved just the same as actual `Promise` objects.
```
async function f() {
const thenable = {
then(resolve, \_reject) {
resolve("resolved!");
},
};
console.log(await thenable); // "resolved!"
}
f();
```
They can also be rejected:
```
async function f() {
const thenable = {
then(resolve, reject) {
reject(new Error("rejected!"));
},
};
await thenable; // Throws Error: rejected!
}
f();
```
### Conversion to promise
If the value is not a `Promise`, `await` converts the value to a resolved `Promise`, and waits for it. The awaited value's identity doesn't change as long as it doesn't have a `then` property that's callable.
```
async function f3() {
const y = await 20;
console.log(y); // 20
const obj = {};
console.log((await obj) === obj); // true
}
f3();
```
### Handling rejected promises
If the `Promise` is rejected, the rejected value is thrown.
```
async function f4() {
try {
const z = await Promise.reject(30);
} catch (e) {
console.error(e); // 30
}
}
f4();
```
You can handle rejected promises without a `try` block by chaining a [`catch()`](../global_objects/promise/catch) handler before awaiting the promise.
```
const response = await promisedFunction().catch((err) => {
console.error(err);
return "default response";
});
// response will be "default response" if the promise is rejected
```
This is built on the assumption that `promisedFunction()` never synchronously throws an error, but always returns a rejected promise. This is the case for most properly-designed promise-based functions, which usually look like:
```
function promisedFunction() {
// Immediately return a promise to minimize chance of an error being thrown
return new Promise((resolve, reject) => {
// do something async
});
}
```
However, if `promisedFunction()` does throw an error synchronously, the error won't be caught by the `catch()` handler. In this case, the `try...catch` statement is necessary.
### Top level await
You can use the `await` keyword on its own (outside of an async function) at the top level of a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). This means that modules with child modules that use `await` will wait for the child modules to execute before they themselves run, all while not blocking other child modules from loading.
Here is an example of a simple module using the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and specifying await within the [`export`](../statements/export) statement. Any modules that include this will wait for the fetch to resolve before running any code.
```
// fetch request
const colors = fetch("../data/colors.json").then((response) => response.json());
export default await colors;
```
### Control flow effects of await
When an `await` is encountered in code (either in an async function or in a module), the awaited expression is executed, while all code that depends on the expression's value is paused and pushed into the [microtask queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop). The main thread is then freed for the next task in the event loop. This happens even if the awaited value is an already-resolved promise or not a promise. For example, consider the following code:
```
async function foo(name) {
console.log(name, "start");
console.log(name, "middle");
console.log(name, "end");
}
foo("First");
foo("Second");
// First start
// First middle
// First end
// Second start
// Second middle
// Second end
```
In this case, the two async functions are synchronous in effect, because they don't contain any `await` expression. The three statements happen in the same tick. In promise terms, the function corresponds to:
```
function foo(name) {
return new Promise((resolve) => {
console.log(name, "start");
console.log(name, "middle");
console.log(name, "end");
resolve();
});
}
```
However, as soon as there's one `await`, the function becomes asynchronous, and execution of following statements is deferred to the next tick.
```
async function foo(name) {
console.log(name, "start");
await console.log(name, "middle");
console.log(name, "end");
}
foo("First");
foo("Second");
// First start
// First middle
// Second start
// Second middle
// First end
// Second end
```
This corresponds to:
```
function foo(name) {
return new Promise((resolve) => {
console.log(name, "start");
resolve(console.log(name, "middle"));
}).then(() => {
console.log(name, "end");
});
}
```
While the extra `then()` handler is not necessary, and the handler can be merged with the executor passed to the constructor, the `then()` handler's existence means the code will take one extra tick to complete. The same happens for `await`. Therefore, make sure to use `await` only when necessary (to unwrap promises into their values).
Other microtasks can execute before the async function resumes. This example uses [`queueMicrotask()`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) to demonstrate how the microtask queue is processed when each `await` expression is encountered.
```
let i = 0;
queueMicrotask(function test() {
i++;
console.log("microtask", i);
if (i < 3) {
queueMicrotask(test);
}
});
(async () => {
console.log("async function start");
for (let i = 1; i < 3; i++) {
await null;
console.log("async function resume", i);
}
await null;
console.log("async function end");
})();
queueMicrotask(() => {
console.log("queueMicrotask() after calling async function");
});
console.log("script sync part end");
// Logs:
// async function start
// script sync part end
// microtask 1
// async function resume 1
// queueMicrotask() after calling async function
// microtask 2
// async function resume 2
// microtask 3
// async function end
```
In this example, the `test()` function is always called before the async function resumes, so the microtasks they each schedule are always executed in an intertwined fashion. On the other hand, because both `await` and `queueMicrotask()` schedule microtasks, the order of execution is always based on the order of scheduling. This is why the "queueMicrotask() after calling async function" log happens after the async function resumes for the first time.
### Improving stack trace
Sometimes, the `await` is omitted when a promise is directly returned from an async function.
```
async function noAwait() {
// Some actions...
return /\* await \*/ lastAsyncTask();
}
```
However, consider the case where `lastAsyncTask` asynchronously throws an error.
```
async function lastAsyncTask() {
await null;
throw new Error("failed");
}
async function noAwait() {
return lastAsyncTask();
}
noAwait();
// Error: failed
// at lastAsyncTask
```
Only `lastAsyncTask` appears in the stack trace, because the promise is rejected after it has already been returned from `noAwait` — in some sense, the promise is unrelated to `noAwait`. To improve the stack trace, you can use `await` to unwrap the promise, so that the exception gets thrown into the current function. The exception will then be immediately wrapped into a new rejected promise, but during error creation, the caller will appear in the stack trace.
```
async function lastAsyncTask() {
await null;
throw new Error("failed");
}
async function withAwait() {
return await lastAsyncTask();
}
withAwait();
// Error: failed
// at lastAsyncTask
// at async withAwait
```
However, there's a little performance penalty coming with `return await` because the promise has to be unwrapped and wrapped again.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `await` | 55 | 14 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
| `top_level` | 89 | 89 | 89 | No | 75
73-75 | 15 | 89 | 89 | 89 | 63 | 15 | 15.0 | 1.0 | 14.8.0
Not supported in CommonJS modules.
14.3.0
Not supported in CommonJS modules. |
See also
--------
* [`async function`](../statements/async_function)
* [`async function` expression](async_function)
* [`AsyncFunction`](../global_objects/asyncfunction) object
* [Top level await](https://v8.dev/features/top-level-await) on v8.dev
| programming_docs |
javascript class expression class expression
================
The `class` keyword can be used to define a class inside an expression. Similar to [function expressions](function), class expressions can be named or unnamed. If named, the name of the class is local to the class body only.
Try it
------
Syntax
------
```
const MyClass = class [className] [extends otherClassName] {
// class body
}
```
Description
-----------
A class expression has a similar syntax to a [class declaration (statement)](../statements/class). As with `class` statements, the body of a `class` expression is executed in [strict mode](../strict_mode).
There are several differences between class expressions and [class statements](../statements/class), however:
* Class expressions may omit the class name ("binding identifier"), which is not possible with [class statements](../statements/class).
* Class expressions allow you to redefine (re-declare) classes **without throwing** a [`SyntaxError`](../global_objects/syntaxerror). This is not the case with [class statements](../statements/class).
The `constructor` method is optional. Classes generated with class expressions will always respond to [`typeof`](typeof) with the value `"function"`.
```
'use strict';
let Foo = class {}; // constructor property is optional
Foo = class {}; // Re-declaration is allowed
typeof Foo; // returns "function"
typeof class {}; // returns "function"
Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration)
```
Examples
--------
### A simple class expression
This is just a simple anonymous class expression which you can refer to using the variable `Foo`.
```
const Foo = class {
constructor() {}
bar() {
return 'Hello World!';
}
};
const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
```
### Named class expressions
If you want to refer to the current class inside the class body, you can create a *named class expression*. The name is only visible within the scope of the class expression itself.
```
const Foo = class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
}
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-class-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `class` | 42 | 13 | 45 | No | 29 | 7 | 42 | 42 | 45 | 29 | 7 | 4.0 | 1.0 | 6.0.0
5.0.0 |
See also
--------
* [function expression](function)
* [class declaration](../statements/class)
* [Classes](../classes)
javascript new.target new.target
==========
The `new.target` meta-property lets you detect whether a function or constructor was called using the [`new`](new) operator. In constructors and functions invoked using the [`new`](new) operator, `new.target` returns a reference to the constructor or function that `new` was called upon. In normal function calls, `new.target` is [`undefined`](../global_objects/undefined).
Try it
------
Syntax
------
```
new.target
```
### Value
`new.target` is guaranteed to be a constructable function value or `undefined`.
* In class constructors, it refers to the class that `new` was called upon, which may be a subclass of the current constructor, because subclasses transitively call the superclass's constructor through [`super()`](super).
* In ordinary functions, if the function is constructed directly with [`new`](new), `new.target` refers to the function itself. If the function is called without `new`, `new.target` is [`undefined`](../global_objects/undefined). Functions can be used as the base class for [`extends`](../classes/extends), in which case `new.target` may refer to the subclass.
* If a constructor (class or function) is called via [`Reflect.construct()`](../global_objects/reflect/construct), then `new.target` refers to the value passed as `newTarget` (which defaults to `target`).
* In [arrow functions](../functions/arrow_functions), `new.target` is inherited from the surrounding scope. If the arrow function is not defined within another class or function which has a `new.target` binding, then a syntax error is thrown.
* In [static initialization blocks](../classes/static_initialization_blocks), `new.target` is [`undefined`](../global_objects/undefined).
Description
-----------
The `new.target` syntax consists of the keyword `new`, a dot, and the identifier `target`. Because `new` is a [reserved word](../lexical_grammar#reserved_words), not an identifier, this is not a [property accessor](property_accessors), but a special expression syntax.
The `new.target` meta-property is available in all function/class bodies; using `new.target` outside of functions or classes is a syntax error.
Examples
--------
### new.target in function calls
In normal function calls (as opposed to constructor function calls), `new.target` is [`undefined`](../global_objects/undefined). This lets you detect whether a function was called with [`new`](new) as a constructor.
```
function Foo() {
if (!new.target) {
throw new Error("Foo() must be called with new");
}
console.log("Foo instantiated with new");
}
new Foo(); // Logs "Foo instantiated with new"
Foo(); // Throws "Foo() must be called with new"
```
### new.target in constructors
In class constructors, `new.target` refers to the constructor that was directly invoked by `new`. This is also the case if the constructor is in a parent class and was delegated from a child constructor. `new.target` points to the class that `new` was called upon. For example, when `b` was initialized using `new B()`, the name of `B` was printed; and similarly, in case of `a`, the name of class `A` was printed.
```
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
const a = new A(); // Logs "A"
const b = new B(); // Logs "B"
```
### new.target using Reflect.construct()
Before [`Reflect.construct()`](../global_objects/reflect/construct) or classes, it was common to implement inheritance by passing the value of [`this`](this), and letting the base constructor mutate it.
```
function Base() {
this.name = "Base";
}
function Extended() {
// Only way to make the Base() constructor work on the existing
// `this` value instead of a new object that `new` creates.
Base.call(this);
this.otherProperty = "Extended";
}
Object.setPrototypeOf(Extended.prototype, Base.prototype);
Object.setPrototypeOf(Extended, Base);
console.log(new Extended()); // Extended { name: 'Base', otherProperty: 'Extended' }
```
However, [`call()`](../global_objects/function/call) and [`apply()`](../global_objects/function/apply) actually *call* the function instead of *constructing* it, so `new.target` has value `undefined`. This means that if `Base()` checks whether it's constructed with `new`, an error will be thrown, or it may behave in other unexpected ways. For example, you can't extend [`Map`](../global_objects/map/map) this way, because the `Map()` constructor cannot be called without `new`.
All built-in constructors directly construct the entire prototype chain of the new instance by reading `new.target.prototype`. So to make sure that (1) `Base` is constructed with `new`, and (2) `new.target` points to the subclass instead of `Base` itself, we need to use [`Reflect.construct()`](../global_objects/reflect/construct).
```
function BetterMap(entries) {
// Call the base class constructor, but setting `new.target` to the subclass,
// so that the instance created has the correct prototype chain.
return Reflect.construct(Map, [entries], BetterMap);
}
BetterMap.prototype.upsert = function (key, actions) {
if (this.has(key)) {
this.set(key, actions.update(this.get(key)));
} else {
this.set(key, actions.insert());
}
};
Object.setPrototypeOf(BetterMap.prototype, Map.prototype);
Object.setPrototypeOf(BetterMap, Map);
const map = new BetterMap([["a", 1]]);
map.upsert("a", {
update: (value) => value + 1,
insert: () => 1,
});
console.log(map.get("a")); // 2
```
**Note:** In fact, due to the lack of `Reflect.construct()`, it is not possible to properly subclass built-ins (like [`Error` subclassing](../global_objects/error#custom_error_types)) when transpiling to pre-ES6 code.
However, if you are writing ES6 code, prefer using classes and `extends` instead, as it's more readable and less error-prone.
```
class BetterMap extends Map {
// The constructor is omitted because it's just the default one
upsert(key, actions) {
if (this.has(key)) {
this.set(key, actions.update(this.get(key)));
} else {
this.set(key, actions.insert());
}
}
}
const map = new BetterMap([["a", 1]]);
map.upsert("a", {
update: (value) => value + 1,
insert: () => 1,
});
console.log(map.get("a")); // 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-built-in-function-objects](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-built-in-function-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `new.target` | 46 | 13 | 41 | No | 33 | 11 | 46 | 46 | 41 | 33 | 11 | 5.0 | 1.0 | 5.0.0 |
See also
--------
* [Functions](../functions)
* [Classes](../classes)
* [`new`](new)
* [`this`](this)
javascript async function expression async function expression
=========================
The `async function` keywords can be used to define an async function inside an expression.
You can also define async functions using an [async function declaration](../statements/async_function).
Syntax
------
```
async function (param0) {
statements
}
async function (param0, param1) {
statements
}
async function (param0, param1, /\* … ,\*/ paramN) {
statements
}
async function name(param0) {
statements
}
async function name(param0, param1) {
statements
}
async function name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
Async functions can also be defined with the [arrow syntax](../functions/arrow_functions).
### Parameters
`name` Optional
The function name. Can be omitted, in which case the function is *anonymous*. The name is only local to the function body.
`paramN` Optional
The name of an argument to be passed to the function.
`statements` Optional
The statements which comprise the body of the function.
Description
-----------
An `async function` expression is very similar to, and has almost the same syntax as, an [`async function statement`](../statements/async_function). The main difference between an async `function` expression and an async `function` statement is the *function name*, which can be omitted in `async function` expressions to create *anonymous* functions. An `async function` expression can be used as an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about [functions](../functions) for more information.
Examples
--------
### Simple example
```
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// async function expression assigned to a variable
const add = async function (x) {
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
};
add(10).then((v) => {
console.log(v); // prints 60 after 4 seconds.
});
// async function expression used as an IIFE
(async function (x) {
const p1 = resolveAfter2Seconds(20);
const p2 = resolveAfter2Seconds(30);
return x + (await p1) + (await p2);
})(10).then((v) => {
console.log(v); // prints 60 after 2 seconds.
});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `async_function` | 55 | 15 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
See also
--------
* [`async function`](../statements/async_function)
* [`AsyncFunction`](../global_objects/asyncfunction) object
* [`await`](await)
javascript Equality (==) Equality (==)
=============
The `==` operator checks whether its two operands are equal, returning a Boolean result. Unlike the [strict equality](strict_equality) operator, it attempts to convert and compare operands that are of different types.
Try it
------
Syntax
------
```
x == y
```
Description
-----------
The equality operators (`==` and `!=`) provide the [IsLooselyEqual](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#loose_equality_using) semantic. This can be roughly summarized as follows:
1. If the operands have the same type, they are compared as follows:
* Object: return `true` only if both operands reference the same object.
* String: return `true` only if both operands have the same characters in the same order.
* Number: return `true` only if both operands have the same value. `+0` and `-0` are treated as the same value. If either operand is `NaN`, return `false`; so, `NaN` is never equal to `NaN`.
* Boolean: return `true` only if operands are both `true` or both `false`.
* BigInt: return `true` only if both operands have the same value.
* Symbol: return `true` only if both operands reference the same symbol.
2. If one of the operands is `null` or `undefined`, the other must also be `null` or `undefined` to return `true`. Otherwise return `false`.
3. If one of the operands is an object and the other is a primitive, [convert the object to a primitive](https://developer.mozilla.org/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](../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](../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()`](../global_objects/bigint/bigint) constructor. If conversion fails, return `false`.
Loose equality is *symmetric*: `A == B` always has identical semantics to `B == A` for any values of `A` and `B` (except for the order of applied conversions).
The most notable difference between this operator and the [strict equality](strict_equality) (`===`) operator is that the strict equality operator does not attempt type conversion. Instead, the strict equality operator always considers operands of different types to be different. The strict equality operator essentially carries out only step 1, and then returns `false` for all other cases.
There's a "willful violation" of the above algorithm: if one of the operands is [`document.all`](https://developer.mozilla.org/en-US/docs/Web/API/Document/all), it is treated as if it's `undefined`. This means that `document.all == null` is `true`, but `document.all === undefined && document.all === null` is `false`.
Examples
--------
### Comparison with no type conversion
```
1 == 1; // true
"hello" == "hello"; // true
```
### Comparison with type conversion
```
"1" == 1; // true
1 == "1"; // true
0 == false; // true
0 == null; // false
0 == undefined; // false
0 == !!null; // true, look at Logical NOT operator
0 == !!undefined; // true, look at Logical NOT operator
null == undefined; // true
const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3; // true
number1 == number2; // false
```
### Comparison of objects
```
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 == object2); // false
console.log(object1 == object1); // true
```
### Comparing strings and String objects
Note that strings constructed using `new String()` are objects. If you compare one of these with a string literal, the `String` object will be converted to a string literal and the contents will be compared. However, if both operands are `String` objects, then they are compared as objects and must reference the same object for comparison to succeed:
```
const string1 = "hello";
const string2 = String("hello");
const string3 = new String("hello");
const string4 = new String("hello");
console.log(string1 == string2); // true
console.log(string1 == string3); // true
console.log(string2 == string3); // true
console.log(string3 == string4); // false
console.log(string4 == string4); // true
```
### Comparing Dates and strings
```
const d = new Date("December 17, 1995 03:24:00");
const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
console.log(d == s); //true
```
### Comparing arrays and strings
```
const a = [1, 2, 3];
const b = "1,2,3";
a == b; // true, `a` converts to string
const c = [true, 0.5, "hey"];
const d = c.toString(); // "true,0.5,hey"
c == d; // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-equality-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-equality-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Equality` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Inequality operator](inequality)
* [Strict equality operator](strict_equality)
* [Strict inequality operator](strict_inequality)
javascript Subtraction (-) Subtraction (-)
===============
The `-` operator subtracts the two operands, producing their difference.
Try it
------
Syntax
------
```
x - y
```
Description
-----------
The subtraction operator [converts both operands to numeric values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and carries out either number subtraction or [BigInt](../global_objects/bigint) subtraction, depending on the two operands' types. If the types don't match, a [`TypeError`](../global_objects/typeerror) is thrown.
Examples
--------
### Subtraction with numbers
```
// Number - Number -> subtraction
5 - 3; // 2
// Number - Number -> subtraction
3 - 5; // -2
```
### Subtraction with non-numbers
```
// String - Number -> subtraction
"foo" - 3; // NaN; "foo" is converted to the number NaN
// Number - String -> subtraction
5 - "3"; // 2; "3" is converted to the number 3
```
### Subtraction with BigInts
```
// BigInt - BigInt -> subtraction
2n - 1n; // 1n
```
You cannot mix BigInt and number operands in subtraction.
```
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-subtraction-operator-minus](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-subtraction-operator-minus) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Subtraction` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
| programming_docs |
javascript Increment (++) Increment (++)
==============
The `++` operator increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.
Try it
------
Syntax
------
```
x++
++x
```
Description
-----------
If used postfix, with operator after operand (for example, `x++`), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, `++x`), the increment operator increments and returns the value after incrementing.
The increment operator can only be applied on operands that are references (variables and object properties; i.e. valid [assignment targets](assignment)). `++x` itself evaluates to a value, not a reference, so you cannot chain multiple increment operators together.
```
++(++x); // SyntaxError: Invalid left-hand side expression in prefix operation
```
Examples
--------
### Postfix increment
```
let x = 3;
const y = x++;
// x = 4
// y = 3
```
### Prefix increment
```
let x = 3;
const y = ++x;
// x = 4
// y = 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-postfix-increment-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-postfix-increment-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Increment` | 2 | 12 | 1 | 3 | 3 | 4 | 4.4 | 18 | 4 | 10.1 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript Nullish coalescing assignment (??=) Nullish coalescing assignment (??=)
===================================
The `x ??= y` operator only assigns if `x` is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`).
Try it
------
Syntax
------
```
expr1 ??= expr2
```
Description
-----------
Nullish coalescing assignment [*short-circuits*](operator_precedence#short-circuiting), meaning that `x ??= y` is equivalent to:
```
x ?? (x = y);
```
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the [nullish coalescing](nullish_coalescing) operator. For example, the following does not throw an error, despite `x` being `const`:
```
const x = 1;
x ??= 2;
```
Neither would the following trigger the setter:
```
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ??= 2;
```
In fact, if `x` is not nullish, `y` is not evaluated at all.
```
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing
```
Examples
--------
### Using nullish coalescing assignment
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and [default values](destructuring_assignment#default_value), `??=` also applies the default value if the property has value `null`.
```
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Nullish_coalescing_assignment` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [The nullish coalescing operator (`??`)](nullish_coalescing)
* [Nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
javascript instanceof instanceof
==========
The `instanceof` operator tests to see if the `prototype` property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with [`Symbol.hasInstance`](../global_objects/symbol/hasinstance).
Try it
------
Syntax
------
```
object instanceof constructor
```
### Parameters
`object` The object to test.
`constructor` Constructor to test against.
### Exceptions
[`TypeError`](../global_objects/typeerror) Thrown if `constructor` is not an object. If `constructor` doesn't have a [`@@hasInstance`](../global_objects/symbol/hasinstance) method, it must also be a function.
Description
-----------
The `instanceof` operator tests the presence of `constructor.prototype` in `object`'s prototype chain. This usually (though [not always](#overriding_the_behavior_of_instanceof)) means `object` was constructed with `constructor`.
```
// defining constructors
function C() {}
function D() {}
const o = new C();
// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;
// false, because D.prototype is nowhere in o's prototype chain
o instanceof D;
o instanceof Object; // true, because:
C.prototype instanceof Object; // true
// Re-assign `constructor.prototype`: you should
// rarely do this in practice.
C.prototype = {};
const o2 = new C();
o2 instanceof C; // true
// false, because C.prototype is nowhere in
// o's prototype chain anymore
o instanceof C;
D.prototype = new C(); // add C to [[Prototype]] linkage of D
const o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true since C.prototype is now in o3's prototype chain
```
Note that the value of an `instanceof` test can change if `constructor.prototype` is re-assigned after creating the object (which is usually discouraged). It can also be changed by changing `object`'s prototype using [`Object.setPrototypeOf`](../global_objects/object/setprototypeof).
Classes behave in the same way, because classes also have the `prototype` property.
```
class A {}
class B extends A {}
const o1 = new A();
// true, because Object.getPrototypeOf(o1) === A.prototype
o1 instanceof A;
// false, because B.prototype is nowhere in o1's prototype chain
o1 instanceof B;
const o2 = new B();
// true, because Object.getPrototypeOf(Object.getPrototypeOf(o2)) === A.prototype
o2 instanceof A;
// true, because Object.getPrototypeOf(o2) === B.prototype
o2 instanceof B;
```
For [bound functions](../global_objects/function/bind), `instanceof` looks up for the `prototype` property on the target function, since bound functions don't have `prototype`.
```
class Base {}
const BoundBase = Base.bind(null, 1, 2);
console.log(new Base() instanceof BoundBase); // true
```
### instanceof and @@hasInstance
If `constructor` has a [`Symbol.hasInstance`](../global_objects/symbol/hasinstance) method, the method will be called in priority, with `object` as its only argument and `constructor` as `this`.
```
// This class allows plain objects to be disguised as this class's instance,
// as long as the object has a particular flag as its property.
class Forgeable {
static isInstanceFlag = Symbol("isInstanceFlag");
static [Symbol.hasInstance](obj) {
return Forgeable.isInstanceFlag in obj;
}
}
const obj = { [Forgeable.isInstanceFlag]: true };
console.log(obj instanceof Forgeable); // true
```
### instanceof and multiple realms
JavaScript execution environments (windows, frames, etc.) are each in their own *realm*. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, `[] instanceof window.frames[0].Array` will return `false`, because `Array.prototype !== window.frames[0].Array.prototype` and arrays in the current realm inherit from the former.
This may not make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is in fact an Array using [`Array.isArray()`](../global_objects/array/isarray), neglecting which realm it comes from.
For example, to check if a [`Node`](https://developer.mozilla.org/en-US/docs/Web/API/Node) is an [`SVGElement`](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement) in a different context, you can use `myNode instanceof myNode.ownerDocument.defaultView.SVGElement`.
Examples
--------
### Using instanceof with String
The following example shows the behavior of `instanceof` with `String` objects.
```
const literalString = "This is a literal string";
const stringObject = new String("String created with constructor");
literalString instanceof String; // false, string primitive is not a String
stringObject instanceof String; // true
literalString instanceof Object; // false, string primitive is not an Object
stringObject instanceof Object; // true
stringObject instanceof Date; // false
```
### Using instanceof with Date
The following example shows the behavior of `instanceof` with `Date` objects.
```
const myDate = new Date();
myDate instanceof Date; // true
myDate instanceof Object; // true
myDate instanceof String; // false
```
### Objects created using Object.create()
The following example shows the behavior of `instanceof` with objects created using [`Object.create()`](../global_objects/object/create).
```
function Shape() {}
function Rectangle() {
Shape.call(this); // call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
const rect = new Rectangle();
rect instanceof Object; // true
rect instanceof Shape; // true
rect instanceof Rectangle; // true
rect instanceof String; // false
const literalObject = {};
const nullObject = Object.create(null);
nullObject.name = "My object";
literalObject instanceof Object; // true, every object literal has Object.prototype as prototype
({} instanceof Object); // true, same case as above
nullObject instanceof Object; // false, prototype is end of prototype chain (null)
```
### Demonstrating that mycar is of type Car and type Object
The following code creates an object type `Car` and an instance of that object type, `mycar`. The `instanceof` operator demonstrates that the `mycar` object is of type `Car` and of type `Object`.
```
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const mycar = new Car("Honda", "Accord", 1998);
const a = mycar instanceof Car; // returns true
const b = mycar instanceof Object; // returns true
```
### Not an instanceof
To test if an object is not an `instanceof` a specific constructor, you can do:
```
if (!(mycar instanceof Car)) {
// Do something, like:
// mycar = new Car(mycar)
}
```
This is really different from:
```
if (!mycar instanceof Car) {
// unreachable code
}
```
This will always be `false`. (`!mycar` will be evaluated before `instanceof`, so you always try to know if a boolean is an instance of `Car`).
### Overriding the behavior of instanceof
A common pitfall of using `instanceof` is believing that, if `x instanceof C`, then `x` was created using `C` as constructor. This is not true, because `x` could be directly assigned with `C.prototype` as its prototype. In this case, if your code reads [private fields](../classes/private_class_fields) of `C` from `x`, it would still fail:
```
class C {
#value = "foo";
static getValue(x) {
return x.#value;
}
}
const x = { \_\_proto\_\_: C.prototype };
if (x instanceof C) {
console.log(C.getValue(x)); // TypeError: Cannot read private member #value from an object whose class did not declare it
}
```
To avoid this, you can override the behavior of `instanceof` by adding a `Symbol.hasInstance` method to `C`, so that it does a branded check with [`in`](in):
```
class C {
#value = "foo";
static [Symbol.hasInstance](x) {
return #value in x;
}
static getValue(x) {
return x.#value;
}
}
const x = { \_\_proto\_\_: C.prototype };
if (x instanceof C) {
// Doesn't run, because x is not a C
console.log(C.getValue(x));
}
```
Note that you may want to limit this behavior to the current class; otherwise, it could lead to false positives for subclasses:
```
class D extends C {}
console.log(new C() instanceof D); // true; because D inherits @@hasInstance from C
```
You could do this by checking that `this` is the current constructor:
```
class C {
#value = "foo";
static [Symbol.hasInstance](x) {
return this === C && #value in x;
}
}
class D extends C {}
console.log(new C() instanceof D); // false
console.log(new C() instanceof C); // true
console.log({ \_\_proto\_\_: C.prototype } instanceof C); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `instanceof` | 1 | 12 | 1 | 5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`typeof`](typeof)
* [`Symbol.hasInstance`](../global_objects/symbol/hasinstance)
* [`Object.prototype.isPrototypeOf`](../global_objects/object/isprototypeof)
javascript Object initializer Object initializer
==================
An **object initializer** is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (`{}`). Objects can also be initialized using [`new Object()`](../global_objects/object/object) or [`Object.create()`](../global_objects/object/create).
Try it
------
Syntax
------
```
o = {};
o = {a: 'foo', b: 42, c: {}};
const a = 'foo';
const b = 42;
const c = {};
o = { a: a, b: b, c: c };
o = {
get property() {},
set property(value) {},
};
o = { \_\_proto\_\_: prototype };
// Shorthand property names
o = { a, b, c };
// Shorthand method names
o = {
property(parameters) {},
};
// Computed property names
const prop = 'foo';
o = {
[prop]: 'hey',
['b' + 'ar']: 'there',
};
```
Description
-----------
An object initializer is an expression that describes the initialization of an [`Object`](../global_objects/object). Objects consist of *properties*, which are used to describe an object. The values of object properties can either contain [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) data types or other objects.
### Object literal syntax vs. JSON
The object literal syntax is not the same as the **J**ava**S**cript **O**bject **N**otation ([JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON)). Although they look similar, there are differences between them:
* JSON *only* permits property definition using the `"property": value` syntax. The property name must be double-quoted, and the definition cannot be a shorthand. Computed property names are not allowed either.
* JSON object property values can only be strings, numbers, `true`, `false`, `null`, arrays, or another JSON object. This means JSON cannot express methods or non-plain objects like [`Date`](../global_objects/date) or [`RegExp`](../global_objects/regexp).
* In JSON, `"__proto__"` is a normal property key. In an object literal, it [sets the object's prototype](#prototype_setter).
JSON is a *strict subset* of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate `__proto__` keys, which does not apply to [`JSON.parse()`](../global_objects/json/parse). The latter treats `__proto__` like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the `__proto__` key — for object literals, it sets the object's prototype; for JSON, it's a normal property.
```
console.log(JSON.parse('{ "\_\_proto\_\_": 0, "\_\_proto\_\_": 1 }')); // {\_\_proto\_\_: 1}
console.log({ "\_\_proto\_\_": 0, "\_\_proto\_\_": 1 }); // SyntaxError: Duplicate \_\_proto\_\_ fields are not allowed in object literals
console.log(JSON.parse('{ "\_\_proto\_\_": {} }')); // { \_\_proto\_\_: {} }
console.log({ "\_\_proto\_\_": {} }); // {} (with {} as prototype)
```
Examples
--------
### Creating objects
An empty object with no properties can be created like this:
```
const object = {};
```
However, the advantage of the *literal* or *initializer* notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of `key: value` pairs delimited by commas.
The following code creates an object with three properties and the keys are `"foo"`, `"age"` and `"baz"`. The values of these keys are a string `"bar"`, the number `42`, and another object.
```
const object = {
foo: 'bar',
age: 42,
baz: { myProp: 12 },
};
```
### Accessing properties
Once you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See [property accessors](property_accessors) for detailed information.)
```
object.foo // "bar"
object['age'] // 42
object.baz // {myProp: 12}
object.baz.myProp //12
```
### Property definitions
We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:
```
const a = 'foo';
const b = 42;
const c = {};
const o = {
a: a,
b: b,
c: c,
};
```
There is a shorter notation available to achieve the same:
```
const a = 'foo';
const b = 42;
const c = {};
// Shorthand property names
const o = { a, b, c };
// In other words,
console.log(o.a === { a }.a); // true
```
#### Duplicate property names
When using the same name for your properties, the second property will overwrite the first.
```
const a = { x: 1, x: 2 };
console.log(a); // {x: 2}
```
In ECMAScript 5 strict mode code, duplicate property names were considered a [`SyntaxError`](../global_objects/syntaxerror). With the introduction of computed property names making duplication possible at runtime, ECMAScript 2015 has removed this restriction.
```
function haveES2015DuplicatePropertySemantics() {
'use strict';
try {
({ prop: 1, prop: 2 });
// No error thrown, duplicate property names allowed in strict mode
return true;
} catch (e) {
// Error thrown, duplicates prohibited in strict mode
return false;
}
}
```
### Method definitions
A property of an object can also refer to a [function](../functions) or a [getter](../functions/get) or [setter](../functions/set) method.
```
const o = {
property: function (parameters) {},
get property() {},
set property(value) {},
};
```
A shorthand notation is available, so that the keyword `function` is no longer necessary.
```
// Shorthand method names
const o = {
property(parameters) {},
};
```
There is also a way to concisely define generator methods.
```
const o = {
\*generator() {
// …
},
};
```
Which is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):
```
const o = {
generator: function\* () {
// …
},
};
```
For more information and examples about methods, see [method definitions](../functions/method_definitions).
### Computed property names
The object initializer syntax also supports computed property names. That allows you to put an expression in brackets `[]`, that will be computed and used as the property name. This is reminiscent of the bracket notation of the [property accessor](property_accessors) syntax, which you may have used to read and set properties already.
Now you can use a similar syntax in object literals, too:
```
// Computed property names
let i = 0;
const a = {
[`foo${++i}`]: i,
[`foo${++i}`]: i,
[`foo${++i}`]: i,
};
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
const items = ["A", "B", "C"];
const obj = {
[items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"
const param = 'size';
const config = {
[param]: 12,
[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};
console.log(config); // {size: 12, mobileSize: 4}
```
### Spread properties
Object literals support the [spread syntax](spread_syntax). It copies own enumerable properties from a provided object onto a new object.
Shallow-cloning (excluding `prototype`) or merging objects is now possible using a shorter syntax than [`Object.assign()`](../global_objects/object/assign).
```
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 }
```
**Warning:** Note that [`Object.assign()`](../global_objects/object/assign) triggers [setters](../functions/set), whereas the spread syntax doesn't!
### Prototype setter
A property definition of the form `__proto__: value` or `"__proto__": value` does not create a property with the name `__proto__`. Instead, if the provided value is an object or [`null`](null), it points the `[[Prototype]]` of the created object to that value. (If the value is not an object or `null`, the object is not changed.)
Note that the `__proto__` key is standardized syntax, in contrast to the non-standard and non-performant [`Object.prototype.__proto__`](../global_objects/object/proto) accessors. It sets the `[[Prototype]]` during object creation, similar to [`Object.create`](../global_objects/object/create) — instead of mutating the prototype chain.
```
const obj1 = {};
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
const obj2 = { \_\_proto\_\_: null };
console.log(Object.getPrototypeOf(obj2)); // null
const protoObj = {};
const obj3 = { "\_\_proto\_\_": protoObj };
console.log(Object.getPrototypeOf(obj3) === protoObj); // true
const obj4 = { \_\_proto\_\_: "not an object or null" };
console.log(Object.getPrototypeOf(obj4) === Object.prototype); // true
console.log(Object.hasOwn(obj4, "\_\_proto\_\_")); // false
```
Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.
Property definitions that do not use "colon" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.
```
const __proto__ = "variable";
const obj1 = { __proto__ };
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
console.log(Object.hasOwn(obj1, "\_\_proto\_\_")); // true
console.log(obj1.__proto__); // "variable"
const obj2 = { \_\_proto\_\_() { return "hello"; } };
console.log(obj2.\_\_proto\_\_()); // "hello"
const obj3 = { ["\_\_proto\_\_"]: 17 };
console.log(obj3.__proto__); // 17
// Mixing prototype setter with normal own properties with "\_\_proto\_\_" key
const obj4 = { ["\_\_proto\_\_"]: 17, \_\_proto\_\_: {} }; // {\_\_proto\_\_: 17} (with {} as prototype)
const obj5 = {
["\_\_proto\_\_"]: 17,
\_\_proto\_\_: {},
\_\_proto\_\_: null, // SyntaxError: Duplicate \_\_proto\_\_ fields are not allowed in object literals
};
const obj6 = {
["\_\_proto\_\_"]: 17,
["\_\_proto\_\_"]: "hello",
\_\_proto\_\_: null,
}; // {\_\_proto\_\_: "hello"} (with null as prototype)
const obj7 = {
["\_\_proto\_\_"]: 17,
__proto__,
\_\_proto\_\_: null,
}; // {\_\_proto\_\_: "variable"} (with null as prototype)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object-initializer](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-object-initializer) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Object_initializer` | 1 | 12 | 1 | 1 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `computed_property_names` | 47 | 12 | 34 | No | 34 | 8 | 47 | 47 | 34 | 34 | 8 | 5.0 | ? | 4.0.0 |
| `shorthand_method_names` | 47 | 12 | 34 | No | 34 | 9 | 47 | 47 | 34 | 34 | 9 | 5.0 | ? | 4.0.0 |
| `shorthand_property_names` | 47 | 12 | 33 | No | 34 | 9 | 47 | 47 | 33 | 34 | 9 | 5.0 | ? | 4.0.0 |
| `spread_properties` | 60 | 79 | 55 | No | 47 | 11.1 | 60 | 60 | 55 | 44 | 11.3 | 8.0 | ? | 8.3.0 |
See also
--------
* [Property accessors](property_accessors)
* [`get`](../functions/get) / [`set`](../functions/set)
* [Method definitions](../functions/method_definitions)
* [Lexical grammar](../lexical_grammar)
| programming_docs |
javascript Less than (<) Less than (<)
=============
The `<` operator returns `true` if the left operand is less than the right operand, and `false` otherwise.
Try it
------
Syntax
------
```
x < y
```
Description
-----------
The operands are compared with multiple rounds of coercion, which can be summarized as follows:
* First, objects are [converted to primitives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](../global_objects/symbol/toprimitive) (with `"number"` as hint), [`valueOf()`](../global_objects/object/valueof), and [`toString()`](../global_objects/object/tostring) methods, in that order. The left operand is always coerced before the right one. Note that although `[@@toPrimitive]()` is called with the `"number"` hint (meaning there's a slight preference for the object to become a number), the return value is not [converted to a number](../global_objects/number#number_coercion), since strings are still specially handled.
* If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain.
* Otherwise JavaScript attempts to convert non-numeric types to numeric values:
+ Boolean values `true` and `false` are converted to 1 and 0 respectively.
+ `null` is converted to 0.
+ `undefined` is converted to `NaN`.
+ Strings are converted based on the values they contain, and are converted as `NaN` if they do not contain numeric values.
* If either value is [`NaN`](../global_objects/nan), the operator returns `false`.
* Otherwise the values are compared as numeric values. BigInt and number values can be compared together.
Other operators, including [`>`](greater_than), [`>=`](greater_than_or_equal), and [`<=`](less_than_or_equal), use the same algorithm as `<`. There are two cases where all four operators return `false`:
* If one of the operands gets converted to a BigInt, while the other gets converted to a string that cannot be converted to a BigInt value (it throws a [syntax error](../errors/invalid_bigint_syntax) when passed to [`BigInt()`](../global_objects/bigint/bigint)).
* If one of the operands gets converted to `NaN`. (For example, strings that cannot be converted to numbers, or `undefined`.)
For all other cases, the four operators have the following relationships:
```
x < y === !(x >= y);
x <= y === !(x > y);
x > y === y < x;
x >= y === y <= x;
```
**Note:** One observable difference between `<` and `>` is the order of coercion, especially if the coercion to primitive has side effects. All comparison operators coerce the left operand before the right operand.
Examples
--------
### String to string comparison
```
console.log("a" < "b"); // true
console.log("a" < "a"); // false
console.log("a" < "3"); // false
```
### String to number comparison
```
console.log("5" < 3); // false
console.log("3" < 3); // false
console.log("3" < 5); // true
console.log("hello" < 5); // false
console.log(5 < "hello"); // false
console.log("5" < 3n); // false
console.log("3" < 5n); // true
```
### Number to Number comparison
```
console.log(5 < 3); // false
console.log(3 < 3); // false
console.log(3 < 5); // true
```
### Number to BigInt comparison
```
console.log(5n < 3); // false
console.log(3 < 5n); // true
```
### Comparing Boolean, null, undefined, NaN
```
console.log(true < false); // false
console.log(false < true); // true
console.log(0 < true); // true
console.log(true < 1); // false
console.log(null < 0); // false
console.log(null < 1); // true
console.log(undefined < 3); // false
console.log(3 < undefined); // false
console.log(3 < NaN); // false
console.log(NaN < 3); // false
```
### Comparison with side effects
Comparisons always coerce their operands to primitives. This means the same object may end up having different values within one comparison expression. For example, you may have two values that are both greater than and less than the other.
```
class Mystery {
static #coercionCount = -1;
valueOf() {
Mystery.#coercionCount++;
// The left operand is coerced first, so this will return 0
// Then it returns 1 for the right operand
return Mystery.#coercionCount % 2;
}
}
const l = new Mystery();
const r = new Mystery();
console.log(l < r && r < l);
// true
```
**Warning:** This can be a source of confusion. If your objects provide custom primitive conversion logic, make sure it is *idempotent*: multiple coercions should return the same value.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Less_than` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Greater than operator](greater_than)
* [Greater than or equal operator](greater_than_or_equal)
* [Less than or equal operator](less_than_or_equal)
javascript Strict inequality (!==) Strict inequality (!==)
=======================
The `!==` operator checks whether its two operands are not equal, returning a Boolean result. Unlike the <inequality> operator, the strict inequality operator always considers operands of different types to be different.
Try it
------
Syntax
------
```
x !== y
```
Description
-----------
The strict inequality operator checks whether its operands are not equal. It is the negation of the [strict equality](strict_equality) operator so the following two lines will always give the same result:
```
x !== y;
!(x === y);
```
For details of the comparison algorithm, see the page for the [strict equality](strict_equality) operator.
Like the strict equality operator, the strict inequality operator will always consider operands of different types to be different:
```
3 !== "3"; // true
```
Examples
--------
### Comparing operands of the same type
```
"hello" !== "hello"; // false
"hello" !== "hola"; // true
3 !== 3; // false
3 !== 4; // true
true !== true; // false
true !== false; // true
null !== null; // false
```
### Comparing operands of different types
```
"3" !== 3; // true
true !== 1; // true
null !== undefined; // true
```
### Comparing objects
```
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 !== object2); // true
console.log(object1 !== object1); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-equality-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-equality-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Strict_inequality` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Equality operator](equality)
* [Inequality operator](inequality)
* [Strict equality operator](strict_equality)
javascript Unary negation (-) Unary negation (-)
==================
The `-` operator precedes its operand and negates it.
Try it
------
Syntax
------
```
-x
```
Examples
--------
### Negating numbers
```
const x = 3;
const y = -x;
// y = -3
// x = 3
```
### Negating non-numbers
The unary negation operator can [convert a non-number into a number](../global_objects/number#number_coercion).
```
const x = "4";
const y = -x;
// y = -4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-unary-minus-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-unary-minus-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Unary_negation` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary plus operator](unary_plus)
javascript Comma operator (,) Comma operator (,)
==================
The `,` operator evaluates each of its operands (from left to right) and returns the value of the last operand. This is commonly used to provide multiple updaters to a [`for`](../statements/for) loop's afterthought.
Try it
------
Syntax
------
```
expr1, expr2, expr3/\* , … \*/
```
### Parameters
`expr1`, `expr2`, `expr3`, … One or more expressions, the last of which is returned as the value of the compound expression.
Description
-----------
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple updaters in a `for` loop.
Because all expressions except the last are evaluated and then discarded, these expressions must have side effects to be useful. Common expressions that have side effects are assignments, function calls, and [`++`](increment) and [`--`](decrement) operators. Others may also have side effects if they invoke [getters](../functions/get) or trigger [type coercions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion).
The comma operator has the lowest [precedence](operator_precedence) of all operators. If you want to incorporate a comma-joined expression into a bigger expression, you must parenthesize it.
The comma operator is completely different from commas used as syntactic separators in other locations, which include:
* Elements in array initializers (`[1, 2, 3]`)
* Properties in [object initializers](object_initializer) (`{ a: 1, b: 2 }`)
* Parameters in [function declarations](../statements/function)/expressions (`function f(a, b) { … }`)
* Arguments in function calls (`f(1, 2)`)
* Binding lists in [`let`](../statements/let), [`const`](../statements/const), or [`var`](../statements/var) declarations (`const a = 1, b = 2;`)
* Import lists in [`import`](../statements/import) declarations (`import { a, b } from "c";`)
* Export lists in [`export`](../statements/export) declarations (`export { a, b };`)
In fact, although some of these places accept almost all expressions, they don't accept comma-joined expressions because that would be ambiguous with the syntactic comma separators. In this case, you must parenthesize the comma-joined expression. For example, the following is a `const` declaration that declares two variables, where the comma is not the comma operator:
```
const a = 1, b = 2;
```
It is different from the following, where `b = 2` is an [assignment expression](assignment), not a declaration. The value of `a` is `2`, the return value of the assignment, while the value of `1` is discarded:
```
const a = (1, b = 2);
```
Comma operators cannot appear as [trailing commas](../trailing_commas).
Examples
--------
### Using the comma operator in a for loop
If `a` is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment `i` and decrement `j` at once, thus printing the values of the diagonal elements in the array:
```
const a = Array.from({ length: 10 }, () =>
Array.from({ length: 10 }, Math.random),
); // A 10×10 array of random numbers
for (let i = 0, j = 9; i <= 9; i++, j--) {
console.log(`a[${i}][${j}] = ${a[i][j]}`);
}
```
### Using the comma operator to join assignments
Because commas have the lowest [precedence](operator_precedence) — even lower than assignment — commas can be used to join multiple assignment expressions. In the following example, `a` is set to the value of `b = 3` (which is 3). Then, the `c = 4` expression evaluates and its result becomes the return value of the entire comma expression.
```
let a, b, c;
a = b = 3, c = 4; // Returns 4
console.log(a); // 3 (left-most)
let x, y, z;
x = (y = 5, z = 6); // Returns 6
console.log(x); // 6 (right-most)
```
### Processing and then returning
Another example that one could make with the comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:
```
function myFunc() {
let x = 0;
return (x += 1, x); // the same as return ++x;
}
```
This is especially useful for one-line [arrow functions](../functions/arrow_functions). The following example uses a single [`map()`](../global_objects/array/map) to get both the sum of an array and the squares of its elements, which would otherwise require two iterations, one with [`reduce()`](../global_objects/array/reduce) and one with `map()`:
```
let sum = 0;
const squares = [1, 2, 3, 4, 5].map((x) => (sum += x, x \* x));
console.log(squares); // [1, 4, 9, 16, 25]
console.log(sum); // 15
```
### Discarding reference binding
The comma operator always returns the last expression as a *value* instead of a *reference*. This causes some contextual information such as the [`this`](this) binding to be lost. For example, a property access returns a reference to the function, which also remembers the object that it's accessed on, so that calling the property works properly. If the method is returned from a comma expression, then the function is called as if it's a new function value, and `this` is `undefined`.
```
const obj = {
value: "obj",
method() {
console.log(this.value);
},
};
obj.method(); // "obj"
(obj.method)(); // "obj" (the grouping operator still returns the reference)
(0, obj.method)(); // undefined (the comma operator returns a new value)
```
You can enter [indirect eval](../global_objects/eval#direct_and_indirect_eval) with this technique, because direct eval requires the function call to happen on the reference to the `eval()` function.
```
globalThis.isDirectEval = false;
{
const isDirectEval = true;
console.log(eval("isDirectEval")); // true
console.log((eval)("isDirectEval")); // true (the grouping operator still returns a reference to `eval`)
console.log((0, eval)("isDirectEval")); // false (the comma operator returns a new value)
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-comma-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-comma-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Comma_Operator` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`for` loop](../statements/for)
javascript import() import()
========
The `import()` syntax, commonly called *dynamic import*, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
Unlike the [declaration-style counterpart](../statements/import), dynamic imports are only evaluated when needed, and permits greater syntactic flexibility.
Syntax
------
```
import(moduleName)
```
The `import()` call is a syntax that closely resembles a function call, but `import` itself is a keyword, not a function. You cannot alias it like `const myImport = import`, which will throw a [`SyntaxError`](../global_objects/syntaxerror).
### Parameters
`moduleName` The module to import from. The evaluation of the specifier is host-specified, but always follows the same algorithm as static [import declarations](../statements/import).
### Return value
It returns a promise which fulfills to an object containing all exports from `moduleName`, with the same shape as a namespace import (`import * as name from moduleName`): a [sealed](../global_objects/object/issealed) object with [`null` prototype](../global_objects/object#null-prototype_objects). All keys are [enumerable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) in lexicographic order (i.e. the default behavior of [`Array.prototype.sort()`](../global_objects/array/sort#description)), with the default export available as a key called `default`.
Description
-----------
The import declaration syntax (`import something from "somewhere"`) is static and will always result in the imported module being evaluated at load time. Dynamic imports allows one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand. The following are some reasons why you might need to use dynamic import:
* When importing statically significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time.
* When importing statically significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing.
* When the module you are importing does not exist at load time.
* When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers.)
* When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.)
* When you are in a non-module environment (for example, `eval` or a script file).
Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and [tree shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking).
If your file is not run as a module (if it's referenced in an HTML file, the script tag must have `type="module"`), you will not be able to use static import declarations, but the asynchronous dynamic import syntax will always be available, allowing you to import modules into non-module environments.
Examples
--------
### Import a module for its side effects only
```
(async () => {
if (somethingIsTrue) {
// import module for side effects
await import("/modules/my-module.js");
}
})();
```
If your project uses packages that export ESM, you can also import them for side effects only. This will run the code in the package entry point file (and any files it imports) only.
### Importing defaults
You need to destructure and rename the "default" key from the returned object.
```
(async () => {
if (somethingIsTrue) {
const {
default: myDefault,
foo,
bar,
} = await import("/modules/my-module.js");
}
})();
```
### Importing on-demand in response to user action
This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The `import()` function also supports `await`.
```
const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
link.addEventListener("click", (e) => {
e.preventDefault();
import("/modules/my-module.js")
.then((module) => {
module.loadPageInto(main);
})
.catch((err) => {
main.textContent = err.message;
});
});
}
```
### Importing different modules based on environment
In processes such as server-side rendering, you may need to load different logic on server or in browser because they interact with different globals or modules (for example, browser code has access to web APIs like `document` and `navigator`, while server code has access to the server file system). You can do so through a conditional dynamic import.
```
let myModule;
if (typeof window === "undefined") {
myModule = await import("module-used-on-server");
} else {
myModule = await import("module-used-in-browser");
}
```
### Importing modules with a non-literal specifier
Dynamic imports allow any expression as the module specifier, not necessarily string literals.
Here, we load 10 modules, `/modules/module-0.js`, `/modules/module-1.js`, etc., in parallel, and call the `load` functions that each one exports.
```
Promise.all(
Array.from({ length: 10 }).map((\_, index) =>
import(`/modules/module-${index}.js`)
)
).then((modules) => modules.forEach((module) => module.load()));
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-import-calls](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-import-calls) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `import` | 63 | 79 | 67 | No | 50 | 11.1 | 63 | 63 | 67 | 46 | 11.3 | 8.0 | 1.0
Bundled Deno applications (using `deno compile`) do not support dynamic imports | 13.2.0
Dynamic `import` can be used in either CommonJS or ES module files, to import either CommonJS or ES module files. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_import_expressions) for more details.
12.0.0
Dynamic `import` can be used in either CommonJS or ES module files, to import either CommonJS or ES module files. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_import_expressions) for more details. |
| `options_parameter` | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | No | 15 | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | 15 | 16.0 | 1.17 | 17.5.0
17.0.0-17.5.0
16.15.0-17.0.0
16.14.0-16.15.0
The second parameter no longer throws a parser error, but the `--experimental-json-modules` flag is still needed to load JSON modules.
16.0.0-16.14.0 |
See also
--------
* [`import` declaration](../statements/import)
| programming_docs |
javascript Bitwise OR (|) Bitwise OR (|)
==============
The `|` operator returns a `1` in each bit position for which the corresponding bits of either or both operands are `1`s.
Try it
------
Syntax
------
```
a | b
```
Description
-----------
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes 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:
```
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
Each bit in the first operand is paired with the corresponding bit in the second operand: *first bit* to *first bit*, *second bit* to *second bit*, and so on.
The operator is applied to each pair of bits, and the result is constructed bitwise.
The truth table for the OR operation is:
| a | b | a OR b |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
```
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
```
Bitwise ORing any number `x` with `0` yields `x` converted to a 32-bit integer.
Examples
--------
### Using bitwise OR
```
// 9 (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)
14 | 9;
// 15 (00000000000000000000000000001111)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-BitwiseORExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-BitwiseORExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_OR` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Bitwise OR assignment operator](bitwise_or_assignment)
javascript Assignment (=) Assignment (=)
==============
The `=` operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Try it
------
Syntax
------
```
x = y
```
Examples
--------
### Simple assignment and chaining
```
let x = 5;
let y = 10;
let z = 25;
x = y; // x is 10
x = y = z; // x, y and z are all 25
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Destructuring assignment](destructuring_assignment)
javascript Logical NOT (!) Logical NOT (!)
===============
The `!` (logical complement, negation) operator takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns `false` if its single operand can be converted to `true`; otherwise, returns `true`.
Try it
------
Syntax
------
```
!expr
```
Description
-----------
Returns `false` if its single operand can be converted to `true`; otherwise, returns `true`.
If a value can be converted to `true`, the value is so-called [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). If a value can be converted to `false`, the value is so-called [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
Examples of expressions that can be converted to false are:
* `null`;
* `NaN`;
* `0`;
* empty string (`""` or `''` or ````);
* `undefined`.
Even though the `!` operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a [boolean primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type). To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator (`!!`) or the [`Boolean`](../global_objects/boolean/boolean) constructor.
Examples
--------
### Using NOT
The following code shows examples of the `!` (logical NOT) operator.
```
n1 = !true // !t returns false
n2 = !false // !f returns true
n3 = !'' // !f returns true
n4 = !'Cat' // !t returns false
```
### Double NOT (`!!`)
It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding [boolean primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type). The conversion is based on the "truthyness" or "falsyness" of the value (see [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)).
The same conversion can be done through the [`Boolean`](../global_objects/boolean/boolean) function.
```
n1 = !!true // !!truthy returns true
n2 = !!{} // !!truthy returns true: any object is truthy...
n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()!
n4 = !!false // !!falsy returns false
n5 = !!"" // !!falsy returns false
n6 = !!Boolean(false) // !!falsy returns false
```
### Converting between NOTs
The following operation involving **booleans**:
```
!!bCondition
```
is always equal to:
```
bCondition
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-logical-not-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-logical-not-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Logical_NOT` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Boolean`](../global_objects/boolean)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
javascript Logical AND assignment (&&=) Logical AND assignment (&&=)
============================
The `x &&= y` operator only assigns if `x` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
Try it
------
Syntax
------
```
expr1 &&= expr2
```
Description
-----------
Logical AND assignment [*short-circuits*](operator_precedence#short-circuiting), meaning that `x &&= y` is equivalent to:
```
x && (x = y);
```
No assignment is performed if the left-hand side is not truthy, due to short-circuiting of the [logical AND](logical_and) operator. For example, the following does not throw an error, despite `x` being `const`:
```
const x = 0;
x &&= 2;
```
Neither would the following trigger the setter:
```
const x = {
get value() {
return 0;
},
set value(v) {
console.log("Setter called");
},
};
x.value &&= 2;
```
In fact, if `x` is not truthy, `y` is not evaluated at all.
```
const x = 0;
x &&= console.log("y evaluated");
// Logs nothing
```
Examples
--------
### Using logical AND assignment
```
let x = 0;
let y = 1;
x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Logical_AND_assignment` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [Logical AND (&&)](logical_and)
* [The nullish coalescing operator (`??`)](nullish_coalescing)
* [Bitwise AND assignment (`&=`)](bitwise_and_assignment)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
javascript import.meta import.meta
===========
The `import.meta` meta-property exposes context-specific metadata to a JavaScript module. It contains information about the module, such as the module's URL.
Syntax
------
```
import.meta
```
### Value
The `import.meta` object is created by the host environment, as an extensible [`null`-prototype](../global_objects/object#null-prototype_objects) object where all properties are writable, configurable, and enumerable. The spec doesn't specify any properties to be defined on it, but hosts usually implement the following property:
`url` The full URL to the module, includes query parameters and/or hash (following the `?` or `#`). In browsers, this is either the URL from which the script was obtained (for external scripts), or the URL of the containing document (for inline scripts). In Node.js, this is the file path (including the `file://` protocol).
Description
-----------
The `import.meta` syntax consists of the keyword `import`, a dot, and the identifier `meta`. Because `import` is a [reserved word](../lexical_grammar#reserved_words), not an identifier, this is not a [property accessor](property_accessors), but a special expression syntax.
The `import.meta` meta-property is available in JavaScript modules; using `import.meta` outside of a module (including [direct `eval()`](../global_objects/eval#direct_and_indirect_eval) within a module) is a syntax error.
Examples
--------
### Passing query parameters
Using query parameters in the `import` specifier allows module-specific argument passing, which may be complementary to reading parameters from the application-wide [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) (or on Node.js, through `process.argv`). For example, with the following HTML:
```
<script type="module">
import "./index.mjs?someURLInfo=5";
</script>
```
The `index.mjs` module is able to retrieve the `someURLInfo` parameter through `import.meta`:
```
// index.mjs
new URL(import.meta.url).searchParams.get("someURLInfo"); // 5
```
The same applies when a module imports another:
```
// index.mjs
import "./index2.mjs?someURLInfo=5";
// index2.mjs
new URL(import.meta.url).searchParams.get("someURLInfo"); // 5
```
The ES module implementation in Node.js supports resolving module specifiers containing query parameters (or the hash), as in the latter example. However, you cannot use queries or hashes when the module is specified through the CLI command (like `node index.mjs?someURLInfo=5`), because the CLI entrypoint uses a more CommonJS-like resolution mode, treating the path as a file path rather than a URL. To pass parameters to the entrypoint module, use CLI arguments and read them through `process.argv` instead (like `node index.mjs --someURLInfo=5`).
### Getting current module's file path
In Node.js CommonJS modules, there's a `__dirname` variable that contains the absolute path to the folder containing current module, which is useful for resolving relative paths. However, ES modules cannot have contextual variables except for `import.meta`. Therefore, to get the current module's file path, you can use `import.meta.url`.
Before (CommonJS):
```
const fs = require("fs/promises");
const path = require("path");
const filePath = path.join(__dirname, "someFile.txt");
fs.readFile(filePath, "utf8").then(console.log);
```
After (ES modules):
```
import fs from "node:fs/promises";
import { fileURLToPath } from "node:url";
const filePath = fileURLToPath(new URL('./someFile.txt', import.meta.url));
fs.readFile(filePath, "utf8").then(console.log);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-ImportMeta](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-ImportMeta) |
| [HTML Standard # hostgetimportmetaproperties](https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `import.meta` | 64 | 79 | 62 | No | 51 | 11.1 | 64 | 64 | 62 | 47 | 12 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`import`](../statements/import)
* [`export`](../statements/export)
javascript Left shift (<<) Left shift (<<)
===============
The `<<` operator shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
Try it
------
Syntax
------
```
a << b
```
Description
-----------
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.
For example, `9 << 2` yields 36:
```
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
```
Bitwise shifting any number `x` to the left by `y` bits yields `x * 2 ** y`. So e.g.: `9 << 3` translates to: `9 * (2 ** 3) = 9 * (8) = 72`.
The left operand will be converted to a 32-bit integer, which means floating point numbers will be truncated, and number not within the 32-bit bounds will over-/underflow.
The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, `100 << 32` is the same as `100 << 0` (and produces `100`) because 32 modulo 32 is 0.
Examples
--------
### Using left shift
```
9 << 3; // 72
// 9 \* (2 \*\* 3) = 9 \* (8) = 72
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-left-shift-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-left-shift-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Left_shift` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Left shift assignment operator](left_shift_assignment)
javascript Less than or equal (<=) Less than or equal (<=)
=======================
The `<=` operator returns `true` if the left operand is less than or equal to the right operand, and `false` otherwise.
Try it
------
Syntax
------
```
x <= y
```
Description
-----------
The operands are compared using the same algorithm as the [Less than](less_than) operator, except that equal values (after attempting coercion) return `true`.
Examples
--------
### String to string comparison
```
console.log("a" <= "b"); // true
console.log("a" <= "a"); // true
console.log("a" <= "3"); // false
```
### String to number comparison
```
console.log("5" <= 3); // false
console.log("3" <= 3); // true
console.log("3" <= 5); // true
console.log("hello" <= 5); // false
console.log(5 <= "hello"); // false
```
### Number to Number comparison
```
console.log(5 <= 3); // false
console.log(3 <= 3); // true
console.log(3 <= 5); // true
```
### Number to BigInt comparison
```
console.log(5n <= 3); // false
console.log(3 <= 3n); // true
console.log(3 <= 5n); // true
```
### Comparing Boolean, null, undefined, NaN
```
console.log(true <= false); // false
console.log(true <= true); // true
console.log(false <= true); // true
console.log(true <= 0); // false
console.log(true <= 1); // true
console.log(null <= 0); // true
console.log(1 <= null); // false
console.log(undefined <= 3); // false
console.log(3 <= undefined); // false
console.log(3 <= NaN); // false
console.log(NaN <= 3); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Less_than_or_equal` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Greater than operator](greater_than)
* [Greater than or equal operator](greater_than_or_equal)
* [Less than operator](less_than)
javascript async function* expression async function\* expression
===========================
The `async function*` keywords can be used to define an asynchronous generator function inside an expression.
Try it
------
Syntax
------
```
async function\* (param0) {
statements
}
async function\* (param0, param1) {
statements
}
async function\* (param0, param1, /\* … ,\*/ paramN) {
statements
}
async function\* name(param0) {
statements
}
async function\* name(param0, param1) {
statements
}
async function\* name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
### Parameters
`name` Optional
The function name. Can be omitted, in which case the function is *anonymous*. The name is only local to the function body.
`paramN` Optional
The name of an argument to be passed to the function. A function can have up to 255 arguments.
`statements` Optional
The statements which comprise the body of the function.
Description
-----------
An `async function*` expression is very similar to and has almost the same syntax as a [async function\* statement](../statements/async_function*). The main difference between an `async function*` expression and an `async function*` statement is the *function name*, which can be omitted in `async function*` expressions to create *anonymous* asynchronous generator functions. See also the chapter about [`functions`](../functions) for more information.
Examples
--------
### Using async function\*
The following example defines an unnamed asynchronous generator function and assigns it to `x`. The function yields the square of its argument:
```
const x = async function\* (y) {
yield Promise.resolve(y \* y);
};
x(6)
.next()
.then((res) => console.log(res.value)); // 36
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-generator-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-generator-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `async_function*` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*`](../statements/async_function*) statement
* [`AsyncGeneratorFunction`](../global_objects/asyncgeneratorfunction) object
* [The Iterator protocol](../iteration_protocols)
* [`GeneratorFunction`](../global_objects/generatorfunction) object
* [`yield`](yield)
* [`yield*`](yield*)
* [`Function`](../global_objects/function) object
* [Functions](../functions)
| programming_docs |
javascript Greater than (>) Greater than (>)
================
The `>` operator returns `true` if the left operand is greater than the right operand, and `false` otherwise.
Try it
------
Syntax
------
```
x > y
```
Description
-----------
The operands are compared using the same algorithm as the [Less than](less_than) operator, except the two operands are swapped.
Examples
--------
### String to string comparison
```
console.log("a" > "b"); // false
console.log("a" > "a"); // false
console.log("a" > "3"); // true
```
### String to number comparison
```
console.log("5" > 3); // true
console.log("3" > 3); // false
console.log("3" > 5); // false
console.log("hello" > 5); // false
console.log(5 > "hello"); // false
console.log("5" > 3n); // true
console.log("3" > 5n); // false
```
### Number to Number comparison
```
console.log(5 > 3); // true
console.log(3 > 3); // false
console.log(3 > 5); // false
```
### Number to BigInt comparison
```
console.log(5n > 3); // true
console.log(3 > 5n); // false
```
### Comparing Boolean, null, undefined, NaN
```
console.log(true > false); // true
console.log(false > true); // false
console.log(true > 0); // true
console.log(true > 1); // false
console.log(null > 0); // false
console.log(1 > null); // true
console.log(undefined > 3); // false
console.log(3 > undefined); // false
console.log(3 > NaN); // false
console.log(NaN > 3); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Greater_than` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Greater than or equal operator](greater_than_or_equal)
* [Less than operator](less_than)
* [Less than or equal operator](less_than_or_equal)
javascript Right shift assignment (>>=) Right shift assignment (>>=)
============================
The `>>=` operator moves the specified amount of bits to the right and assigns the result to the variable.
Try it
------
Syntax
------
```
x >>= y // x = x >> y
```
Examples
--------
### Using right shift assignment
```
let a = 5; // (00000000000000000000000000000101)
a >>= 2; // 1 (00000000000000000000000000000001)
let b = -5; // (-00000000000000000000000000000101)
b >>= 2; // -2 (-00000000000000000000000000000010)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Right_shift_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Right shift operator](right_shift)
javascript Unsigned right shift (>>>) Unsigned right shift (>>>)
==========================
The `>>>` (zero-fill right shift) operator evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. The sign bit becomes `0`, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
Try it
------
Syntax
------
```
a >>> b
```
Description
-----------
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. The sign bit becomes `0`, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
Consider the 32-bit binary representations of the decimal (base 10) numbers `9` and `-9`:
```
9 (base 10): 00000000000000000000000000001001 (base 2)
-9 (base 10): 11111111111111111111111111110111 (base 2)
```
Notice that the binary representation of the negative decimal (base 10) number `-9` is the [two's complement](https://en.wikipedia.org/wiki/Two's_complement) of the binary representation of the positive decimal (base 10) number `9`. That is, it's calculated by inverting all the bits of `00000000000000000000000000001001` and adding `1`.
In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number `9`, the leftmost bit of the binary representation is `0`, and for the negative decimal number `-9`, the leftmost bit of the binary representation is `1`.
Given those binary representations of the decimal (base 10) numbers `9`, and `-9`:
For the positive number `9`, zero-fill right shift and [sign-propagating right shift](right_shift) yield the same result: `9 >>> 2` yields `2`, the same as `9 >> 2`:
```
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```
Notice how two rightmost bits, `01`, have been shifted off, and two zeroes have been shifted in from the left.
However, notice what happens for `-9`: `-9 >> 2` ([sign-propagating right shift](right_shift)) yields `-3`, but `-9 >>> 2` (zero-fill right shift) yields 1073741821:
```
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
```
Notice how two rightmost bits, `11`, have been shifted off. For `-9 >> 2` ([sign-propagating right shift](right_shift)), two copies of the leftmost `1` bit have been shifted in from the left, which preserves the negative sign. On the other hand, for `-9 >>> 2` (zero-fill right shift), zeroes have instead been shifted in from the left, so the negative sign of the number is not preserved, and the result is instead a (large) positive number.
The left operand will be converted to an unsigned 32-bit integer, which means floating point numbers will be truncated, and number not within the 32-bit bounds will over-/underflow.
The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, `100 >>> 32` is the same as `100 >>> 0` (and produces `100`) because 32 modulo 32 is 0.
Examples
--------
### Using unsigned right shift
```
9 >>> 2; // 2
-9 >>> 2; // 1073741821
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-unsigned-right-shift-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-unsigned-right-shift-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Unsigned_right_shift` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Unsigned right shift assignment operator](unsigned_right_shift_assignment)
javascript Greater than or equal (>=) Greater than or equal (>=)
==========================
The `>=` operator returns `true` if the left operand is greater than or equal to the right operand, and `false` otherwise.
Try it
------
Syntax
------
```
x >= y
```
Description
-----------
The operands are compared using the same algorithm as the [Less than](less_than) operator, except the two operands are swapped, and equal values (after attempting coercion) return `true`.
Examples
--------
### String to string comparison
```
console.log("a" >= "b"); // false
console.log("a" >= "a"); // true
console.log("a" >= "3"); // true
```
### String to number comparison
```
console.log("5" >= 3); // true
console.log("3" >= 3); // true
console.log("3" >= 5); // false
console.log("hello" >= 5); // false
console.log(5 >= "hello"); // false
```
### Number to Number comparison
```
console.log(5 >= 3); // true
console.log(3 >= 3); // true
console.log(3 >= 5); // false
```
### Number to BigInt comparison
```
console.log(5n >= 3); // true
console.log(3 >= 3n); // true
console.log(3 >= 5n); // false
```
### Comparing Boolean, null, undefined, NaN
```
console.log(true >= false); // true
console.log(true >= true); // true
console.log(false >= true); // false
console.log(true >= 0); // true
console.log(true >= 1); // true
console.log(null >= 0); // true
console.log(1 >= null); // true
console.log(undefined >= 3); // false
console.log(3 >= undefined); // false
console.log(3 >= NaN); // false
console.log(NaN >= 3); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-relational-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-relational-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Greater_than_or_equal` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Greater than operator](greater_than)
* [Less than operator](less_than)
* [Less than or equal operator](less_than_or_equal)
javascript Bitwise XOR assignment (^=) Bitwise XOR assignment (^=)
===========================
The `^=` operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable.
Try it
------
Syntax
------
```
x ^= y // x = x ^ y
```
Examples
--------
### Using bitwise XOR assignment
```
let a = 5; // 00000000000000000000000000000101
a ^= 3; // 00000000000000000000000000000011
console.log(a); // 00000000000000000000000000000110
// 6
let b = 5; // 00000000000000000000000000000101
b ^= 0; // 00000000000000000000000000000000
console.log(b); // 00000000000000000000000000000101
// 5
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Bitwise_XOR_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Bitwise XOR operator](bitwise_xor)
javascript Spread syntax (...) Spread syntax (...)
===================
The `...` syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. See [rest parameters](../functions/rest_parameters) and [rest property](destructuring_assignment#rest_property).
Try it
------
Syntax
------
```
myFunction(a, ...iterableObj, b)
[1, ...iterableObj, '4', 'five', 6]
{ ...obj, key: 'value' }
```
Description
-----------
Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:
* [Function arguments](#spread_in_function_calls) list (`myFunction(a, ...iterableObj, b)`)
* [Array literals](#spread_in_array_literals) (`[1, ...iterableObj, '4', 'five', 6]`)
* [Object literals](#spread_in_object_literals) (`{ ...obj, key: 'value' }`)
Although the syntax looks the same, they come with slightly different semantics.
Only [iterable](../iteration_protocols) objects, like [`Array`](../global_objects/array), can be spread in array and function parameters. Many objects are not iterable, including all [plain objects](../global_objects/object) that lack a [`Symbol.iterator`](../global_objects/symbol/iterator) method:
```
const obj = { key1: 'value1' };
const array = [...obj]; // TypeError: obj is not iterable
```
On the other hand, spreading in object literals [enumerates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties#traversing_object_properties) the own properties of the object. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.
```
const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }
```
When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See [`Function.prototype.apply()`](../global_objects/function/apply) for more details.
Examples
--------
### Spread in function calls
#### Replace apply()
It is common to use [`Function.prototype.apply()`](../global_objects/function/apply) in cases where you want to use the elements of an array as arguments to a function.
```
function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction.apply(null, args);
```
With spread syntax the above can be written as:
```
function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction(...args);
```
Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times.
```
function myFunction(v, w, x, y, z) {}
const args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
```
#### Apply for new operator
When calling a constructor with [`new`](new), it's not possible to **directly** use an array and `apply()`, because `apply()` *calls* the target function instead of *constructing* it, which means, among other things, that [`new.target`](new.target) will be `undefined`. However, an array can be easily used with `new` thanks to spread syntax:
```
const dateFields = [1970, 0, 1]; // 1 Jan 1970
const d = new Date(...dateFields);
```
### Spread in array literals
#### A more powerful array literal
Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of [`push()`](../global_objects/array/push), [`splice()`](../global_objects/array/splice), [`concat()`](../global_objects/array/concat), etc. With spread syntax this becomes much more succinct:
```
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
```
Just like spread for argument lists, `...` can be used anywhere in the array literal, and may be used more than once.
#### Copy an array
```
const arr = [1, 2, 3];
const arr2 = [...arr]; // like arr.slice()
arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
```
**Note:** Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with [`Object.assign()`](../global_objects/object/assign) — no native operation in JavaScript does a deep clone. The web API method [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) allows deep copying values of certain [supported types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types).
```
const a = [[1], [2], [3]];
const b = [...a];
b.shift().shift();
// 1
// Oh no! Now array 'a' is affected as well:
console.log(a);
// [[], [2], [3]]
```
#### A better way to concatenate arrays
[`Array.prototype.concat()`](../global_objects/array/concat) is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as:
```
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);
```
With spread syntax this becomes:
```
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
// arr1 is now [0, 1, 2, 3, 4, 5]
```
[`Array.prototype.unshift()`](../global_objects/array/unshift) is often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as:
```
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
// Prepend all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2);
console.log(arr1); // [3, 4, 5, 0, 1, 2]
```
With spread syntax, this becomes:
```
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1 = [...arr2, ...arr1];
console.log(arr1); // [3, 4, 5, 0, 1, 2]
```
**Note:** Unlike `unshift()`, this creates a new `arr1`, instead of modifying the original `arr1` array in-place.
### Spread in object literals
Shallow-cloning (excluding prototype) or merging of objects is possible using a shorter syntax than [`Object.assign()`](../global_objects/object/assign).
```
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 }
```
Note that [`Object.assign()`](../global_objects/object/assign) can be used to mutate an object, whereas spread syntax can't.
```
const obj1 = { foo: 'bar', x: 42 };
Object.assign(obj1, { x: 1337 });
console.log(obj1); // { foo: "bar", x: 1337 }
```
In addition, [`Object.assign()`](../global_objects/object/assign) triggers setters on the target object, whereas spread syntax does not.
```
const objectAssign = Object.assign({ set foo(val) { console.log(val); } }, { foo: 1 });
// Logs "1"; objectAssign.foo is still the original setter
const spread = { set foo(val) { console.log(val); }, ...{ foo: 1 } };
// Nothing is logged; spread.foo is 1
```
You cannot naively re-implement the [`Object.assign()`](../global_objects/object/assign) function through a single spreading:
```
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const merge = (...objects) => ({ ...objects });
const mergedObj1 = merge(obj1, obj2);
// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
const mergedObj2 = merge({}, obj1, obj2);
// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
```
In the above example, the spread syntax does not work as one might expect: it spreads an *array* of arguments into the object literal, due to the rest parameter. Here is an implementation of `merge` using the spread syntax, whose behavior is similar to [`Object.assign()`](../global_objects/object/assign), except that it doesn't trigger setters, nor mutates any object:
```
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const merge = (...objects) => objects.reduce((acc, cur) => ({ ...acc, ...cur }));
const mergedObj1 = merge(obj1, obj2);
// { foo: 'baz', x: 42, y: 13 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-SpreadElement](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-SpreadElement) |
| [ECMAScript Language Specification # prod-ArgumentList](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-ArgumentList) |
| [ECMAScript Language Specification # prod-PropertyDefinition](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-PropertyDefinition) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Spread_syntax` | 46 | 12 | 16 | No | 37 | 8 | 46 | 46 | 16 | 37 | 8 | 5.0 | 1.0 | 5.0.0
4.0.0 |
| `spread_in_arrays` | 46 | 12 | 16 | No | 37 | 8 | 46 | 46 | 16 | 37 | 8 | 5.0 | 1.0 | 5.0.0
4.0.0 |
| `spread_in_function_calls` | 46 | 12 | 27 | No | 37 | 8 | 46 | 46 | 27 | 37 | 8 | 5.0 | ? | 5.0.0
4.0.0 |
| `spread_in_object_literals` | 60 | 79 | 55 | No | 47 | 11.1 | 60 | 60 | 55 | 44 | 11.3 | 8.2 | ? | 8.3.0
8.0.0 |
See also
--------
* [Rest parameters](../functions/rest_parameters)
* [Rest property](destructuring_assignment#rest_property)
* [`Function.prototype.apply()`](../global_objects/function/apply)
| programming_docs |
javascript Right shift (>>) Right shift (>>)
================
The `>>` operator returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a [two's complement](https://en.wikipedia.org/wiki/Two's_complement) bit string) to the right by the number of bits, modulo 32, specified in the second operand. Excess bits shifted off to the right are discarded, and copies of the leftmost bit are shifted in from the left.
The resulting binary representation is evaluated as a [two's complement](https://en.wikipedia.org/wiki/Two's_complement) bit string. So if the leftmost bit in the resulting binary representation is `1`, the resulting number is negative. Because the leftmost bit (the sign bit) of the result will always have the same value as the leftmost bit of the first operand, the sign of the resulting number is the same as the sign of the first operand, hence the name "sign-extending right shift" or "sign-filling right shift". This operation is also commonly referred to as an "arithmetic right shift".
Try it
------
Syntax
------
```
a >> b
```
Description
-----------
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. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
Consider the 32-bit binary representations of the decimal (base 10) numbers `9` and `-9`:
```
9 (base 10): 00000000000000000000000000001001 (base 2)
-9 (base 10): 11111111111111111111111111110111 (base 2)
```
Notice that the binary representation of the negative decimal (base 10) number `-9` is the [two's complement](https://en.wikipedia.org/wiki/Two's_complement) of the binary representation of the positive decimal (base 10) number `9`. That is, it's calculated by inverting all the bits of `00000000000000000000000000001001` and adding `1`.
In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number `9`, the leftmost bit of the binary representation is `0`, and for the negative decimal number `-9`, the leftmost bit of the binary representation is `1`.
Given those binary representations of the decimal (base 10) numbers `9`, and `-9`:
`9 >> 2` yields 2:
```
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```
Notice how two rightmost bits, `01`, have been shifted off, and two copies of the leftmost bit, `0` have been shifted in from the left.
`-9 >> 2` yields `-3`:
```
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
```
Notice how two rightmost bits, `11`, have been shifted off. But as far as the leftmost bits: in this case, the leftmost bit is `1`. So two copies of that leftmost `1` bit have been shifted in from the left — which preserves the negative sign.
The binary representation `11111111111111111111111111111101` is equal to the negative decimal (base 10) number `-3`, because all negative integers are stored as [two's complements](https://en.wikipedia.org/wiki/Two's_complement), and this one can be calculated by inverting all the bits of the binary representation of the positive decimal (base 10) number `3`, which is `00000000000000000000000000000011`, and then adding one.
The left operand will be converted to a 32-bit integer, which means floating point numbers will be truncated, and number not within the 32-bit bounds will over-/underflow.
The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, `100 >> 32` is the same as `100 >> 0` (and produces `100`) because 32 modulo 32 is 0.
Examples
--------
### Using right shift
```
9 >> 2; // 2
-9 >> 2; // -3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-signed-right-shift-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-signed-right-shift-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Right_shift` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators)
* [Right shift assignment operator](right_shift_assignment)
* [Unsigned right shift operator](unsigned_right_shift)
javascript Nullish coalescing operator (??) Nullish coalescing operator (??)
================================
The `??` operator is a logical operator that returns its right-hand side operand when its left-hand side operand is [`null`](null) or [`undefined`](../global_objects/undefined), and otherwise returns its left-hand side operand.
Try it
------
Syntax
------
```
leftExpr ?? rightExpr
```
Description
-----------
The nullish coalescing operator can be seen as a special case of the [logical OR (`||`) operator](logical_or). The latter returns the right-hand side operand if the left operand is *any* [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value, not only `null` or `undefined`. In other words, if you use `||` to provide some default value to another variable `foo`, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., `''` or `0`). See [below](#assigning_a_default_value_to_a_variable) for more examples.
The nullish coalescing operator has the fifth-lowest [operator precedence](operator_precedence), directly lower than `||` and directly higher than the [conditional (ternary) operator](conditional_operator).
It is not possible to combine both the AND (`&&`) and OR operators (`||`) directly with `??`. A [syntax error](../errors/cant_use_nullish_coalescing_unparenthesized) will be thrown in such cases.
```
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
```
Instead, provide parenthesis to explicitly indicate precedence:
```
(null || undefined) ?? "foo"; // returns "foo"
```
Examples
--------
### Using the nullish coalescing operator
In this example, we will provide default values but keep values other than `null` or `undefined`.
```
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
```
### Assigning a default value to a variable
Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator ([`||`](logical_or)):
```
let foo;
// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";
```
However, due to `||` being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any *falsy* value (including `0`, `''`, `NaN`, `false`, etc.) was not returned. This behavior may cause unexpected consequences if you consider `0`, `''`, or `NaN` as valid values.
```
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
```
The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either `null` or `undefined` (but no other falsy values):
```
const myText = ""; // An empty string (which is also a falsy value)
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
```
### Short-circuiting
Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither `null` nor `undefined`.
```
function A() {
console.log("A was called");
return undefined;
}
function B() {
console.log("B was called");
return false;
}
function C() {
console.log("C was called");
return "foo";
}
console.log(A() ?? C());
// Logs "A was called" then "C was called" and then "foo"
// as A() returned undefined so both expressions are evaluated
console.log(B() ?? C());
// Logs "B was called" then "false"
// as B() returned false (and not null or undefined), the right
// hand side expression was not evaluated
```
### Relationship with the optional chaining operator (?.)
The nullish coalescing operator treats `undefined` and `null` as specific values. So does the [optional chaining operator (`?.`)](optional_chaining), which is useful to access a property of an object which may be `null` or `undefined`. Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.
```
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-CoalesceExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-CoalesceExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Nullish_coalescing` | 80 | 80 | 72 | No | 67 | 13.1 | 80 | 80 | 79 | 57 | 13.4 | 13.0 | 1.0 | 14.0.0 |
See also
--------
* The [nullish coalescing assignment (`??=`) operator](nullish_coalescing_assignment)
* The [optional chaining (`?.`) operator](optional_chaining)
* The [logical OR (`||`) operator](logical_or)
* [Default parameters in functions](../functions/default_parameters)
javascript Grouping operator ( ) Grouping operator ( )
=====================
The `( )` operator controls the precedence of evaluation in expressions. It also acts as a container for arbitrary expressions in certain syntactic constructs, where ambiguity or syntax errors would otherwise occur.
Try it
------
Syntax
------
```
(expression)
```
### Parameters
`expression` Any [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) to be evaluated, including [comma-joined](comma_operator) expressions.
Description
-----------
The grouping operator consists of a pair of parentheses around an expression that groups the contents. The operator overrides the normal [operator precedence](operator_precedence), so that operators with lower precedence (as low as the [comma](comma_operator) operator) can be evaluated before an operator with higher precedence.
Examples
--------
### Using the grouping operator
Evaluating addition and subtraction before multiplication and division.
```
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
```
Notice in these examples that the order in which the *operators* evaluate has changed, but the order in which the *operands* evaluate has not. For example, in this code, the function invocations `a()`, `b()`, and `c()` are evaluated left-to-right (the normal order of evaluation) before the operator order is considered.
```
a() \* (b() + c());
```
The function `a` will be called before the function `b`, which will be called before the function `c`. For more on operator precedence, see its [reference page](operator_precedence).
### Using the grouping operator to eliminate parsing ambiguity
An [expression statement](../statements/expression_statement) cannot start with the keyword `function`, because the parser would see it as the start of a [function declaration](../statements/function). This means the following [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) syntax is invalid:
```
function () {
// code
}();
```
The grouping operator can be used to eliminate this ambiguity, since when the parser sees the left parenthesis, it knows that what follows must be an expression instead of a declaration.
```
(function () {
// code
})();
```
You may also use the [`void`](void#immediately_invoked_function_expressions) operator to eliminate ambiguity.
In an [arrow function](../functions/arrow_functions) concise body (one that directly returns an expression without the keyword `return`), the grouping operator can be used to return an object literal expression, because otherwise the left curly brace would be interpreted as the start of the function body.
```
const f = () => ({ a: 1 });
```
If a property is accessed on a number literal, the [property accessor](property_accessors) dot `.` may be ambiguous with a decimal point, unless the number already has a decimal point. You can wrap integer literals in parentheses to eliminate this ambiguity.
```
(1).toString(); // "1"
```
### Grouping operator and automatic semicolon insertion
The grouping operator can mitigate [automatic semicolon insertion](../lexical_grammar#automatic_semicolon_insertion) (ASI) pitfalls. For example, the `return` keyword and the returned expression cannot have a line break in between:
```
function sum(a, b) {
return
a + b;
}
```
This code will return `undefined`, because a semicolon is inserted directly after the `return` keyword, which causes the function to return immediately without evaluating `a + b`. In case the returned expression is long and you want to keep it well-formatted, you may use the grouping operator to signify that the `return` keyword is followed by an expression and prevent semicolon insertion:
```
function sum(a, b) {
return (
a + b
);
}
```
However, grouping may also *introduce* ASI hazards. When a line starts with a left parenthesis and the previous line ends with an expression, the parser will not insert a semicolon before the line break, because it could be the middle of a function call. For example:
```
const a = 1
(1).toString()
```
This code would be parsed as:
```
const a = 1(1).toString();
```
Which throws "TypeError: 1 is not a function". If your coding style does not use semicolons, remember that when a line starts with a left parenthesis, *prefix* it with a semicolon. This practice is recommended by several formatters and/or style guides, including [Prettier](https://prettier.io/docs/en/rationale.html#semicolons) and [standard](https://standardjs.com/rules.html#semicolons).
```
const a = 1
;(1).toString()
```
For more advice on working with ASI, see its [reference section](../lexical_grammar#automatic_semicolon_insertion).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-grouping-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-grouping-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Grouping` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Operator precedence](operator_precedence)
* [`delete`](delete)
* [`typeof`](typeof)
javascript Inequality (!=) Inequality (!=)
===============
The `!=` operator checks whether its two operands are not equal, returning a Boolean result. Unlike the [strict inequality](strict_inequality) operator, it attempts to convert and compare operands that are of different types.
Try it
------
Syntax
------
```
x != y
```
Description
-----------
The inequality operator checks whether its operands are not equal. It is the negation of the <equality> operator so the following two lines will always give the same result:
```
x != y;
!(x == y);
```
For details of the comparison algorithm, see the page for the <equality> operator.
Like the equality operator, the inequality operator will attempt to convert and compare operands of different types:
```
3 != "3"; // false
```
To prevent this, and require that different types are considered to be different, use the [strict inequality](strict_inequality) operator instead:
```
3 !== "3"; // true
```
Examples
--------
### Comparison with no type conversion
```
1 != 2; // true
"hello" != "hola"; // true
1 != 1; // false
"hello" != "hello"; // false
```
### Comparison with type conversion
```
"1" != 1; // false
1 != "1"; // false
0 != false; // false
0 != null; // true
0 != undefined; // true
0 != !!null; // false, look at Logical NOT operator
0 != !!undefined; // false, look at Logical NOT operator
null != undefined; // false
const number1 = new Number(3);
const number2 = new Number(3);
number1 != 3; // false
number1 != number2; // true
```
### Comparison of objects
```
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 != object2); // true
console.log(object1 != object1); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-equality-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-equality-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Inequality` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Equality operator](equality)
* [Strict equality operator](strict_equality)
* [Strict inequality operator](strict_inequality)
javascript Logical OR assignment (||=) Logical OR assignment (||=)
===========================
The `x ||= y` operator only assigns if `x` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
Try it
------
Syntax
------
```
expr1 ||= expr2
```
Description
-----------
Logical OR assignment [*short-circuits*](operator_precedence#short-circuiting), meaning that `x ||= y` is equivalent to:
```
x || (x = y);
```
No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the [logical OR](logical_or) operator. For example, the following does not throw an error, despite `x` being `const`:
```
const x = 1;
x ||= 2;
```
Neither would the following trigger the setter:
```
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ||= 2;
```
In fact, if `x` is truthy, `y` is not evaluated at all.
```
const x = 1;
x ||= console.log("y evaluated");
// Logs nothing
```
Examples
--------
### Setting default content
If the "lyrics" element is empty, display a default value:
```
document.getElementById("lyrics").textContent ||= "No lyrics.";
```
Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.
Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value), `||=` must be used, so that "No lyrics." is displayed instead of a blank space. However, if the API returns [`null`](null) or [`undefined`](../global_objects/undefined) in case of blank content, [`??=`](nullish_coalescing_assignment) should be used instead.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Logical_OR_assignment` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
See also
--------
* [Logical OR (||)](logical_or)
* [The nullish coalescing operator (`??`)](nullish_coalescing)
* [Bitwise OR assignment (`|=`)](bitwise_or_assignment)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
| programming_docs |
javascript Exponentiation (**) Exponentiation (\*\*)
=====================
The `**` operator returns the result of raising the first operand to the power of the second operand. It is equivalent to [`Math.pow()`](../global_objects/math/pow), except it also accepts [BigInts](../global_objects/bigint) as operands.
Try it
------
Syntax
------
```
x \*\* y
```
Description
-----------
The exponentiation operator is right-associative: `a ** b ** c` is equal to `a ** (b ** c)`.
In most languages, such as PHP, Python, and others that have an exponentiation operator (`**`), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary `+` and unary `-`, but there are a few exceptions. For example, in Bash, the `**` operator is defined to have a lower precedence than unary operators.
In JavaScript, it is impossible to write an ambiguous exponentiation expression. That is, you cannot put a unary operator (`+/-/~/!/delete/void/typeof`) immediately before the base number; [doing so will cause a SyntaxError](../errors/unparenthesized_unary_expr_lhs_exponentiation).
For example, `-2 ** 2` is 4 in Bash, but is -4 in other languages (such as Python). This is invalid in JavaScript, as the operation is ambiguous. You have to parenthesize either side — for example, as `-(2 ** 2)` — to make the intention unambiguous.
Note that some programming languages use the caret symbol `^` for exponentiation, but JavaScript uses that symbol for the [bitwise logical XOR operator](bitwise_xor).
`NaN ** 0` (and the equivalent `Math.pow(NaN, 0)`) is the only case where [`NaN`](../global_objects/nan) doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior.
Examples
--------
### Basic exponentiation
```
2 \*\* 3 // 8
3 \*\* 2 // 9
3 \*\* 2.5 // 15.588457268119896
10 \*\* -1 // 0.1
NaN \*\* 2 // NaN
NaN \*\* 0 // 1
1 \*\* Infinity // NaN
```
### Associativity
```
2 \*\* 3 \*\* 2 // 512
2 \*\* (3 \*\* 2) // 512
(2 \*\* 3) \*\* 2 // 64
```
### Usage with unary operators
To invert the sign of the result of an exponentiation expression:
```
-(2 \*\* 2) // -4
```
To force the base of an exponentiation expression to be a negative number:
```
(-2) \*\* 2 // 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-exp-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-exp-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Exponentiation` | 52 | 14 | 52 | No | 39 | 10.1 | 51 | 52 | 52 | 41 | 10.3 | 6.0 | 1.0 | 7.0.0
6.5.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Division operator](division)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript delete operator delete operator
===============
The `delete` operator removes a property from an object. If the property's value is an object and there are no more references to the object, the object held by that property is eventually released automatically.
Try it
------
Syntax
------
```
delete object.property
delete object[property]
```
**Note:** The syntax allows a wider range of expressions following the `delete` operator, but only the above forms lead to meaningful behaviors.
### Parameters
`object` The name of an object, or an expression evaluating to an object.
`property` The property to delete.
### Return value
`true` for all cases except when the property is an [own](../global_objects/object/hasown) [non-configurable](../global_objects/object/defineproperty#configurable_attribute) property, in which case `false` is returned in non-strict mode.
### Exceptions
[`TypeError`](../global_objects/typeerror) Thrown in [strict mode](../strict_mode) if the property is an own non-configurable property.
[`ReferenceError`](../global_objects/referenceerror) Thrown if `object` is [`super`](super).
Description
-----------
The `delete` operator has the same [precedence](operator_precedence) as other unary operators like [`typeof`](typeof). Therefore, it accepts any expression formed by higher-precedence operators. However, the following forms lead to early syntax errors in [strict mode](../strict_mode):
```
delete identifier;
delete object.#privateProperty;
```
Because [classes](../classes) are automatically in strict mode, and [private properties](../classes/private_class_fields) can only be legally referenced in class bodies, this means private properties can never be deleted. While `delete identifier` [may work](#deleting_global_properties) if `identifier` refers to a configurable property of the global object, you should avoid this form and prefix it with [`globalThis`](../global_objects/globalthis) instead.
While other expressions are accepted, they don't lead to meaningful behaviors:
```
delete console.log(1);
// Logs 1, returns true, but nothing deleted
```
The `delete` operator removes a given property from an object. On successful deletion, it will return `true`, else `false` will be returned. Unlike what common belief suggests (perhaps due to other programming languages like [delete in C++](https://docs.microsoft.com/cpp/cpp/delete-operator-cpp?view=msvc-170)), the `delete` operator has **nothing** to do with directly freeing memory. Memory management is done indirectly via breaking references. See the [memory management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management) page for more details.
It is important to consider the following scenarios:
* If the property which you are trying to delete does not exist, `delete` will not have any effect and will return `true`.
* `delete` only has an effect on own properties. If a property with the same name exists on the object's prototype chain, then after deletion, the object will use the property from the prototype chain.
* Non-configurable properties cannot be removed. This includes properties of built-in objects like [`Math`](../global_objects/math), [`Array`](../global_objects/array), [`Object`](../global_objects/object) and properties that are created as non-configurable with methods like [`Object.defineProperty()`](../global_objects/object/defineproperty).
* Deleting variables, including function parameters, never works. `delete variable` will throw a [`SyntaxError`](../global_objects/syntaxerror) in strict mode, and will have no effect in non-strict mode.
+ Any variable declared with [`var`](../statements/var) cannot be deleted from the global scope or from a function's scope, because while they may be attached to the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object), they are not configurable.
+ Any variable declared with [`let`](../statements/let) or [`const`](../statements/const) cannot be deleted from the scope within which they were defined, because they are not attached to an object.
### Cross-browser notes
As of modern ECMAScript specification, the traversal order of object properties is well-defined and stable across implementations. However, in the case of Internet Explorer, when one uses `delete` on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property *value* is indeed set to `undefined`, if one later adds back a property with the same name, the property will be iterated in its *old* position — not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.
If you want to use an ordered associative array with support of old runtimes, use a [`Map`](../global_objects/map) object if available (through a polyfill, for example), or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.
Examples
--------
### Using delete
**Note:** The following example uses non-strict-mode only features, like implicitly creating global variables and deleting identifiers, which are forbidden in strict mode.
```
// Creates the property empCount on the global scope.
// Since we are using var, this is marked as non-configurable.
var empCount = 43;
// Creates the property adminName on the global scope.
// Since it was defined without "var", it is marked configurable.
EmployeeDetails = {
name: "xyz",
age: 5,
designation: "Developer",
};
// delete can be used to remove properties from objects.
delete EmployeeDetails.name; // returns true
// Even when the property does not exist, delete returns "true".
delete EmployeeDetails.salary; // returns true
// EmployeeDetails is a property of the global scope.
delete EmployeeDetails; // returns true
// On the contrary, empCount is not configurable
// since var was used.
delete empCount; // returns false
// delete also does not affect built-in static properties
// that are non-configurable.
delete Math.PI; // returns false
function f() {
var z = 44;
// delete doesn't affect local variable names
delete z; // returns false
}
```
### delete and the prototype chain
In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:
```
function Foo() {
this.bar = 10;
}
Foo.prototype.bar = 42;
const foo = new Foo();
// foo.bar is associated with the
// own property.
console.log(foo.bar); // 10
// Delete the own property within the
// foo object.
delete foo.bar; // returns true
// foo.bar is still available in the
// prototype chain.
console.log(foo.bar); // 42
// Delete the property on the prototype.
delete Foo.prototype.bar; // returns true
// The "bar" property can no longer be
// inherited from Foo since it has been
// deleted.
console.log(foo.bar); // undefined
```
### Deleting array elements
When you delete an array element, the array `length` is not affected. This holds even if you delete the last element of the array.
When the `delete` operator removes an array element, that element is no longer in the array. In the following example, `trees[3]` is removed with `delete`.
```
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
console.log(3 in trees); // false
```
This creates a [sparse array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) with an empty slot. If you want an array element to exist but have an undefined value, use the `undefined` value instead of the `delete` operator. In the following example, `trees[3]` is assigned the value `undefined`, but the array element still exists:
```
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees[3] = undefined;
console.log(3 in trees); // true
```
If instead, you want to remove an array element by changing the contents of the array, use the [`splice()`](../global_objects/array/splice) method. In the following example, `trees[3]` is removed from the array completely using [`splice()`](../global_objects/array/splice):
```
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
```
### Deleting non-configurable properties
When a property is marked as non-configurable, `delete` won't have any effect, and will return `false`. In strict mode, this will raise a `TypeError`.
```
const Employee = {};
Object.defineProperty(Employee, "name", { configurable: false });
console.log(delete Employee.name); // returns false
```
[`var`](../statements/var) creates non-configurable properties that cannot be deleted with the `delete` operator:
```
// Since "nameOther" is added using with the
// var keyword, it is marked as non-configurable
var nameOther = "XYZ";
// We can access this global property using:
Object.getOwnPropertyDescriptor(globalThis, "nameOther");
// {
// value: "XYZ",
// writable: true,
// enumerable: true,
// configurable: false
// }
delete globalThis.nameOther; // return false
```
In strict mode, this would raise an exception.
### Deleting global properties
If a global property is configurable (for example, via direct property assignment), it can be deleted, and subsequent references to them as global variables will produce a [`ReferenceError`](../global_objects/referenceerror).
```
globalThis.globalVar = 1;
console.log(globalVar); // 1
// In non-strict mode, you can use `delete globalVar` as well
delete globalThis.globalVar;
console.log(globalVar); // ReferenceError: globalVar is not defined
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-delete-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-delete-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `delete` | 1 | 12 | 1 | 4 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [In depth analysis on delete](http://perfectionkills.com/understanding-delete/)
* [`Reflect.deleteProperty()`](../global_objects/reflect/deleteproperty)
* [`Map.prototype.delete()`](../global_objects/map/delete)
javascript function* expression function\* expression
=====================
The `function*` keyword can be used to define a generator function inside an expression.
Try it
------
Syntax
------
```
function\* (param0) {
statements
}
function\* (param0, param1) {
statements
}
function\* (param0, param1, /\* … ,\*/ paramN) {
statements
}
function\* name(param0) {
statements
}
function\* name(param0, param1) {
statements
}
function\* name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
### Parameters
`name` Optional
The function name. Can be omitted, in which case the function is *anonymous*. The name is only local to the function body.
`paramN` Optional
The name of an argument to be passed to the function. A function can have up to 255 arguments.
`statements` Optional
The statements which comprise the body of the function.
Description
-----------
A `function*` expression is very similar to and has almost the same syntax as a [function\* statement](../statements/function*). The main difference between a `function*` expression and a `function*` statement is the *function name*, which can be omitted in `function*` expressions to create *anonymous* generator functions. See also the chapter about [`functions`](../functions) for more information.
Examples
--------
### Using function\*
The following example defines an unnamed generator function and assigns it to `x`. The function yields the square of its argument:
```
const x = function\* (y) {
yield y \* y;
};
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-generator-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `function*` | 49 | 12 | 26 | No | 36 | 10 | 49 | 49 | 26 | 36 | 10 | 5.0 | 1.0 | 4.0.0 |
| `trailing_comma` | 58 | 79 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
See also
--------
* [`function*`](../statements/function*) statement
* [`GeneratorFunction`](../global_objects/generatorfunction) object
* [The Iterator protocol](../iteration_protocols)
* [`yield`](yield)
* [`yield*`](yield*)
* [`Function`](../global_objects/function) object
* [`function`](../statements/function) statement
* [`function`](function) expression
javascript new operator new operator
============
The `new` operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
Try it
------
Syntax
------
```
new constructor
new constructor()
new constructor(arg1)
new constructor(arg1, arg2)
new constructor(arg1, arg2, /\* …, \*/ argN)
```
### Parameters
`constructor` A class or function that specifies the type of the object instance.
`arg1`, `arg2`, …, `argN`
A list of values that the `constructor` will be called with. `new Foo` is equivalent to `new Foo()`, i.e. if no argument list is specified, `Foo` is called without arguments.
Description
-----------
When a function is called with the `new` keyword, the function will be used as a constructor. `new` will do the following things:
1. Creates a blank, plain JavaScript object. For convenience, let's call it `newInstance`.
2. Points `newInstance`'s [[Prototype]] to the constructor function's `prototype` property, if the `prototype` is an [`Object`](../global_objects/object). Otherwise, `newInstance` stays as a plain object with `Object.prototype` as its [[Prototype]]. **Note:** Properties/objects added to the constructor function's `prototype` property are therefore accessible to all instances created from the constructor function.
3. Executes the constructor function with the given arguments, binding `newInstance` as the [`this`](this) context (i.e. all references to `this` in the constructor function now refer to `newInstance`).
4. If the constructor function returns a [non-primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values), this return value becomes the result of the whole `new` expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, `newInstance` is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)
[Classes](../classes) can only be instantiated with the `new` operator — attempting to call a class without `new` will throw a `TypeError`.
Creating an object with a user-defined constructor function requires two steps:
1. Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object `Foo` might look like this:
```
function Foo(bar1, bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
```
2. Create an instance of the object with `new`.
```
const myFoo = new Foo('Bar 1', 2021);
```
**Note:** An object can have a property that is itself another object. See the examples below.
You can always add a property to a previously defined object instance. For example, the statement `car1.color = "black"` adds a property `color` to `car1`, and assigns it a value of `"black"`.
However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor's `prototype` property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a `color` property with value `"original color"` to all objects of type `Car`, and then overwrites that value with the string `"black"` only in the instance object `car1`. For more information, see [prototype](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes).
```
function Car() {}
const car1 = new Car();
const car2 = new Car();
console.log(car1.color); // undefined
Car.prototype.color = 'original color';
console.log(car1.color); // 'original color'
car1.color = 'black';
console.log(car1.color); // 'black'
console.log(Object.getPrototypeOf(car1).color); // 'original color'
console.log(Object.getPrototypeOf(car2).color); // 'original color'
console.log(car1.color); // 'black'
console.log(car2.color); // 'original color'
```
**Note:** While the constructor function can be invoked like any regular function (i.e. without the `new` operator), in this case a new object is not created and the value of `this` is also different.
A function can know whether it is invoked with `new` by checking [`new.target`](new.target). `new.target` is only `undefined` when the function is invoked without `new`. For example, you can have a function that behaves differently when it's called versus when it's constructed:
```
function Car(color) {
if (!new.target) {
// Called as function.
return `${color} car`;
}
// Called with new.
this.color = color;
}
const a = Car("red"); // a is "red car"
const b = new Car("red"); // b is `Car { color: "red" }`
```
Prior to ES6, which introduced [classes](../classes), most JavaScript built-ins are both callable and constructible, although many of them exhibit different behaviors. To name a few:
* [`Array()`](../global_objects/array/array), [`Error()`](../global_objects/error/error), and [`Function()`](../global_objects/function/function) behave the same when called as a function or a constructor.
* [`Boolean()`](../global_objects/boolean/boolean), [`Number()`](../global_objects/number/number), and [`String()`](../global_objects/string/string) coerce their argument to the respective primitive type when called, and return wrapper objects when constructed.
* [`Date()`](../global_objects/date/date) returns a string representing the current date when called, equivalent to `new Date().toString()`.
After ES6, the language is stricter about which are constructors and which are functions. For example:
* [`Symbol()`](../global_objects/symbol/symbol) and [`BigInt()`](../global_objects/bigint/bigint) can only be called without `new`. Attempting to construct them will throw a `TypeError`.
* [`Proxy`](../global_objects/proxy/proxy) and [`Map`](../global_objects/map/map) can only be constructed with `new`. Attempting to call them will throw a `TypeError`.
Examples
--------
### Object type and object instance
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:
```
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
```
Now you can create an object called `myCar` as follows:
```
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.year` is the integer 1993, and so on.
You can create any number of `car` objects by calls to `new`. For example:
```
const kensCar = new Car('Nissan', '300ZX', 1992);
```
### Object property that is itself another object
Suppose you define an object called `Person` as follows:
```
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
```
And then instantiate two new `Person` objects as follows:
```
const rand = new Person('Rand McNally', 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:
```
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:
```
const car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
const car2 = new Car('Nissan', '300ZX', 1992, ken);
```
Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects `rand` and `ken` as the parameters for the owners. To find out the name of the owner of `car2`, you can access the following property:
```
car2.owner.name
```
### Using `new` with classes
```
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const p = new Person("Caroline");
p.greet(); // Hello, my name is Caroline
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-new-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-new-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `new` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Function`](../global_objects/function)
* [`Reflect.construct()`](../global_objects/reflect/construct)
* [`Object`](../global_objects/object)
| programming_docs |
javascript Function expression Function expression
===================
The `function` keyword can be used to define a function inside an expression.
You can also define functions using the [`Function`](../global_objects/function/function) constructor and a [function declaration](../statements/function).
Try it
------
Syntax
------
The expression is not allowed at the start of a statement.
```
function (param0) {
statements
}
function (param0, param1) {
statements
}
function (param0, param1, /\* … ,\*/ paramN) {
statements
}
function name(param0) {
statements
}
function name(param0, param1) {
statements
}
function name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
You can also create functions using the [arrow function syntax](../functions/arrow_functions).
### Parameters
`name` Optional
The function name. Can be omitted, in which case the function is *anonymous*. The name is only local to the function body.
`paramN` Optional
The name of an argument to be passed to the function.
`statements` Optional
The statements which comprise the body of the function.
Description
-----------
A function expression is very similar to and has almost the same syntax as a function declaration (see [`function`](../statements/function) statement for details). The main difference between a function expression and a function declaration is the *function name*, which can be omitted in function expressions to create *anonymous* functions.
A function expression can be used as an [IIFE (Immediately Invoked Function Expression)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) which runs as soon as it is defined. See also the chapter about [functions](../functions) for more information.
### Function expression hoisting
Function expressions in JavaScript are not hoisted, unlike [function declarations](../statements/function#function_declaration_hoisting). You can't use function expressions before you create them:
```
console.log(notHoisted); // undefined
// Even though the variable name is hoisted,
// the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function () {
console.log('bar');
};
```
### Named function expression
If you want to refer to the current function inside the function body, you need to create a named function expression. **This name is then local only to the function body (scope)**. This also avoids using the non-standard [`arguments.callee`](../functions/arguments/callee) property.
```
const math = {
factit: function factorial(n) {
console.log(n)
if (n <= 1) {
return 1;
}
return n \* factorial(n - 1);
}
};
math.factit(3) //3;2;1;
```
The variable to which the function expression is assigned will have a `name` property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to [arrow functions](../functions/arrow_functions) (arrows don't have a name so you can only give the variable an implicit name).
```
const foo = function () {};
foo.name // "foo"
const foo2 = foo;
foo2.name // "foo"
const bar = function baz() {};
bar.name // "baz"
console.log(foo === foo2); // true
console.log(typeof baz); // undefined
console.log(bar === baz); // false (errors because baz == undefined)
```
Examples
--------
### Creating an unnamed function
The following example defines an unnamed function and assigns it to `x`. The function returns the square of its argument:
```
const x = function (y) {
return y \* y;
};
```
### Using a function as a callback
More commonly it is used as a [callback](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function):
```
button.addEventListener('click', function (event) {
console.log('button is clicked!');
})
```
### Using an Immediately Invoked Function Expression (IIFE)
An anonymous function is created and called:
```
(function () {
console.log('Code runs!');
})();
// or
!function () {
console.log('Code runs!');
}();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `function` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `trailing_comma` | 58 | 14 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
See also
--------
* [Arrow functions](../functions/arrow_functions)
* [Functions](../functions)
* [`Function`](../global_objects/function)
* [`function`](../statements/function) statement
* [`function*`](../statements/function*) statement
* [`function*`](function*) expression
* [`GeneratorFunction`](../global_objects/generatorfunction)
* [async function](../statements/async_function)
* [async function expression](async_function)
javascript Remainder assignment (%=) Remainder assignment (%=)
=========================
The `%=` operator divides a variable by the value of the right operand and assigns the remainder to the variable.
Try it
------
Syntax
------
```
x %= y // x = x % y
```
Examples
--------
### Using remainder assignment
```
let bar = 5;
bar %= 2; // 1
bar %= 'foo'; // NaN
bar %= 0; // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Remainder_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Remainder operator](remainder)
javascript Conditional (ternary) operator Conditional (ternary) operator
==============================
The **conditional (ternary) operator** is the only JavaScript operator that takes three operands: a condition followed by a question mark (`?`), then an expression to execute if the condition is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) followed by a colon (`:`), and finally the expression to execute if the condition is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). This operator is frequently used as an alternative to an [`if...else`](../statements/if...else) statement.
Try it
------
Syntax
------
```
condition ? exprIfTrue : exprIfFalse
```
### Parameters
`condition` An expression whose value is used as a condition.
`exprIfTrue` An expression which is executed if the `condition` evaluates to a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value (one which equals or can be converted to `true`).
`exprIfFalse` An expression which is executed if the `condition` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) (that is, has a value which can be converted to `false`).
Description
-----------
Besides `false`, possible falsy expressions are: `null`, `NaN`, `0`, the empty string (`""`), and `undefined`. If `condition` is any of these, the result of the conditional expression will be the result of executing the expression `exprIfFalse`.
Examples
--------
### A simple example
```
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
```
### Handling null values
One common usage is to handle a value that may be `null`:
```
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
}
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
```
### Conditional chains
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an `if … else if … else if … else` chain:
```
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
```
This is equivalent to the following [`if...else`](../statements/if...else) chain.
```
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-conditional-operator](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-conditional-operator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Conditional_Operator` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [if statement](../statements/if...else)
* [Nullish coalescing operator](nullish_coalescing)
* [Optional chaining](optional_chaining)
* [Making decisions in your code — conditionals](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
* [Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators)
javascript yield yield
=====
The `yield` operator is used to pause and resume a [generator function](../statements/function*).
Try it
------
Syntax
------
```
[rv] = yield [expression]
```
`expression` Optional
Defines the value to return from the generator function via [the iterator protocol](../iteration_protocols#the_iterator_protocol). If omitted, `undefined` is returned instead.
`rv` Optional
Retrieves the optional value passed to the generator's `next()` method to resume its execution.
Description
-----------
The `yield` keyword pauses generator function execution and the value of the expression following the `yield` keyword is returned to the generator's caller. It can be thought of as a generator-based version of the `return` keyword.
`yield` can only be called directly from the generator function that contains it. It cannot be called from nested functions or from callbacks.
The `yield` keyword causes the call to the generator's `next()` method to return an `IteratorResult` object with two properties: `value` and `done`. The `value` property is the result of evaluating the `yield` expression, and `done` is `false`, indicating that the generator function has not fully completed.
Once paused on a `yield` expression, the generator's code execution remains paused until the generator's `next()` method is called. Each time the generator's `next()` method is called, the generator resumes execution, and runs until it reaches one of the following:
* A `yield`, which causes the generator to once again pause and return the generator's new value. The next time `next()` is called, execution resumes with the statement immediately after the `yield`.
* [`throw`](../statements/throw) is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown).
* The end of the generator function is reached. In this case, execution of the generator ends and an `IteratorResult` is returned to the caller in which the `value` is [`undefined`](../global_objects/undefined) and `done` is `true`.
* A [`return`](../statements/return) statement is reached. In this case, execution of the generator ends and an `IteratorResult` is returned to the caller in which the `value` is the value specified by the `return` statement and `done` is `true`.
If an optional value is passed to the generator's `next()` method, that value becomes the value returned by the generator's current `yield` operation.
Between the generator's code path, its `yield` operators, and the ability to specify a new starting value by passing it to [`Generator.prototype.next()`](../global_objects/generator/next), generators offer enormous power and control.
**Warning:** Unfortunately, `next()` is asymmetric, but that can't be helped: It always sends a value to the currently suspended `yield`, but returns the operand of the following `yield`.
Examples
--------
### Using yield
The following code is the declaration of an example generator function.
```
function\* countAppleSales() {
const saleList = [3, 7, 5];
for (let i = 0; i < saleList.length; i++) {
yield saleList[i];
}
}
```
Once a generator function is defined, it can be used by constructing an iterator as shown.
```
const appleStore = countAppleSales(); // Generator { }
console.log(appleStore.next()); // { value: 3, done: false }
console.log(appleStore.next()); // { value: 7, done: false }
console.log(appleStore.next()); // { value: 5, done: false }
console.log(appleStore.next()); // { value: undefined, done: true }
```
You can also send a value with `next(value)` into the generator. `step` evaluates as a return value in this syntax `rv = yield expression` — although a value passed to the generator's `next()` method is ignored the first time `next()` is called.
```
function\* counter(value) {
let step;
while (true) {
step = yield value++;
if (step) {
value += step;
}
}
}
const generatorFunc = counter(0);
console.log(generatorFunc.next().value); // 0
console.log(generatorFunc.next().value); // 1
console.log(generatorFunc.next().value); // 2
console.log(generatorFunc.next().value); // 3
console.log(generatorFunc.next(10).value); // 14
console.log(generatorFunc.next().value); // 15
console.log(generatorFunc.next(10).value); // 26
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-YieldExpression](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#prod-YieldExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `yield` | 39 | 12 | 26
["Starting with Firefox 33, the parsing of the `yield` expression has been updated to conform with the ES2015 specification.", "Starting with Firefox 29, an `IteratorResult` object returned for completed generator function."] | No | 26 | 10 | 39 | 39 | 26
["Starting with Firefox 33, the parsing of the `yield` expression has been updated to conform with the ES2015 specification.", "Starting with Firefox 29, an `IteratorResult` object returned for completed generator function."] | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [The Iterator protocol](../iteration_protocols)
* [`function*`](../statements/function*)
* [`function*` expression](function*)
* [`yield*`](yield*)
javascript Division assignment (/=) Division assignment (/=)
========================
The `/=` operator divides a variable by the value of the right operand and assigns the result to the variable.
Try it
------
Syntax
------
```
x /= y // x = x / y
```
Examples
--------
### Using division assignment
```
let bar = 5;
bar /= 2; // 2.5
bar /= 2; // 1.25
bar /= 0; // Infinity
bar /= "foo"; // NaN
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-assignment-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-assignment-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Division_assignment` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators)
* [Division operator](division)
javascript Logical AND (&&) Logical AND (&&)
================
The `&&` (logical conjunction) operator for a set of boolean operands will be `true` if and only if all the operands are `true`. Otherwise it will be `false`.
More generally, the operator returns the value of the first [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) operand encountered when evaluating from left to right, or the value of the last operand if they are all [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
Try it
------
Syntax
------
```
expr1 && expr2
```
Description
-----------
Logical AND (`&&`) evaluates operands from left to right, returning immediately with the value of the first [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) operand it encounters; if all values are [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), the value of the last operand is returned.
If a value can be converted to `true`, the value is so-called [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). If a value can be converted to `false`, the value is so-called [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
Examples of expressions that can be converted to false are:
* `false`;
* `null`;
* `NaN`;
* `0`;
* empty string (`""` or `''` or ````);
* `undefined`.
The AND operator preserves non-Boolean values and returns them as they are:
```
result = '' && 'foo'; // result is assigned "" (empty string)
result = 2 && 0; // result is assigned 0
result = 'foo' && 4; // result is assigned 4
```
Even though the `&&` operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a [boolean primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type). To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double [`NOT operator`](logical_not) or the [`Boolean`](../global_objects/boolean/boolean) constructor.
### Short-circuit evaluation
The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be `false`, the AND operator stops and returns the original value of that falsy operand; it does **not** evaluate any of the remaining operands.
Consider the pseudocode below.
```
(some falsy expression) && expr
```
The `expr` part is **never evaluated** because the first operand `(some falsy expression)` is evaluated as [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). If `expr` is a function, the function is never called. See the example below:
```
function A() {
console.log('called A');
return false;
}
function B() {
console.log('called B');
return true;
}
console.log(A() && B());
// Logs "called A" to the console due to the call for function A,
// && evaluates to false (function A returns false), then false is logged to the console;
// the AND operator short-circuits here and ignores function B
```
### Operator precedence
The AND operator has a higher precedence than the OR operator, meaning the `&&` operator is executed before the `||` operator (see [operator precedence](operator_precedence)).
```
true || false && false // returns true
true && (false || false) // returns false
(2 === 3) || (4 < 0) && (1 === 1) // returns false
```
Examples
--------
### Using AND
The following code shows examples of the `&&` (logical AND) operator.
```
a1 = true && true // t && t returns true
a2 = true && false // t && f returns false
a3 = false && true // f && t returns false
a4 = false && (3 === 4) // f && f returns false
a5 = 'Cat' && 'Dog' // t && t returns "Dog"
a6 = false && 'Cat' // f && t returns false
a7 = 'Cat' && false // t && f returns false
a8 = '' && false // f && f returns ""
a9 = false && '' // f && f returns false
```
### Conversion rules for booleans
#### Converting AND to OR
The following operation involving **booleans**:
```
bCondition1 && bCondition2
```
is always equal to:
```
!(!bCondition1 || !bCondition2)
```
#### Converting OR to AND
The following operation involving **booleans**:
```
bCondition1 || bCondition2
```
is always equal to:
```
!(!bCondition1 && !bCondition2)
```
### Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.
The following composite operation involving **booleans**:
```
bCondition1 || (bCondition2 && bCondition3)
```
is always equal to:
```
bCondition1 || bCondition2 && bCondition3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-LogicalANDExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-LogicalANDExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Logical_AND` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Boolean`](../global_objects/boolean)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
| programming_docs |
javascript Logical OR (||) Logical OR (||)
===============
The `||` (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the `||` operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.
Try it
------
Syntax
------
```
expr1 || expr2
```
Description
-----------
If `expr1` can be converted to `true`, returns `expr1`; else, returns `expr2`.
If a value can be converted to `true`, the value is so-called [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). If a value can be converted to `false`, the value is so-called [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
Examples of expressions that can be converted to false are:
* `null`;
* `NaN`;
* `0`;
* empty string (`""` or `''` or ````);
* `undefined`.
Even though the `||` operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a [boolean primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type). To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double [NOT operator](logical_not) or the [`Boolean`](../global_objects/boolean/boolean) constructor.
### Short-circuit evaluation
The logical OR expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule:
`(some truthy expression) || expr` is short-circuit evaluated to the truthy expression.
Short circuit means that the `expr` part above is **not evaluated**, hence any side effects of doing so do not take effect (e.g., if `expr` is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:
```
function A() {
console.log('called A');
return false;
}
function B() {
console.log('called B');
return true;
}
console.log(B() || A());
// Logs "called B" due to the function call,
// then logs true (which is the resulting value of the operator)
```
### Operator precedence
The following expressions might seem equivalent, but they are not, because the `&&` operator is executed before the `||` operator (see [operator precedence](operator_precedence)).
```
true || false && false // returns true, because && is executed first
(true || false) && false // returns false, because grouping has the highest precedence
```
Examples
--------
### Using OR
The following code shows examples of the `||` (logical OR) operator.
```
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 === 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
o10 = false || varObject // f || object returns varObject
```
**Note:** If you use this operator to provide a default value to some variable, be aware that any *falsy* value will not be used. If you only need to filter out [`null`](null) or [`undefined`](../global_objects/undefined), consider using [the nullish coalescing operator](nullish_coalescing).
### Conversion rules for booleans
#### Converting AND to OR
The following operation involving **booleans**:
```
bCondition1 && bCondition2
```
is always equal to:
```
!(!bCondition1 || !bCondition2)
```
#### Converting OR to AND
The following operation involving **booleans**:
```
bCondition1 || bCondition2
```
is always equal to:
```
!(!bCondition1 && !bCondition2)
```
### Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules.
The following composite operation involving **booleans**:
```
bCondition1 && (bCondition2 || bCondition3)
```
is always equal to:
```
!(!bCondition1 || !bCondition2 && !bCondition3)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-LogicalORExpression](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-LogicalORExpression) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Logical_OR` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [The nullish coalescing operator (`??`)](nullish_coalescing)
* [`Boolean`](../global_objects/boolean)
* [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
* [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
javascript Division (/) Division (/)
============
The `/` operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.
Try it
------
Syntax
------
```
x / y
```
Examples
--------
### Basic division
```
1 / 2; // 0.5
Math.floor(3 / 2); // 1
1.0 / 2.0; // 0.5
```
### Division by zero
```
2.0 / 0; // Infinity
2.0 / 0.0; // Infinity, because 0.0 === 0
2.0 / -0.0; // -Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-multiplicative-operators](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-multiplicative-operators) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Division` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Addition operator](addition)
* [Subtraction operator](subtraction)
* [Multiplication operator](multiplication)
* [Remainder operator](remainder)
* [Exponentiation operator](exponentiation)
* [Increment operator](increment)
* [Decrement operator](decrement)
* [Unary negation operator](unary_negation)
* [Unary plus operator](unary_plus)
javascript constructor constructor
===========
The `constructor` method is a special method of a [class](../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 [`Object.prototype.constructor`](../global_objects/object/constructor).
Try it
------
Syntax
------
```
constructor() { /\* … \*/ }
constructor(argument0) { /\* … \*/ }
constructor(argument0, argument1) { /\* … \*/ }
constructor(argument0, argument1, /\* … ,\*/ argumentN) { /\* … \*/ }
```
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.
```
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:
```
constructor() {}
```
If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:
```
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](../global_objects/array/@@iterator) through [argument spreading](../operators/spread_syntax).
That enables code like this to work:
```
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()`](../operators/super). For example:
```
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`](../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](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`](../operators/this) and access the class that is called with [`new`](../operators/new) through [`new.target`](../operators/new.target). Note that methods (including [getters](../functions/get) and [setters](../functions/set)) and the [prototype chain](https://developer.mozilla.org/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`.
```
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 [`TypeError`](../global_objects/typeerror) will be thrown.
```
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](public_class_fields) of the derived class will be defined. This trick is called ["return overriding"](private_class_fields#returning_overriding_object), which allows a derived class's fields (including [private](private_class_fields) ones) to be defined on unrelated objects.
There can be only one special method with the name `constructor` in a class. Having more than one occurrence of a `constructor` method in a class will throw a [`SyntaxError`](../global_objects/syntaxerror) error. Having a getter or setter called `constructor` is also a [`SyntaxError`](../global_objects/syntaxerror).
The `constructor` follows normal [method](../functions/method_definitions) syntax, so [parameter default values](../functions/default_parameters), [rest parameters](../functions/rest_parameters), etc. can all be used.
```
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.
```
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 }
```
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)).
```
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 of the new prototype. Changing the prototype of the current class's `prototype` property doesn't affect which constructor `super()` calls.
```
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
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-static-semantics-constructormethod](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-static-semantics-constructormethod) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `constructor` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
See also
--------
* [`super()`](../operators/super)
* [`class` declaration](../statements/class)
* [`class` expression](../operators/class)
* [`Classes`](../classes)
* [`Object.prototype.constructor`](../global_objects/object/constructor)
* [Static initialization block](static_initialization_blocks)
javascript Public class fields Public class fields
===================
Both static and instance public fields are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they participate in prototype inheritance.
Syntax
------
```
class ClassWithField {
instanceField;
instanceFieldWithInitializer = "instance field";
static staticField;
static staticFieldWithInitializer = "static field";
}
```
Description
-----------
This page introduces public instance fields in detail.
* For public static fields, see [`static`](static).
* For private fields, see [private class features](private_class_fields).
* For public methods, see [methods definitions](../functions/method_definitions).
* For public accessors, see [getter](../functions/get) and [setter](../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.
```
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"
```
In the field initializer, [`this`](../operators/this) refers to the class instance under construction, and [`super`](../operators/super) refers to the `prototype` property of the base class, which contains the base class's instance methods, but not its instance fields.
```
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"
```
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.
```
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
```
Because class fields are added using the [`[[DefineOwnProperty]]`](../global_objects/proxy/proxy/defineproperty) semantic (which is essentially [`Object.defineProperty()`](../global_objects/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.
```
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.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-FieldDefinition](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#prod-FieldDefinition) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Public_class_fields` | 72 | 79 | 69 | No | 60 | 14.1
14-14.1
Doesn't support public static fields. See WebKit bug [194095](https://webkit.org/b/194095). | 72 | 72 | 79 | 51 | 14.5
14-14.5
Doesn't support public static fields. See WebKit bug [194095](https://webkit.org/b/194095). | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [The Semantics of All JS Class Elements](https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html)
* [Public and private class fields](https://v8.dev/features/class-fields) article at the v8.dev site
| programming_docs |
javascript Static initialization blocks Static initialization blocks
============================
**Static initialization blocks** are a special feature of a [`class`](../statements/class) that enable more flexible initialization of [`static`](static) properties than can be achieved using per-field initialization.
Static blocks allow statements to be evaluated during initialization, which allows initializations that (for example) include `try...catch` or set multiple fields from a single value.
Initialization is performed in the context of the current class declaration, with privileged access to private state. This means that static blocks can also be used to share information between classes with instance private fields and other classes or functions declared in the same scope (analogous to "friend" classes in C++).
Try it
------
Syntax
------
```
class ClassWithSIB {
static {
// …
}
}
```
Description
-----------
A [`class`](../statements/class) can have any number of `static {}` initialization blocks in its class body. These are evaluated, along with any interleaved static field initializers, in the order they are declared. Any static initialization of a super class is performed first, before that of its sub classes.
The scope of the variables declared inside the static block is local to the block. Since `var`, `function`, `const` or `let` declared in a `static {}` initialization block are local to the block, any `var` declarations in the block are not hoisted.
```
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 properties of a super class. Note however that it is a syntax error to call [`super()`](../operators/super) in a class static initialization block, or to attempt to access arguments of the class constructor function.
The scope of the static block is nested *within* the lexical scope of the class body, and can access the private instance variables of the class.
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.
```
class MyClass {
static field1 = console.log('field1 called');
static {
console.log('Class static block #1 called');
}
static field2 = console.log('field2 called');
static {
console.log('Class static block #2 called');
}
}
/\*
> "field1 called"
> "Class static block #1 called"
> "field2 called"
> "Class static block #2 called"
\*/
```
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.
```
class A {
static field = 'A static field';
static {
console.log(this.field);
}
}
```
The [`super.property`](../operators/super) can be used inside a `static` block to reference properties of a super class. This includes static properties, as shown below:
```
class A {
static fieldA = 'A.fieldA';
}
class B extends A {
static {
console.log(super.fieldA);
// 'A.fieldA'
}
}
```
### Access to private fields
This example below shows how access can be granted to the private object 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)):
```
let getDPrivateField;
class D {
#privateField;
constructor(v) {
this.#privateField = v;
}
static {
getDPrivateField = (d) => d.#privateField;
}
}
console.log(getDPrivateField(new D('private'))); // private
```
### Workarounds
Prior to ES13 more complex static initialization might be achieved by using a static method that is called after the other properties to perform static initialization, or having a method that is external to the class that performs initialization tasks.
In both cases the approach is less elegant, and does not grant access to private methods in the class.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-ClassStaticBlock](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#prod-ClassStaticBlock) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Static_initialization_blocks` | 94 | 94 | 93 | No | 80 | No | 94 | 94 | 93 | 66 | No | 17.0 | 1.14 | 16.11.0 |
See also
--------
* [Class static initialization blocks](https://v8.dev/features/class-static-initializer-blocks) (v8.dev blog)
* [ES2022 feature: class static initialization blocks](https://2ality.com/2021/09/class-static-block.html) (2ality.com blog)
* [Classes](../classes)
* [`super()`](../operators/super)
* [Object.prototype.constructor](../global_objects/object/constructor)
javascript static static
======
The `static` keyword defines a [static method or field](../classes#static_methods_and_properties) for a class, or a [static initialization block](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](public_class_fields) interchangeably.
Try it
------
Syntax
------
```
class ClassWithStatic {
static staticField;
static staticFieldWithInitializer = value;
static staticMethod() {
// …
}
}
```
Description
-----------
This page introduces public static properties of classes, which include static methods, static accessors, and static fields.
* For private static features, see [private class features](private_class_fields).
* For instance features, see [methods definitions](../functions/method_definitions), [getter](../functions/get), [setter](../functions/set), and [public class fields](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 using the [`[[DefineOwnProperty]]`](../global_objects/proxy/proxy/defineproperty) semantic (which is essentially [`Object.defineProperty()`](../global_objects/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 fields without initializers are initialized to `undefined`. Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.
```
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`](../operators/this) refers to the current class (which you can also access through its name), and [`super`](../operators/super) refers to the base class constructor.
```
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"
```
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.
```
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`](../operators/this) keyword.
```
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 [`this`](../operators/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`
```
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
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-class-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `static` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
See also
--------
* [`class` expression](../operators/class)
* [`class` declaration](../statements/class)
* [Classes](../classes)
javascript Private class features Private class features
======================
Class fields are [public](public_class_fields) by default, but private class members can be created by using a hash `#` prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.
Private members are not native to the language before this syntax existed. In prototypical inheritance, its behavior may be emulated with [`WeakMap`](../global_objects/weakmap#emulating_private_members) objects or [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#emulating_private_methods_with_closures), but they can't compare to the `#` syntax in terms of ergonomics.
Syntax
------
```
class ClassWithPrivate {
#privateField;
#privateFieldWithInitializer = 42;
#privateMethod() {
// …
}
static #privateStaticField;
static #privateStaticFieldWithInitializer = 42;
static #privateStaticMethod() {
// …
}
}
```
Description
-----------
Most class features 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](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](../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`](../operators/delete).
```
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
delete this.#privateField; // Syntax error
this.#undeclaredField = 444; // Syntax error
}
}
const instance = new ClassWithPrivateField();
instance.#privateField === 42; // 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.
If you access a private property from an object that doesn't have the property, a [`TypeError`](../global_objects/typeerror) is thrown, instead of returning `undefined` as normal properties do.
```
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
```
You can use the [`in`](../operators/in) operator to check for potentially missing private fields (or private methods). This will return `true` if the private field or method exists, and `false` otherwise.
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](https://developer.mozilla.org/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.
Examples
--------
### Private fields
Private fields include private instance fields and private static fields. Private fields are accessible on the class constructor from inside the class declaration itself. They are used for declaration of field names as well as for accessing a field's value.
#### Private instance fields
Like public fields, private fields are added before the constructor runs in a base class, or immediately after [`super()`](../operators/super) is invoked in a subclass.
```
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
}
}
class SubClass extends ClassWithPrivateField {
#subPrivateField;
constructor() {
super();
this.#subPrivateField = 23;
}
}
new SubClass();
// SubClass {#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.
```
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
```
**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
Private static fields are added to the class constructor at class evaluation time. Like their public counterparts, private static fields are only accessible on the class itself or on the `this` context of static methods, but not on the `this` context of instance methods.
```
class ClassWithPrivateStaticField {
static #PRIVATE\_STATIC\_FIELD;
static publicStaticMethod() {
ClassWithPrivateStaticField.#PRIVATE\_STATIC\_FIELD = 42;
return ClassWithPrivateStaticField.#PRIVATE\_STATIC\_FIELD;
}
publicInstanceMethod() {
ClassWithPrivateStaticField.#PRIVATE\_STATIC\_FIELD = 42;
return ClassWithPrivateStaticField.#PRIVATE\_STATIC\_FIELD;
}
}
console.log(ClassWithPrivateStaticField.publicStaticMethod()); // 42
console.log(new ClassWithPrivateStaticField().publicInstanceMethod()); // 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`](../operators/this). In the following example, `this` refers to the `SubClass` class (not the `BaseClassWithPrivateStaticField` class) when we try to call `SubClass.basePublicStaticMethod()`, and so causes a `TypeError`.
```
class BaseClassWithPrivateStaticField {
static #PRIVATE\_STATIC\_FIELD;
static basePublicStaticMethod() {
return this.#PRIVATE\_STATIC\_FIELD;
}
}
class SubClass extends BaseClassWithPrivateStaticField {}
SubClass.basePublicStaticMethod(); // TypeError: Cannot read private member #PRIVATE\_STATIC\_FIELD 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`](../operators/super#calling_methods_from_super).
```
class BaseClassWithPrivateStaticField {
static #PRIVATE\_STATIC\_FIELD;
static basePublicStaticMethod() {
// When invoked through super, `this` still refers to Subclass
return this.#PRIVATE\_STATIC\_FIELD;
}
}
class SubClass extends BaseClassWithPrivateStaticField {
static callSuperBaseMethod() {
return super.basePublicStaticMethod();
}
}
SubClass.callSuperBaseMethod(); // TypeError: Cannot read private member #PRIVATE\_STATIC\_FIELD from an object whose class did not declare it
```
You are advised to always access static private fields through the class name, not through `this`, so inheritance doesn't break the method.
### Private methods
#### Private instance methods
Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.
```
class ClassWithPrivateMethod {
#privateMethod() {
return "hello world";
}
getPrivateMessage() {
return this.#privateMethod();
}
}
const instance = new ClassWithPrivateMethod();
console.log(instance.getPrivateMessage());
// hello world
```
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](../functions/get) and [setter](../functions/set) counterparts.
```
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 `Class.prototype`.
```
class C {
#method() {}
static getMethod(x) {
return x.#method;
}
}
console.log(C.getMethod(new C())); // [Function: #method]
console.log(C.getMethod(C.prototype)); // Object must be an instance of class C
```
#### Private static methods
Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.
```
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod1() {
return ClassWithPrivateStaticMethod.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
console.log(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42);
// true
console.log(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42);
// true
```
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 `Derived.publicStaticMethod2()`, `this` refers to the `Derived` class (not the `Base` class) and so causes a `TypeError`.
```
class Base {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod1() {
return Base.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
class Derived extends Base {}
console.log(Derived.publicStaticMethod1());
// 42
console.log(Derived.publicStaticMethod2());
// 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.
```
class PrivateConstructor {
static #isInternalConstructing = false;
constructor() {
if (!PrivateConstructor.#isInternalConstructing) {
throw new TypeError("PrivateConstructor is not constructable");
}
}
static create() {
PrivateConstructor.#isInternalConstructing = true;
const instance = new PrivateConstructor();
PrivateConstructor.#isInternalConstructing = false;
return instance;
}
}
new PrivateConstructor(); // TypeError: PrivateConstructor is not constructable
PrivateConstructor.create(); // PrivateConstructor {}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # prod-PrivateIdentifier](https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#prod-PrivateIdentifier) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Private_class_fields` | 74 | 79 | 90 | No | 62 | 14.1 | 74 | 74 | 90 | 53 | 14.5 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [Using classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_Classes)
* [Public class fields](public_class_fields)
* [Private Syntax FAQ](https://github.com/tc39/proposal-class-fields/blob/main/PRIVATE_SYNTAX_FAQ.md)
* [The Semantics of All JS Class Elements](https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html)
* [Public and private class fields](https://v8.dev/features/class-fields) article at the v8.dev site
| programming_docs |
javascript extends extends
=======
The `extends` keyword is used in [class declarations](../statements/class) or [class expressions](../operators/class) to create a class that is a child of another class.
Try it
------
Syntax
------
```
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`](../operators/new) and has the [`prototype`](../global_objects/function/prototype) property can be the candidate for the parent class. The two conditions must both hold — for example, [bound functions](../global_objects/function/bind) and [`Proxy`](../global_objects/proxy) can be constructed, but they don't have a `prototype` property, so they cannot be subclassed.
```
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 [`Object`](../global_objects/object) or [`null`](../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`](../operators/new) operator.)
```
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` | `Function.prototype` | `null` |
| `extends ParentClass` | `ParentClass` | `ParentClass.prototype` |
```
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).
```
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 [`TypeError`](../global_objects/typeerror) will be thrown.
```
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 for the derived class when further initializing [class fields](public_class_fields). This trick is called ["return overriding"](private_class_fields#returning_overriding_object), which allows a derived class's fields (including [private](private_class_fields) 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 [`Promise.resolve()`](../global_objects/promise/resolve) or [`Array.from()`](../global_objects/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 [`Promise.prototype.then()`](../global_objects/promise/then) or [`Array.prototype.map()`](../global_objects/array/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 [`Promise`](../global_objects/promise), overriding [`then()`](../global_objects/promise/then) automatically causes the behavior of [`catch()`](../global_objects/promise/catch) to change; or for a subclass of [`Map`](../global_objects/map), overriding [`set()`](../global_objects/map/set) automatically causes the behavior of the [`Map()`](../global_objects/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`](../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 [`Array.from()`](../global_objects/array/from) does, but that still means the base class is special-cased.
* The second one requires the instance method to read [`this.constructor`](../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`](../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).
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).
```
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 [`Object.setPrototypeOf()`](../global_objects/object/setprototypeof):
```
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 [`Date`](../global_objects/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).
```
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()}`;
}
}
```
### Species
You might want to return [`Array`](../global_objects/array) objects in your derived array class `MyArray`. The species pattern lets you override default constructors.
For example, when using methods such as [`Array.prototype.map()`](../global_objects/array/map) that return the default constructor, you want these methods to return a parent `Array` object, instead of the `MyArray` object. The [`Symbol.species`](../global_objects/symbol/species) symbol lets you do this:
```
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:
```
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:
```
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`:
```
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()`](../global_objects/map/map) constructor calls the instance's `set()` method.
```
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.
```
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
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-class-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `extends` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 9 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 9 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0
5.0.0
4.0.0 |
See also
--------
* [Classes](../classes)
* [`constructor`](constructor)
* [`super`](../operators/super)
* [Anurag Majumdar - Super & Extends in JavaScript](https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420)
javascript throw throw
=====
The `throw` statement throws a user-defined exception. Execution of the current function will stop (the statements after `throw` won't be executed), and control will be passed to the first [`catch`](try...catch) block in the call stack. If no `catch` block exists among caller functions, the program will terminate.
Try it
------
Syntax
------
```
throw expression
```
`expression` The expression to throw.
Description
-----------
Use the `throw` statement to throw an exception. When you throw an exception, `expression` specifies the value of the exception. Each of the following throws an exception:
```
throw 'Error2'; // generates an exception with a string value
throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true
throw new Error('Required'); // generates an error object with the message of Required
```
Also note that the `throw` statement is affected by [automatic semicolon insertion (ASI)](../lexical_grammar#automatic_semicolon_insertion) as no line terminator between the `throw` keyword and the expression is allowed.
Examples
--------
### Throw an object
You can specify an object when you throw an exception. You can then reference the object's properties in the `catch` block. The following example creates an object of type `UserException` and uses it in a `throw` statement.
```
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
function getMonthName(mo) {
mo--; // Adjust month number for array index (1 = Jan, 12 = Dec)
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException('InvalidMonthNo');
}
}
let monthName;
try {
// statements to try
const myMonth = 15; // 15 is out of bound to raise the exception
monthName = getMonthName(myMonth);
} catch (e) {
monthName = 'unknown';
console.error(e.message, e.name); // pass exception object to err handler
}
```
### Another example of throwing an object
The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type `ZipCodeFormatException`.
```
/\*
\* Creates a ZipCode object.
\*
\* Accepted formats for a zip code are:
\* 12345
\* 12345-6789
\* 123456789
\* 12345 6789
\*
\* If the argument passed to the ZipCode constructor does not
\* conform to one of these patterns, an exception is thrown.
\*/
class ZipCode {
static pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
constructor(zip) {
zip = String(zip);
const match = zip.match(ZipCode.pattern);
if (!match) {
throw new ZipCodeFormatException(zip);
}
// zip code value will be the first match in the string
this.value = match[0];
}
valueOf() {
return this.value;
}
toString() {
return this.value;
}
}
class ZipCodeFormatException extends Error {
constructor(zip) {
super(`${zip} does not conform to the expected format for a zip code`);
}
}
/\*
\* This could be in a script that validates address data
\* for US addresses.
\*/
const ZIPCODE\_INVALID = -1;
const ZIPCODE\_UNKNOWN\_ERROR = -2;
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
const isInvalidCode = e instanceof ZipCodeFormatException;
return isInvalidCode ? ZIPCODE\_INVALID : ZIPCODE\_UNKNOWN\_ERROR;
}
return z;
}
a = verifyZipCode(95060); // returns 95060
b = verifyZipCode(9560); // returns -1
c = verifyZipCode('a'); // returns -1
d = verifyZipCode('95060'); // returns 95060
e = verifyZipCode('95060 1234'); // returns 95060 1234
```
### Rethrow an exception
You can use `throw` to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.
```
try {
throw n; // throws an exception with a numeric value
} catch (e) {
if (e <= 50) {
// statements to handle exceptions 1-50
} else {
// cannot handle this exception, so rethrow
throw e;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-throw-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-throw-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `throw` | 1 | 12 | 1 | 5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`try...catch`](try...catch)
* [`Error`](../global_objects/error)
| programming_docs |
javascript with with
====
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** Use of the `with` statement is not recommended, as it may be the source of confusing bugs and compatibility issues, makes optimization impossible, and is forbidden in [strict mode](../strict_mode). The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
The `with` statement extends the scope chain for a statement.
Syntax
------
```
with (expression)
statement
```
`expression` Adds the given expression to the scope chain used when evaluating the statement. The parentheses around the expression are required.
`statement` Any statement. To execute multiple statements, use a <block> statement (`{ ... }`) to group those statements.
Description
-----------
There are two types of identifiers: a *qualified* identifier and an *unqualified* identifier. An unqualified identifier is one that does not indicate where it comes from.
```
foo; // unqualified identifier
foo.bar; // bar is a qualified identifier
```
Normally, an unqualified identifier is resolved by searching the scope chain for a variable with that name, while a qualified identifier is resolved by searching the prototype chain of an object for a property with that name.
```
const foo = { bar: 1 };
console.log(foo.bar);
// foo is found in the scope chain as a variable;
// bar is found in foo as a property
```
One exception to this is the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object), which sits on top of the scope chain, and whose properties automatically become global variables that can be referred to without qualifiers.
```
console.log(globalThis.Math === Math); // true
```
The `with` statement adds the given object to the head of this scope chain during the evaluation of its statement body. Every unqualified name would first be searched within the object (through a [`in`](../operators/in) check) before searching in the upper scope chain.
Note that if the unqualified reference refers to a method of the object, the method is called with the object as its `this` value.
```
with ([1, 2, 3]) {
console.log(toString()); // 1,2,3
}
```
The object may have an [`@@unscopables`](../global_objects/symbol/unscopables) property, which defines a list of properties that should not be added to the scope chain (for backward compatibility). See the [`Symbol.unscopables`](../global_objects/symbol/unscopables) documentation for more information.
The reasons to use a `with` statement include saving one temporary variable and reducing file size by avoiding repeating a lengthy object reference. However, there are far more reasons why `with` statements are not desirable:
* Performance: The `with` statement forces the specified object to be searched first for all name lookups. Therefore, all identifiers that aren't members of the specified object will be found more slowly in a `with` block. Moreover, the optimizer cannot make any assumptions about what each unqualified identifier refers to, so it must repeat the same property lookup every time the identifier is used.
* Readability: The `with` statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. For example:
```
function f(x, o) {
with (o) {
console.log(x);
}
}
```
If you look just at the definition of `f`, it's impossible to tell what the `x` in the `with` body refers to. Only when `f` is called can `x` be determined to be `o.x` or `f`'s first formal parameter. If you forget to define `x` in the object you pass as the second parameter, you won't get an error — instead you'll just get unexpected results. It's also unclear what the actual intent of such code would be.
* Forward compatibility: Code using `with` may not be forward compatible, especially when used with something other than a plain object, which may gain more properties in the future. Consider this example:
```
function f(foo, values) {
with (foo) {
console.log(values);
}
}
```
If you call `f([1, 2, 3], obj)` in an ECMAScript 5 environment, the `values` reference inside the `with` statement will resolve to `obj`. However, ECMAScript 2015 introduces a [`values`](../global_objects/array/values) property on `Array.prototype` (so it will be available on every array). So, after upgrading the environment, the `values` reference inside the `with` statement resolves to `[1, 2, 3].values` instead, and is likely to cause bugs. In this particular example, `values` is defined as unscopable through [`Array.prototype[@@unscopables]`](../global_objects/array/@@unscopables), so it still correctly resolves to the `values` parameter. If it were not defined as unscopable, one can see how this would be a difficult issue to debug.
Examples
--------
### Using the with statement
The following `with` statement specifies that the [`Math`](../global_objects/math) object is the default object. The statements following the `with` statement refer to the [`PI`](../global_objects/math/pi) property and the [`cos`](../global_objects/math/cos) and [`sin`](../global_objects/math/sin) methods, without specifying an object. JavaScript assumes the `Math` object for these references.
```
let a, x, y;
const r = 10;
with (Math) {
a = PI \* r \* r;
x = r \* cos(PI);
y = r \* sin(PI / 2);
}
```
### Avoiding the with statement by destructuring properties into the current scope
You can usually avoid using `with` through [property destructuring](../operators/destructuring_assignment). Here we create an extra block to mimic the behavior of `with` creating an extra scope — but in actual usage, this block can usually be omitted.
```
let a, x, y;
const r = 10;
{
const { PI, cos, sin } = Math;
a = PI \* r \* r;
x = r \* cos(PI);
y = r \* sin(PI / 2);
}
```
### Creating dynamic namespaces using the with statement and a proxy
`with` will transform every variable lookup to a property lookup, while [Proxies](../global_objects/proxy) allow trapping every property lookup call. You can create a dynamic namespace by combining them.
```
const namespace = new Proxy(
{},
{
has(target, key) {
// Avoid trapping global properties like `console`
if (key in globalThis) {
return false;
}
// Trap all property lookups
return true;
},
get(target, key) {
return key;
},
}
);
with (namespace) {
console.log(a, b, c); // "a" "b" "c"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-with-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-with-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `with` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* <block>
* [Strict mode](../strict_mode)
* [`Symbol.unscopables`](../global_objects/symbol/unscopables)
* [`Array.prototype[@@unscopables]`](../global_objects/array/@@unscopables)
javascript continue continue
========
The `continue` statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
Try it
------
Syntax
------
```
continue;
continue label;
```
`label` Optional
Identifier associated with the label of the statement.
Description
-----------
In contrast to the [`break`](break) statement, `continue` does not terminate the execution of the loop entirely, but instead:
* In a [`while`](while) loop, it jumps back to the condition.
* In a [`for`](for) loop, it jumps to the update expression.
The `continue` statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. In this case, the `continue` statement needs to be nested within this labeled statement.
Examples
--------
### Using continue with while
The following example shows a [`while`](while) loop that has a `continue` statement that executes when the value of `i` is 3. Thus, `n` takes on the values 1, 3, 7, and 12.
```
let i = 0;
let n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
}
```
### Using continue with a label
In the following example, a statement labeled `checkiandj` contains a statement labeled `checkj`. If `continue` is encountered, the program continues at the top of the `checkj` statement. Each time `continue` is encountered, `checkj` reiterates until its condition returns false. When false is returned, the remainder of the `checkiandj` statement is completed.
If `continue` had a label of `checkiandj`, the program would continue at the top of the `checkiandj` statement.
See also <label>.
```
let i = 0;
let j = 8;
checkiandj: while (i < 4) {
console.log(`i: ${i}`);
i += 1;
checkj: while (j > 4) {
console.log(`j: ${j}`);
j -= 1;
if (j % 2 === 0) continue checkj;
console.log(`${j} is odd.`);
}
console.log(`i = ${i}`);
console.log(`j = ${j}`);
}
```
Output:
```
i: 0
// start checkj
j: 8
7 is odd.
j: 7
j: 6
5 is odd.
j: 5
// end checkj
i = 1
j = 4
i: 1
i = 2
j = 4
i: 2
i = 3
j = 4
i: 3
i = 4
j = 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-continue-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-continue-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `continue` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`break`](break)
* <label>
javascript label label
=====
The **labeled statement** can be used with [`break`](break) or [`continue`](continue) statements. It is prefixing a statement with an identifier which you can refer to.
Try it
------
Syntax
------
```
label:
statement
```
`label` Any JavaScript identifier that is not a reserved word.
`statement` A JavaScript statement. `break` can be used with any labeled statement, and `continue` can be used with looping labeled statements.
Description
-----------
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.
Note that JavaScript has *no* `goto` statement; you can only use labels with `break` or `continue`.
In [strict mode](../strict_mode) code, you can't use `let` as a label name. It will throw a [`SyntaxError`](../global_objects/syntaxerror) (let is a reserved identifier).
Examples
--------
### Using a labeled continue with for loops
```
let i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Logs:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
// i = 2, j = 0
// i = 2, j = 1
// i = 2, j = 2
```
Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2".
### Using a labeled continue statement
Given an array of items and an array of tests, this example counts the number of items that passes all the tests.
```
let itemsPassed = 0;
let i, j;
top:
for (i = 0; i < items.length; i++) {
for (j = 0; j < tests.length; j++) {
if (!tests[j].pass(items[i])) {
continue top;
}
}
itemsPassed++;
}
```
### Using a labeled break with for loops
```
let i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
break loop1;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Logs:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
```
Notice the difference with the previous `continue` example.
### Using a labeled break statement
Given an array of items and an array of tests, this example determines whether all items pass all tests.
```
let allPass = true;
let i, j;
top:
for (i = 0; i < items.length; i++) {
for (j = 0; j < tests.length; j++) {
if (!tests[j].pass(items[i])) {
allPass = false;
break top;
}
}
}
```
### Using a labeled block with break
You can use labels within simple blocks, but only `break` statements can make use of non-loop labels.
```
foo: {
console.log('face');
break foo;
console.log('this will not be executed');
}
console.log('swap');
// this will log:
// "face"
// "swap"
```
### Labeled function declarations
Labels can only be applied to [statements, not declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). Still, the [Annex B: Additional ECMAScript Features for Web Browsers](https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers) section defines a legacy grammar to standardize labeled function declarations in non-strict code.
```
L: function F() {}
```
In [strict mode](../strict_mode) code, however, this will throw a [`SyntaxError`](../global_objects/syntaxerror):
```
'use strict';
L: function F() {}
// SyntaxError: functions cannot be labelled
```
[Generator functions](function*) can neither be labeled in strict code, nor in non-strict code:
```
L: function\* F() {}
// SyntaxError: generator functions cannot be labelled
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-labelled-statements](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-labelled-statements) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `label` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`break`](break)
* [`continue`](continue)
javascript let let
===
The `let` declaration declares a block-scoped local variable, optionally initializing it to a value.
Try it
------
Syntax
------
```
let name1 [= value1] [, name2 [= value2]] [, ..., nameN [= valueN]
```
### Parameters
`nameN` The names of the variable or variables to declare. Each must be a legal JavaScript identifier.
`valueN` Optional
For each variable declared, you may optionally specify its initial value to any legal JavaScript expression.
Alternatively, the [Destructuring Assignment](../operators/destructuring_assignment) syntax can also be used to declare variables.
```
let { bar } = foo; // where foo = { bar:10, baz:12 };
/\* This creates a variable with the name 'bar', which has a value of 10 \*/
```
Description
-----------
`let` allows you to declare variables that are limited to the scope of a <block> statement, or expression on which it is used, unlike the [`var`](var) keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between [`var`](var) and `let` is that the latter can only be accessed after its declaration is reached (see [temporal dead zone](#temporal_dead_zone_tdz)). For this reason, `let` declarations are commonly regarded as [non-hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting).
Just like [`const`](const#description) the `let` does *not* create properties of the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object when declared globally (in the top-most scope).
An explanation of why the name "**let**" was chosen can be found [here](https://stackoverflow.com/questions/37916940/why-was-the-name-let-chosen-for-block-scoped-variable-declarations-in-javascri).
Many issues with `let` variables can be avoided by declaring them at the top of the scope in which they are used (doing so may impact readability).
Unlike `var`, `let` begins [*declarations*, not *statements*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). That means you cannot use a lone `let` declaration as the body of a block (which makes sense, since there's no way to access the variable).
```
if (true) let a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
```
Examples
--------
### Scoping rules
Variables declared by `let` have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, `let` works very much like `var`. The main difference is that the scope of a `var` variable is the entire enclosing function:
```
function varTest() {
var x = 1;
{
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
```
At the top level of programs and functions, `let`, unlike `var`, does not create a property on the global object. For example:
```
var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
```
### Redeclarations
Redeclaring the same variable within the same function or block scope raises a [`SyntaxError`](../global_objects/syntaxerror).
```
if (x) {
let foo;
let foo; // SyntaxError thrown.
}
```
You may encounter errors in [`switch`](switch) statements because there is only one block.
```
let x = 1;
switch(x) {
case 0:
let foo;
break;
case 1:
let foo; // SyntaxError for redeclaration.
break;
}
```
A block nested inside a case clause will create a new block scoped lexical environment, avoiding the redeclaration errors shown above.
```
let x = 1;
switch(x) {
case 0: {
let foo;
break;
}
case 1: {
let foo;
break;
}
}
```
If you're experimenting in a REPL, such as the Firefox web console (**Tools** > **Web Developer** > **Web Console**), and you run two `let` declarations with the same name in two separate inputs, you may get the same re-declaration error. See further discussion of this issue in [bug 1580891](https://bugzilla.mozilla.org/show_bug.cgi?id=1580891). The Chrome console allows `let` re-declarations between different REPL inputs.
### Temporal dead zone (TDZ)
A `let` or `const` variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.
While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a [`ReferenceError`](../global_objects/referenceerror). The variable is initialized with a value when execution reaches the line of code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of `undefined`.
This differs from [`var`](var#var_hoisting) variables, which will return a value of `undefined` if they are accessed before they are declared. The code below demonstrates the different result when `let` and `var` are accessed in code before the line in which they are declared.
```
{ // TDZ starts at beginning of scope
console.log(bar); // undefined
console.log(foo); // ReferenceError
var bar = 1;
let foo = 2; // End of TDZ (for foo)
}
```
The term "temporal" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position). For example, the code below works because, even though the function that uses the `let` variable appears before the variable is declared, the function is *called* outside the TDZ.
```
{
// TDZ starts at beginning of scope
const func = () => console.log(letVar); // OK
// Within the TDZ letVar access throws `ReferenceError`
let letVar = 3; // End of TDZ (for letVar)
func(); // Called outside TDZ!
}
```
#### The TDZ and `typeof`
Using the `typeof` operator for a `let` variable in its TDZ will throw a [`ReferenceError`](../global_objects/referenceerror):
```
// results in a 'ReferenceError'
console.log(typeof i);
let i = 10;
```
This differs from using `typeof` for undeclared variables, and variables that hold a value of `undefined`:
```
// prints out 'undefined'
console.log(typeof undeclaredVariable);
```
#### TDZ combined with lexical scoping
The following code results in a `ReferenceError` at the line shown:
```
function test() {
var foo = 33;
if (foo) {
let foo = foo + 55; // ReferenceError
}
}
test();
```
The `if` block is evaluated because the outer `var foo` has a value. However due to lexical scoping this value is not available inside the block: the identifier `foo` *inside* the `if` block is the `let foo`. The expression `(foo + 55)` throws a `ReferenceError` because initialization of `let foo` has not completed — it is still in the temporal dead zone.
This phenomenon can be confusing in a situation like the following. The instruction `let n of n.a` is already inside the private scope of the for loop's block. So, the identifier `n.a` is resolved to the property '`a`' of the '`n`' object located in the first part of the instruction itself (`let n`).
This is still in the temporal dead zone as its declaration statement has not been reached and terminated.
```
function go(n) {
// n here is defined!
console.log(n); // { a: [1, 2, 3] }
for (let n of n.a) { // ReferenceError
console.log(n);
}
}
go({a: [1, 2, 3]});
```
### Other situations
When used inside a block, `let` limits the variable's scope to that block. Note the difference between `var`, whose scope is inside the function where it is declared.
```
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
```
However, this combination of `var` and `let` declaration below is a [`SyntaxError`](../global_objects/syntaxerror) due to `var` being hoisted to the top of the block. This results in an implicit re-declaration of the variable.
```
let x = 1;
{
var x = 2; // SyntaxError for re-declaration
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-let-and-const-declarations](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-let-and-const-declarations) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `let` | 49
41-49
[Strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) is required. | 14
12-14
In Edge 12 and 13, `let` within a `for` loop initializer does not create a separate variable for each loop iteration as defined by ES2015. Instead, it behaves as though the loop were wrapped in a scoping block with the `let` immediately before the loop. | 44
["Before Firefox 44, `let` is only available to code blocks in HTML wrapped in a `<script type=\"application/javascript;version=1.7\">` block (or higher version) and has different semantics (e.g. no temporal dead zone).", "Before Firefox 46, a `TypeError` is thrown on redeclaration instead of a `SyntaxError`.", "Firefox 54 adds support of `let` in workers."] | 11
In Internet Explorer, `let` within a `for` loop initializer does not create a separate variable for each loop iteration as defined by ES2015. Instead, it behaves as though the loop were wrapped in a scoping block with the `let` immediately before the loop. | 17 | 10 | 49
41-49
[Strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) is required. | 49
41-49
[Strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) is required. | 44
["Before Firefox 44, `let` is only available to code blocks in HTML wrapped in a `<script type=\"application/javascript;version=1.7\">` block (or higher version) and has different semantics (e.g. no temporal dead zone).", "Before Firefox 46, a `TypeError` is thrown on redeclaration instead of a `SyntaxError`.", "Firefox 54 adds support of `let` in workers."] | 18 | 10 | 5.0
4.0-5.0
[Strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) is required. | 1.0 | 6.0.0 |
See also
--------
* [`var`](var)
* [`const`](const)
* [Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)
* [ES6 In Depth: `let` and `const`](https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/)
* [Breaking changes in `let` and `const` in Firefox 44](https://blog.mozilla.org/addons/2015/10/14/breaking-changes-let-const-firefox-nightly-44/)
* [You Don't Know JS: Scope & Closures: Chapter 3: Function vs. Block Scope](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/scope%20%26%20closures/ch3.md)
* [StackOverflow: What is the Temporal Dead Zone](https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone/33198850)?
* [StackOverflow: What is the difference between using `let` and `var`?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var)
| programming_docs |
javascript while while
=====
The `while` statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
Try it
------
Syntax
------
```
while (condition)
statement
```
`condition` An expression evaluated before each pass through the loop. If this condition [evaluates to true](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), `statement` is executed. When condition [evaluates to false](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), execution continues with the statement after the `while` loop.
`statement` An optional statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a <block> statement (`{ /* ... */ }`) to group those statements.
Note: Use the [`break`](break) statement to stop a loop before `condition` evaluates to true.
Examples
--------
### Using while
The following `while` loop iterates as long as `n` is less than three.
```
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
```
Each iteration, the loop increments `n` and adds it 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.
### Using an assignment as a condition
In some cases, it can make sense to use an assignment as a condition — but when you do, there's a best-practice syntax you should know about and follow.
Consider the following example, which iterates over a document's comments, logging them to the console.
```
const iterator = document.createNodeIterator(
document,
NodeFilter.SHOW\_COMMENT,
);
let currentNode;
while (currentNode = iterator.nextNode()) {
console.log(currentNode.textContent.trim());
}
```
That's not completely a good-practice example, due to the following line specifically:
```
while (currentNode = iterator.nextNode()) {
```
The *effect* of that line is fine — in that, each time a comment node is found:
1. `iterator.nextNode()` returns that comment node, which gets assigned to `currentNode`.
2. The value of `currentNode = iterator.nextNode()` is therefore [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
3. So the `console.log()` call executes and the loop continues.
…and then, when there are no more comment nodes in the document:
1. `iterator.nextNode()` returns [null](../operators/null).
2. The value of `currentNode = iterator.nextNode()` is therefore also `null`, which is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
3. So the loop ends.
But although the code *works* as expected, the problem with that particular line is: conditions typically use [comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#comparison_operators) such as `===`, but the `=` in that line isn't a comparison operator — instead, it's an [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators). So that `=` *looks like* it's a typo for `===` — even though it's *not* actually a typo.
Therefore, in cases like that one, some [IDEs](https://en.wikipedia.org/wiki/Integrated_development_environment) and [code-linting tools](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain#code_linting_tools) such as ESLint and JSHint — in order to help you catch a possible typo so that you can fix it — will report a warning such as the following:
> Expected a conditional expression and instead saw an assignment.
>
>
But there's a best-practice way to avoid that warning: Make the code more-explicitly indicate it intends the condition to be whether the value of the `currentNode = iterator.nextNode()` assignment is truthy. And you do that minimally by putting additional parentheses as a [grouping operator](../operators/grouping) around the assignment:
```
const iterator = document.createNodeIterator(
document, NodeFilter.SHOW\_COMMENT);
let currentNode;
while ((currentNode = iterator.nextNode())) {
console.log(currentNode.textContent.trim());
}
```
But the real best practice is to go a step further and make the code even more clear — by adding a comparison operator to turn the condition into an explicit comparison:
```
const iterator = document.createNodeIterator(
document, NodeFilter.SHOW\_COMMENT);
let currentNode;
while ((currentNode = iterator.nextNode()) !== null) {
console.log(currentNode.textContent.trim());
}
```
Along with preventing any warnings in IDEs and code-linting tools, what that code is actually doing will be much more obvious to anybody coming along later who needs to read and understand it or modify it.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-while-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-while-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `while` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`do...while`](do...while)
* [`for`](for)
* [`break`](break)
* [`continue`](continue)
javascript if...else if...else
=========
The `if...else` statement executes a statement if a specified condition is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). If the condition is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), another statement in the optional `else` clause will be executed.
Try it
------
Syntax
------
```
if (condition)
statement1
// With an else clause
if (condition)
statement1
else
statement2
```
`condition` An expression that is considered to be either [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) or [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
`statement1` Statement that is executed if *condition* is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). Can be any statement, including further nested `if` statements. To execute multiple statements, use a <block> statement (`{ /* ... */ }`) to group those statements. To execute no statements, use an <empty> statement.
`statement2` Statement that is executed if `condition` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) and the `else` clause exists. Can be any statement, including block statements and further nested `if` statements.
Description
-----------
Multiple `if...else` statements can be nested to create an `else if` clause. Note that there is no `elseif` (in one word) keyword in JavaScript.
```
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
// …
else
statementN
```
To see how this works, this is how it would look if the nesting were properly indented:
```
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
statement3
// …
```
To execute multiple statements within a clause, use a block statement (`{ /* ... */ }`) to group those statements.
```
if (condition) {
statements1
} else {
statements2
}
```
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:
```
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
```
This code looks innocent — however, executing `checkValue(1, 3)` will log "a is not 1". This is because in the case of [dangling else](https://en.wikipedia.org/wiki/Dangling_else), the `else` clause will be connected to the closest `if` clause. Therefore, the code above, with proper indentation, would look like:
```
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
```
In general, it is a good practice to always use block statements, especially in code involving nested `if` statements.
```
function checkValue(a, b) {
if (a === 1) {
if (b === 2) {
console.log("a is 1 and b is 2");
}
} else {
console.log("a is not 1");
}
}
```
Do not confuse the primitive Boolean values `true` and `false` with truthiness or falsiness of the [`Boolean`](../global_objects/boolean) object. Any value that is not `false`, `undefined`, `null`, `0`, `-0`, `NaN`, or the empty string (`""`), and any object, including a Boolean object whose value is `false`, is considered [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) when used as the condition. For example:
```
const b = new Boolean(false);
if (b) // this condition is truthy
statement
```
Examples
--------
### Using if...else
```
if (cipherChar === fromChar) {
result += toChar;
x++;
} else {
result += clearChar;
}
```
### Using else if
Note that there is no `elseif` syntax in JavaScript. However, you can write it with a space between `else` and `if`:
```
if (x > 50) {
/\* do something \*/
} else if (x > 5) {
/\* do something \*/
} else {
/\* do something \*/
}
```
### Using an assignment as a condition
You should almost never have an `if...else` with an assignment like `x = y` as a condition:
```
if (x = y) {
/\* do something \*/
}
```
However, in the rare case you find yourself wanting to do something like that, the [`while`](while) documentation has a [Using an assignment as a condition](while#using_an_assignment_as_a_condition) section with an example showing a general best-practice syntax you should know about and follow.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-if-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-if-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `if...else` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`block`](block)
* [`switch`](switch)
* [Conditional operator](../operators/conditional_operator)
javascript class class
=====
The `class` declaration creates a new class with a given name using prototype-based inheritance.
Try it
------
You can also define a class using a [class expression](../operators/class), which allows redeclarations and omitting class names. Attempting to place **class declaration** in the same scope, under the same name, will throw a [`SyntaxError`](../global_objects/syntaxerror).
Syntax
------
```
class name [extends otherName] {
// class body
}
```
Description
-----------
The class body of a class declaration is executed in [strict mode](../strict_mode). The `constructor` method is optional.
Class declarations behave like [`let`](let) and [`const`](const) and are not [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) (unlike [function declarations](function)).
Examples
--------
### A simple class declaration
In the following example, we first define a class named `Rectangle`, then extend it to create a class named `FilledRectangle`.
Note that `super()`, used in the `constructor`, can only be used in constructors, and *must* be called *before* the `this` keyword can be used.
```
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;
}
}
```
### Attempting to declare a class twice
Re-declaring a class using the class declaration throws a [`SyntaxError`](../global_objects/syntaxerror).
```
class Foo {}
class Foo {} // Uncaught SyntaxError: Identifier 'Foo' has already been declared
```
The same error is thrown when a class has been defined before using the class expression.
```
let Foo = class {};
class Foo {} // Uncaught SyntaxError: Identifier 'Foo' has already been declared
```
If you're experimenting in a REPL, such as the Firefox web console (**Tools** > **Web Developer** > **Web Console**), and you run two class declarations with the same name in two separate inputs, you may get the same re-declaration error. See further discussion of this issue in [bug 1580891](https://bugzilla.mozilla.org/show_bug.cgi?id=1580891). The Chrome console allows class re-declarations between different REPL inputs.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-class-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `class` | 49
42-49
Strict mode is required. | 13 | 45 | No | 36
29-36
Strict mode is required. | 10.1 | 49
42-49
Strict mode is required. | 49
42-49
Strict mode is required. | 45 | 36
29-36
Strict mode is required. | 10.3 | 5.0
4.0-5.0
Strict mode is required. | 1.0 | 6.0.0 |
See also
--------
* [`function` declaration](function)
* [`class` expression](../operators/class)
* [Classes](../classes)
javascript async function async function
==============
The `async function` declaration declares an async function where the `await` keyword is permitted within the function body. The `async` and `await` keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
Async functions may also be defined [as expressions](../operators/async_function).
Try it
------
Syntax
------
```
async function name(param0) {
statements
}
async function name(param0, param1) {
statements
}
async function name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
### Parameters
`name` The function's name.
`param` Optional
The name of an argument to be passed to the function.
`statements` Optional
The statements comprising the body of the function. The `await` mechanism may be used.
### Return value
A [`Promise`](../global_objects/promise) which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.
Description
-----------
Async functions can contain zero or more [`await`](../operators/await) expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of `async` and `await` enables the use of ordinary `try` / `catch` blocks around asynchronous code.
**Note:** The `await` keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a [`SyntaxError`](../global_objects/syntaxerror).
`await` can be used on its own with [JavaScript modules.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)
**Note:** The purpose of `async`/`await` is to simplify the syntax necessary to consume promise-based APIs. The behavior of `async`/`await` is similar to combining [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) and promises.
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
For example, consider the following code:
```
async function foo() {
return 1;
}
```
It is similar to:
```
function foo() {
return Promise.resolve(1);
}
```
**Note:**
Even though the return value of an async function behaves as if it's wrapped in a `Promise.resolve`, they are not equivalent.
An async function will return a different *reference*, whereas `Promise.resolve` returns the same reference if the given value is a promise.
It can be a problem when you want to check the equality of a promise and a return value of an async function.
```
const p = new Promise((res, rej) => {
res(1);
});
async function asyncReturn() {
return p;
}
function basicReturn() {
return Promise.resolve(p);
}
console.log(p === basicReturn()); // true
console.log(p === asyncReturn()); // false
```
The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.
For example:
```
async function foo() {
await 1;
}
```
It is also equivalent to:
```
function foo() {
return Promise.resolve(1).then(() => undefined);
}
```
Code after each await expression can be thought of as existing in a `.then` callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain.
In the following example, we successively await two promises. Progress moves through function `foo` in three stages.
1. The first line of the body of function `foo` is executed synchronously, with the await expression configured with the pending promise. Progress through `foo` is then suspended and control is yielded back to the function that called `foo`.
2. Some time later, when the first promise has either been fulfilled or rejected, control moves back into `foo`. The result of the first promise fulfillment (if it was not rejected) is returned from the await expression. Here `1` is assigned to `result1`. Progress continues, and the second await expression is evaluated. Again, progress through `foo` is suspended and control is yielded.
3. Some time later, when the second promise has either been fulfilled or rejected, control re-enters `foo`. The result of the second promise resolution is returned from the second await expression. Here `2` is assigned to `result2`. Control moves to the return expression (if any). The default return value of `undefined` is returned as the resolution value of the current promise.
```
async function foo() {
const result1 = await new Promise((resolve) =>
setTimeout(() => resolve("1"))
);
const result2 = await new Promise((resolve) =>
setTimeout(() => resolve("2"))
);
}
foo();
```
Note how the promise chain is not built-up in one go. Instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. As a result, we must be mindful of error handling behavior when dealing with concurrent asynchronous operations.
For example, in the following code an unhandled promise rejection error will be thrown, even if a `.catch` handler has been configured further along the promise chain. This is because `p2` will not be "wired into" the promise chain until control returns from `p1`.
```
async function foo() {
const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000));
const p2 = new Promise((\_, reject) => setTimeout(() => reject("2"), 500));
const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead.
}
foo().catch(() => {}); // Attempt to swallow all errors...
```
`async function` declarations are [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope.
Examples
--------
### Async functions and execution order
```
function resolveAfter2Seconds() {
console.log("starting slow promise");
return new Promise((resolve) => {
setTimeout(() => {
resolve("slow");
console.log("slow promise is done");
}, 2000);
});
}
function resolveAfter1Second() {
console.log("starting fast promise");
return new Promise((resolve) => {
setTimeout(() => {
resolve("fast");
console.log("fast promise is done");
}, 1000);
});
}
async function sequentialStart() {
console.log("==SEQUENTIAL START==");
// 1. Execution gets here almost instantly
const slow = await resolveAfter2Seconds();
console.log(slow); // 2. this runs 2 seconds after 1.
const fast = await resolveAfter1Second();
console.log(fast); // 3. this runs 3 seconds after 1.
}
async function concurrentStart() {
console.log("==CONCURRENT START with await==");
const slow = resolveAfter2Seconds(); // starts timer immediately
const fast = resolveAfter1Second(); // starts timer immediately
// 1. Execution gets here almost instantly
console.log(await slow); // 2. this runs 2 seconds after 1.
console.log(await fast); // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}
function concurrentPromise() {
console.log("==CONCURRENT START with Promise.all==");
return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then(
(messages) => {
console.log(messages[0]); // slow
console.log(messages[1]); // fast
}
);
}
async function parallel() {
console.log("==PARALLEL with await Promise.all==");
// Start 2 "jobs" in parallel and wait for both of them to complete
await Promise.all([
(async () => console.log(await resolveAfter2Seconds()))(),
(async () => console.log(await resolveAfter1Second()))(),
]);
}
sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(concurrentPromise, 7000); // same as concurrentStart
// wait again
setTimeout(parallel, 10000); // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
```
#### await and parallelism
In `sequentialStart`, execution suspends 2 seconds for the first `await`, and then another second for the second `await`. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.
In `concurrentStart`, both timers are created and then `await`ed. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer. However, the `await` calls still run in series, which means the second `await` will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.
If you wish to safely perform two or more jobs in parallel, you must await a call to [`Promise.all`](../global_objects/promise/all), or [`Promise.allSettled`](../global_objects/promise/allsettled).
**Warning:** The functions `concurrentStart` and `concurrentPromise` are not functionally equivalent.
In `concurrentStart`, if promise `fast` rejects before promise `slow` is fulfilled, then an unhandled promise rejection error will be raised, regardless of whether the caller has configured a catch clause.
In `concurrentPromise`, `Promise.all` wires up the promise chain in one go, meaning that the operation will fail-fast regardless of the order of rejection of the promises, and the error will always occur within the configured promise chain, enabling it to be caught in the normal way.
### Rewriting a Promise chain with an async function
An API that returns a [`Promise`](../global_objects/promise) will result in a promise chain, and it splits the function into many parts. Consider the following code:
```
function getProcessedData(url) {
return downloadData(url) // returns a promise
.catch((e) => downloadFallbackData(url)) // returns a promise
.then((v) => processDataInWorker(v)); // returns a promise
}
```
it can be rewritten with a single async function as follows:
```
async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch (e) {
v = await downloadFallbackData(url);
}
return processDataInWorker(v);
}
```
Alternatively, you can chain the promise with `catch()`:
```
async function getProcessedData(url) {
const v = await downloadData(url).catch((e) => downloadFallbackData(url));
return processDataInWorker(v);
}
```
In the two rewritten versions, notice there is no `await` statement after the `return` keyword, although that would be valid too: The return value of an async function is implicitly wrapped in [`Promise.resolve`](../global_objects/promise/resolve) - if it's not already a promise itself (as in the examples).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `async_function` | 55 | 15 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
See also
--------
* [async function expression](../operators/async_function)
* [`AsyncFunction`](../global_objects/asyncfunction) object
* [`await`](../operators/await)
* [Decorating Async JavaScript Functions](https://innolitics.com/10x/javascript-decorators-for-promise-returning-functions/) on *innolitics.com*
| programming_docs |
javascript for...in for...in
========
The `for...in` statement iterates over all [enumerable string properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of an object (ignoring properties keyed by [symbols](../global_objects/symbol)), including inherited enumerable properties.
Try it
------
Syntax
------
```
for (variable in object)
statement
```
### Parameters
`variable` Receives a string property name on each iteration. May be either a declaration with [`const`](const), [`let`](let), or [`var`](var), or an [assignment](../operators/assignment) target (e.g. a previously declared variable or an object property).
`object` Object whose non-symbol enumerable properties are iterated over.
`statement` A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](block) to execute multiple statements.
Description
-----------
The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).
A `for...in` loop only iterates over enumerable, non-symbol properties. Objects created from built–in constructors like `Array` and `Object` have inherited non–enumerable properties from `Array.prototype` and `Object.prototype`, such as [`Array`](../global_objects/array)'s [`indexOf()`](../global_objects/array/indexof) method or [`Object`](../global_objects/object)'s [`toString()`](../global_objects/object/tostring) method, which will not be visited in the `for...in` loop.
The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.
The `variable` part of `for...in` accepts anything that can come before the `=` operator. You can use [`const`](const) to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use [`let`](let). You can use [destructuring](../operators/destructuring_assignment) or an object property like `for (x.y in iterable)` as well.
A [legacy syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#statements) allows `var` declarations of the loop variable to have an initializer. This throws a [syntax error](../errors/invalid_for-in_initializer) in strict mode and is ignored in non–strict mode.
### Deleted, added, or modified properties
If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. A property that is deleted before it has been visited will not be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration.
In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.
### Array iteration and for...in
Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. The `for...in` loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of `for...in` close to normal array iteration. However, the `for...in` loop will return all enumerable properties, including those with non–integer names and those that are inherited. Unlike `for...of`, `for...in` uses property enumeration instead of the array's iterator. In [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), `for...of` will visit the empty slots, but `for...in` will not.
It is better to use a [`for`](for) loop with a numeric index, [`Array.prototype.forEach()`](../global_objects/array/foreach), or the [`for...of`](for...of) loop, because they will return the index as a number instead of a string, and also avoid non-index properties.
### Iterating over own properties only
If you only want to consider properties attached to the object itself, and not its prototypes, you can use one of the following techniques:
* [`Object.keys(myObject)`](../global_objects/object/keys)
* [`Object.getOwnPropertyNames(myObject)`](../global_objects/object/getownpropertynames)
`Object.keys` will return a list of enumerable own string properties, while `Object.getOwnPropertyNames` will also contain non-enumerable ones.
Many JavaScript style guides and linters recommend against the use of `for...in`, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used `for...of` loop. `for...in` is most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). In situations where objects are used as ad hoc key-value pairs, `for...in` allows you check if any of those keys hold a particular value.
Examples
--------
### Using for...in
The `for...in` loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.
```
const obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Logs:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
```
### Iterating own properties
The following function illustrates the use of [`Object.hasOwn()`](../global_objects/object/hasown): the inherited properties are not displayed.
```
const triangle = { a: 1, b: 2, c: 3 };
function ColoredTriangle() {
this.color = "red";
}
ColoredTriangle.prototype = triangle;
const obj = new ColoredTriangle();
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
}
// Logs:
// "obj.color = red"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-for-in-and-for-of-statements](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-for-in-and-for-of-statements) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `for...in` | 1 | 12 | 1 | 3 | 2 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`for...of`](for...of)
* [`for`](for)
* [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
* [`Object.getOwnPropertyNames()`](../global_objects/object/getownpropertynames)
* [`Object.hasOwn()`](../global_objects/object/hasown)
* [`Array.prototype.forEach()`](../global_objects/array/foreach)
javascript var var
===
The `var` statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
Try it
------
Syntax
------
```
var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]]
```
`varnameN` Variable name. It can be any legal identifier.
`valueN` Optional
Initial value of the variable. It can be any legal expression. Default value is `undefined`.
Alternatively, the [Destructuring Assignment](../operators/destructuring_assignment) syntax can also be used to declare variables.
```
var { bar } = foo; // where foo = { bar:10, baz:12 };
/\* This creates a variable with the name 'bar', which has a value of 10 \*/
```
Description
-----------
`var` declarations, wherever they occur, are processed before any code is executed. This is called [hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) and is discussed further below.
The scope of a variable declared with `var` is its current *execution context and closures thereof*, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variable declarations using `var` will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
```
'use strict';
function foo() {
var x = 1;
function bar() {
var y = 2;
console.log(x); // 1 (function `bar` closes over `x`)
console.log(y); // 2 (`y` is in scope)
}
bar();
console.log(x); // 1 (`x` is in scope)
console.log(y); // ReferenceError in strict mode, `y` is scoped to `bar`
}
foo();
```
Variables declared using `var` are created before any code is executed in a process known as [hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting). Their initial value is `undefined`.
```
'use strict';
console.log(x); // undefined (note: not ReferenceError)
console.log('still going...'); // still going...
var x = 1;
console.log(x); // 1
console.log('still going...'); // still going...
```
In the global context, a variable declared using `var` is added as a non-configurable property of the global object. This means its property descriptor cannot be changed and it cannot be deleted using [`delete`](../operators/delete). The corresponding name is also added to a list on the internal `[[VarNames]]` slot on the [global environment record](https://tc39.es/ecma262/#sec-global-environment-records) (which forms part of the global lexical environment). The list of names in `[[VarNames]]` enables the runtime to distinguish between global variables and straightforward properties on the global object.
The property created on the global object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object. JavaScript has automatic memory management, and it would make no sense to be able to use the `delete` operator on a global variable.
```
'use strict';
var x = 1;
Object.hasOwn(globalThis, 'x'); // true
delete globalThis.x; // TypeError in strict mode. Fails silently otherwise.
delete x; // SyntaxError in strict mode. Fails silently otherwise.
```
Note that in both NodeJS [CommonJS](https://www.commonjs.org/) modules and native [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object.
### Unqualified identifier assignments
The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with `globalThis.` or `window.` or `global.`.
Because the global object has a `String` property (`Object.hasOwn(globalThis, 'String')`), you can use the following code:
```
function foo() {
String('s') // Note the function `String` is implicitly visible
}
```
So the global object will ultimately be searched for unqualified identifiers. You don't have to type `globalThis.String`, you can just type the unqualified `String`. The corollary, in non-strict mode, is that assignment to unqualified identifiers will, if there is no variable of the same name declared in the scope chain, assume you want to create a property with that name on the global object.
```
foo = 'f' // In non-strict mode, assumes you want to create a property named `foo` on the global object
Object.hasOwn(globalThis, 'foo') // true
```
In [strict mode](../strict_mode), assignment to an unqualified identifier in strict mode will result in a `ReferenceError`, to avoid the accidental creation of properties on the global object.
Note that the implication of the above, is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables, it merely has a syntax that looks like it does.
### var hoisting
Because `var` declarations are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called [*hoisting*](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting), as it appears that the variable declaration is moved to the top of the function or global code.
```
bla = 2;
var bla;
```
This is implicitly understood as:
```
var bla;
bla = 2;
```
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.
It's important to point out that only a variable's declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached. Until then the variable remains `undefined` (but declared):
```
function do\_something() {
console.log(bar); // undefined
var bar = 111;
console.log(bar); // 111
}
```
This is implicitly understood as:
```
function do\_something() {
var bar;
console.log(bar); // undefined
bar = 111;
console.log(bar); // 111
}
```
Examples
--------
### Declaring and initializing two variables
```
var a = 0, b = 0;
```
### Assigning two variables with single string value
```
var a = 'A';
var b = a;
```
This is equivalent to:
```
var a, b = a = 'A';
```
Be mindful of the order:
```
var x = y, y = 'A';
console.log(x + y); // undefinedA
```
Here, `x` and `y` are declared before any code is executed, but the assignments occur later. At the time `x = y` is evaluated, `y` exists so no `ReferenceError` is thrown and its value is `undefined`. So, `x` is assigned the undefined value. Then, `y` is assigned the value `'A'`. Consequently, after the first line, `x === undefined && y === 'A'`, hence the result.
### Initialization of several variables
```
var x = 0;
function f() {
var x = y = 1; // Declares x locally; declares y globally.
}
f();
console.log(x, y); // 0 1
// In non-strict mode:
// x is the global one as expected;
// y is leaked outside of the function, though!
```
The same example as above but with a strict mode:
```
'use strict';
var x = 0;
function f() {
var x = y = 1; // Throws a ReferenceError in strict mode.
}
f();
console.log(x, y);
```
### Implicit globals and outer function scope
Variables that appear to be implicit globals may be references to variables in an outer function scope:
```
var x = 0; // Declares x within file scope, then assigns it a value of 0.
console.log(typeof z); // "undefined", since z doesn't exist yet
function a() {
var y = 2; // Declares y within scope of function a, then assigns it a value of 2.
console.log(x, y); // 0 2
function b() {
x = 3; // Assigns 3 to existing file scoped x.
y = 4; // Assigns 4 to existing outer y.
z = 5; // Creates a new global variable z, and assigns it a value of 5.
// (Throws a ReferenceError in strict mode.)
}
b(); // Creates z as a global variable.
console.log(x, y, z); // 3 4 5
}
a(); // Also calls b.
console.log(x, z); // 3 5
console.log(typeof y); // "undefined", as y is local to function a
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-variable-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-variable-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `var` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`let`](let)
* [`const`](const)
javascript try...catch try...catch
===========
The `try...catch` statement is comprised of a `try` block and either a `catch` block, a `finally` block, or both. The code in the `try` block is executed first, and if it throws an exception, the code in the `catch` block will be executed. The code in the `finally` block will always be executed before control flow exits the entire construct.
Try it
------
Syntax
------
```
try {
tryStatements
} catch (exceptionVar) {
catchStatements
} finally {
finallyStatements
}
```
`tryStatements` The statements to be executed.
`catchStatements` Statement that is executed if an exception is thrown in the `try`-block.
`exceptionVar` Optional
An optional identifier to hold the caught exception for the associated `catch` block. If the `catch` block does not utilize the exception's value, you can omit the `exceptionVar` and its surrounding parentheses, as `catch {...}`.
`finallyStatements` Statements that are executed before control flow exits the `try...catch...finally` construct. These statements execute regardless of whether an exception was thrown or caught.
Description
-----------
The `try` statement always starts with a `try` block. Then, a `catch` block or a `finally` block must be present. It's also possible to have both `catch` and `finally` blocks. This gives us three forms for the `try` statement:
* `try...catch`
* `try...finally`
* `try...catch...finally`
Unlike other constructs such as [`if`](if...else) or [`for`](for), the `try`, `catch`, and `finally` blocks must be *blocks*, instead of single statements.
```
try doSomething(); // SyntaxError
catch (e) console.log(e);
```
A `catch`-block contains statements that specify what to do if an exception is thrown in the `try`-block. If any statement within the `try`-block (or in a function called from within the `try`-block) throws an exception, control is immediately shifted to the `catch`-block. If no exception is thrown in the `try`-block, the `catch`-block is skipped.
The `finally` block will always execute before control flow exits the `try...catch...finally` construct. It always executes, regardless of whether an exception was thrown or caught.
You can nest one or more `try` statements. If an inner `try` statement does not have a `catch`-block, the enclosing `try` statement's `catch`-block is used instead.
You can also use the `try` statement to handle JavaScript exceptions. See the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide) for more information on JavaScript exceptions.
### Unconditional catch-block
When a `catch`-block is used, the `catch`-block is executed when any exception is thrown from within the `try`-block. For example, when the exception occurs in the following code, control transfers to the `catch`-block.
```
try {
throw "myException"; // generates an exception
} catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
```
The `catch`-block specifies an identifier (`e` in the example above) that holds the value of the exception; this value is only available in the [scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope) of the `catch`-block.
### Conditional catch-blocks
You can create "Conditional `catch`-blocks" by combining `try...catch` blocks with `if...else if...else` structures, like this:
```
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
```
A common use case for this is to only catch (and silence) a small subset of expected errors, and then re-throw the error in other cases:
```
try {
myRoutine();
} catch (e) {
if (e instanceof RangeError) {
// statements to handle this very common expected error
} else {
throw e; // re-throw the error unchanged
}
}
```
### The exception identifier
When an exception is thrown in the `try`-block, `exception_var` (i.e., the `e` in `catch (e)`) holds the exception value. You can use this identifier to get information about the exception that was thrown. This identifier is only available in the `catch`-block's [scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope). If you don't need the exception value, it could be omitted.
```
function isValidJSON(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
```
### The finally-block
The `finally` block contains statements to execute after the `try` block and `catch` block(s) execute, but before the statements following the `try...catch...finally` block. Control flow will always enter the `finally` block, which can proceed in one of the following ways:
* Immediately before the `try` block finishes execution normally (and no exceptions were thrown);
* Immediately before the `catch` block finishes execution normally;
* Immediately before a control-flow statement (`return`, `throw`, `break`, `continue`) is executed in the `try` block or `catch` block.
If an exception is thrown from the `try` block, even when there's no `catch` block to handle the exception, the `finally` block still executes, in which case the exception is still thrown immediately after the `finally` block finishes executing.
The following example shows one use case for the `finally`-block. The code opens a file and then executes statements that use the file; the `finally`-block makes sure the file always closes after it is used even if an exception was thrown.
```
openMyFile();
try {
// tie up a resource
writeMyFile(theData);
} finally {
closeMyFile(); // always close the resource
}
```
Control flow statements (`return`, `throw`, `break`, `continue`) in the `finally` block will "mask" any completion value of the `try` block or `catch` block. In this example, the `try` block tries to return 1, but before returning, the control flow is yielded to the `finally` block first, so the `finally` block's return value is returned instead.
```
function doIt() {
try {
return 1;
} finally {
return 2;
}
}
doIt(); // returns 2
```
It is generally a bad idea to have control flow statements in the `finally` block. Only use it for cleanup code.
Examples
--------
### Nested try-blocks
First, let's see what happens with this:
```
try {
try {
throw new Error("oops");
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "finally"
// "outer" "oops"
```
Now, if we already caught the exception in the inner `try`-block by adding a `catch`-block:
```
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "inner" "oops"
// "finally"
```
And now, let's rethrow the error.
```
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
throw ex;
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "inner" "oops"
// "finally"
// "outer" "oops"
```
Any given exception will be caught only once by the nearest enclosing `catch`-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in `catch`-block may do something that throws), will be caught by the "outer" block.
### Returning from a finally-block
If the `finally`-block returns a value, this value becomes the return value of the entire `try-catch-finally` statement, regardless of any `return` statements in the `try` and `catch`-blocks. This includes exceptions thrown inside of the `catch`-block:
```
(() => {
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
throw ex;
} finally {
console.log("finally");
return;
}
} catch (ex) {
console.error("outer", ex.message);
}
})();
// Logs:
// "inner" "oops"
// "finally"
```
The outer "oops" is not thrown because of the return in the `finally`-block. The same would apply to any value returned from the `catch`-block.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-try-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-try-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `try...catch` | 1 | 12 | 1 | 5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `optional_catch_binding` | 66 | 79 | 58 | No | 53 | 11.1 | 66 | 66 | 58 | 47 | 11.3 | 9.0 | 1.0 | 10.0.0 |
See also
--------
* [`Error`](../global_objects/error)
* [`throw`](throw)
| programming_docs |
javascript import import
======
The static `import` declaration is used to import read-only live bindings which are [exported](export) by another module. The imported bindings are called *live bindings* because they are updated by the module that exported the binding, but cannot be modified by the importing module.
In order to use the `import` declaration in a source file, the file must be interpreted by the runtime as a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). In HTML, this is done by adding `type="module"` to the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) tag. Modules are automatically interpreted in [strict mode](../strict_mode).
There is also a function-like dynamic [`import()`](../operators/import), which does not require scripts of `type="module"`.
Syntax
------
```
import defaultExport from "module-name";
import \* as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { default as alias } from "module-name";
import { export1, export2 } from "module-name";
import { export1, export2 as alias2, /\* … \*/ } from "module-name";
import { "string name" as alias } from "module-name";
import defaultExport, { export1, /\* … \*/ } from "module-name";
import defaultExport, \* as name from "module-name";
import "module-name";
```
`defaultExport` Name that will refer to the default export from the module. Must be a valid JavaScript identifier.
`module-name` The module to import from. The evaluation of the specifier is host-specified. This is often a relative or absolute URL to the `.js` file containing the module. In Node, extension-less imports often refer to packages in `node_modules`. Certain bundlers may permit importing files without extensions; check your environment. Only single quoted and double quoted Strings are allowed.
`name` Name of the module object that will be used as a kind of namespace when referring to the imports. Must be a valid JavaScript identifier.
`exportN` Name of the exports to be imported. The name can be either an identifier or a string literal, depending on what `module-name` declares to export. If it is a string literal, it must be aliased to a valid identifier.
`aliasN` Names that will refer to the named imports. Must be a valid JavaScript identifier.
Description
-----------
`import` declarations can only be present in modules, and only at the top-level (i.e. not inside blocks, functions, etc.). If an `import` declaration is encountered in non-module contexts (for example, `<script>` tags without `type="module"`, `eval`, `new Function`, which all have "script" or "function body" as parsing goals), a `SyntaxError` is thrown. To load modules in non-module contexts, use the [dynamic import](../operators/import) syntax instead.
`import` declarations are designed to be syntactically rigid (for example, only string literal specifiers, only permitted at the top-level, all bindings must be identifiers), which allows modules to be statically analyzed and linked before getting evaluated. This is the key to making modules asynchronous by nature, powering features like [top-level await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#top_level_await).
There are four forms of `import` declarations:
* [Named import](#named_import): `import { export1, export2 } from "module-name";`
* [Default import](#default_import): `import defaultExport from "module-name";`
* [Namespace import](#namespace_import): `import * as name from "module-name";`
* [Side effect import](#import_a_module_for_its_side_effects_only): `import "module-name";`
Below are examples to clarify the syntax.
### Named import
Given a value named `myExport` which has been exported from the module `my-module` either implicitly as `export * from 'another.js'`) or explicitly using the [`export`](export) statement, this inserts `myExport` into the current scope.
```
import { myExport } from "/modules/my-module.js";
```
You can import multiple names from the same module.
```
import { foo, bar } from "/modules/my-module.js";
```
You can rename an export when importing it. For example, this inserts `shortName` into the current scope.
```
import { reallyReallyLongModuleExportName as shortName } from "/modules/my-module.js";
```
A module may also export a member as a string literal which is not a valid identifier, in which case you must alias it in order to use it in the current module.
```
// /modules/my-module.js
const a = 1;
export { a as "a-b" };
```
```
import { "a-b" as a } from "/modules/my-module.js";
```
**Note:** `import { x, y } from "mod"` is not equivalent to `import defaultExport from "mod"` and then destructuring `x` and `y` from `defaultExport`. Named and default imports are distinct syntaxes in JavaScript modules.
### Default import
Default exports need to be imported with the corresponding default import syntax. The simplest version directly imports the default:
```
import myDefault from "/modules/my-module.js";
```
Since the default export doesn't explicitly specify a name, you can give the identifier any name you like.
It is also possible to specify a default import with namespace imports or named imports. In such cases, the default import will have to be declared first. For instance:
```
import myDefault, \* as myModule from "/modules/my-module.js";
// myModule.default and myDefault point to the same binding
```
or
```
import myDefault, { foo, bar } from "/modules/my-module.js";
```
Importing a name called `default` has the same effect as a default import. It is necessary to alias the name because `default` is a reserved word.
```
import { default as myDefault } from "/modules/my-module.js";
```
### Namespace import
The following code inserts `myModule` into the current scope, containing all the exports from the module located at `/modules/my-module.js`.
```
import \* as myModule from "/modules/my-module.js";
```
Here, `myModule` represents a *namespace* object which contains all exports as properties. For example, if the module imported above includes an export `doAllTheAmazingThings()`, you would call it like this:
```
myModule.doAllTheAmazingThings();
```
`myModule` is a [sealed](../global_objects/object/issealed) object with [`null` prototype](../global_objects/object#null-prototype_objects). All keys are [enumerable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) in lexicographic order (i.e. the default behavior of [`Array.prototype.sort()`](../global_objects/array/sort#description)), with the default export available as a key called `default`.
**Note:** JavaScript does not have wildcard imports like `import * from "module-name"`, because of the high possibility of name conflicts.
### Import a module for its side effects only
Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.
```
import "/modules/my-module.js";
```
This is often used for [polyfills](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill), which mutate the global variables.
Examples
--------
### Standard Import
In this example, we create a re-usable module that exports a function to get all primes within a given range.
```
// getPrimes.js
/\*\*
\* Returns a list of prime numbers that are smaller than `max`.
\*/
export function getPrimes(max) {
const isPrime = Array.from({ length: max }, () => true);
isPrime[0] = isPrime[1] = false;
isPrime[2] = true;
for (let i = 2; i \* i < max; i++) {
if (isPrime[i]) {
for (let j = i \*\* 2; j < max; j += i) {
isPrime[j] = false;
}
}
}
return [...isPrime.entries()]
.filter(([, isPrime]) => isPrime)
.map(([number]) => number);
}
```
```
import { getPrimes } from "/modules/getPrimes.js";
console.log(getPrimes(10)); // [2, 3, 5, 7]
```
### Imported values can only be modified by the exporter
The identifier being imported is a *live binding*, because the module exporting it may mutate it and the imported value would change. However, the module importing it cannot re-assign it.
```
// my-module.js
export let myValue = 1;
setTimeout(() => {
myValue = 2;
}, 500);
```
```
// main.js
import { myValue } from "/modules/my-module.js";
console.log(myValue); // 1
setTimeout(() => {
console.log(myValue); // 2; my-module has updated its value
myValue = 3; // TypeError: Assignment to constant variable.
// The importing module can only read the value but can't re-assign it.
}, 1000);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-imports](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-imports) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `import` | 61 | 16 | 60 | No | 48 | 10.1 | 61 | 61 | 60 | 45 | 10.3 | 8.0 | 1.0 | 13.2.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_enabling) for more details.
12.0.0-13.2.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_enabling) for more details.
8.5.0-12.0.0
Module filenames must end with `.mjs`, not `.js`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v8.x/api/esm.html#esm_enabling) for more details. |
| `import_assertions` | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | No | 15 | 91 | 91 | No
See [bug 1736059](https://bugzil.la/1736059). | No | 15 | 16.0 | 1.17 | 16.14.0
16.0.0-16.14.0 |
| `worker_support` | 80 | 80 | No
See [bug 1247687](https://bugzil.la/1247687). | No | No | 15 | 80 | 80 | No
See [bug 1247687](https://bugzil.la/1247687). | No | 15 | 13.0 | 1.0 | No |
See also
--------
* [`export`](export)
* [Dynamic imports](../operators/import)
* [`import.meta`](../operators/import.meta)
* Limin Zhu, Brian Terlson and Microsoft Edge Team: [Previewing ES6 Modules and more from ES2015, ES2016 and beyond](https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond/)
* Hacks blog post by Jason Orendorff: [ES6 in Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
* Hacks blog post by Lin Clark: [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)
* Axel Rauschmayer's book: ["Exploring JS: Modules"](https://exploringjs.com/es6/ch_modules.html)
* The Modern JavaScript Tutorial(javascript.info): [Export and Import](https://javascript.info/import-export)
javascript async function* async function\*
================
The `async function*` declaration defines an *async generator function*, which returns an [`AsyncGenerator`](../global_objects/asyncgenerator) object.
Try it
------
You can also define async generator functions using the [`AsyncGeneratorFunction`](../global_objects/asyncgeneratorfunction) constructor or the [`async function*` expression](../operators/async_function*) syntax.
Syntax
------
```
async function\* name(param0) {
statements
}
async function\* name(param0, param1) {
statements
}
async function\* name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
**Note:** Async generator functions do not have arrow function counterparts.
### Parameters
`name` The function name.
`param` Optional
The name of a formal parameter for the function.
`statements` Optional
The statements comprising the body of the function.
Description
-----------
An async generator function combines the features of [async functions](async_function) and [generator functions](function*). You can use both the [`await`](../operators/await) and [`yield`](../operators/yield) keywords within the function body. This empowers you to handle asynchronous tasks ergonomically with `await`, while leveraging the lazy nature of generator functions.
Unlike normal generator functions declared with `function*`, an async generator function return an [`AsyncGenerator`](../global_objects/asyncgenerator) object, which conforms to the [async iterable protocol](../iteration_protocols#the_async_iterator_and_async_iterable_protocols). Every call to `next()` returns a [`Promise`](../global_objects/promise) that resolves to the iterator result object.
When a promise is yielded from an async generator, the iterator result promise's eventual state will match that of the yielded promise. For example:
```
async function\* foo() {
yield Promise.reject(1);
}
foo()
.next()
.catch((e) => console.error(e));
```
`1` will be logged, because if the yielded promise rejects, the iterator result will reject as well. The `value` property of an async generator's resolved result will not be another promise.
`async function*` declarations are [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope.
Examples
--------
### Declaring an async generator function
Async generator functions always produce promises of results — even when each `yield` step is synchronous.
```
async function\* myGenerator(step) {
await new Promise((resolve) => setTimeout(resolve, 10));
yield 0;
yield step;
yield step \* 2;
}
const gen = myGenerator(2);
gen
.next()
.then((res) => {
console.log(res); // { value: 0, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: 2, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: 4, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: undefined, done: true }
return gen.next();
});
```
### Using an async generator function to read a series of files
In this example, we read a series of files and only access its content when requested, using Node's [`fs/promises`](https://nodejs.org/dist/latest-v18.x/docs/api/fs.html) module.
```
async function\* readFiles(directory) {
const files = await fs.readdir(directory);
for (const file of files) {
const stats = await fs.stat(file);
if (stats.isFile()) {
yield {
name: file,
content: await fs.readFile(file, "utf8"),
};
}
}
}
const files = readFiles(".");
console.log((await files.next()).value);
// Possible output: { name: 'file1.txt', content: '...' }
console.log((await files.next()).value);
// Possible output: { name: 'file2.txt', content: '...' }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-generator-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-async-generator-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `async_function*` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*`](../operators/async_function*) expression
* [`AsyncGeneratorFunction`](../global_objects/asyncgeneratorfunction) object
* [The Iterator protocol](../iteration_protocols)
* [`GeneratorFunction`](../global_objects/generatorfunction) object
* [`yield`](../operators/yield)
* [`yield*`](../operators/yield*)
* [`Function`](../global_objects/function) object
* [Functions](../functions)
javascript return return
======
The `return` statement ends function execution and specifies a value to be returned to the function caller.
Try it
------
Syntax
------
```
return [expression]
```
`expression` The expression whose value is to be returned. If omitted, `undefined` is returned instead.
Description
-----------
When a `return` statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, `x`, where `x` is a number.
```
function square(x) {
return x \* x;
}
const demo = square(3);
// demo will equal 9
```
If the value is omitted, `undefined` is returned instead.
The following return statements all break the function execution:
```
return;
return true;
return false;
return x;
return x + y / 3;
```
### Automatic Semicolon Insertion
The `return` statement is affected by [automatic semicolon insertion (ASI)](../lexical_grammar#automatic_semicolon_insertion). No line terminator is allowed between the `return` keyword and the expression.
```
return
a + b;
```
is transformed by ASI into:
```
return;
a + b;
```
The console will warn "unreachable code after return statement".
**Note:** Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a `return` statement.
To avoid this problem (to prevent ASI), you could use parentheses:
```
return (
a + b
);
```
Examples
--------
### Interrupt a function
A function immediately stops at the point where `return` is called.
```
function counter() {
for (let count = 1; ; count++) { // infinite loop
console.log(`${count}A`); // until 5
if (count === 5) {
return;
}
console.log(`${count}B`); // until 4
}
console.log(`${count}C`); // never appears
}
counter();
// Logs:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
```
### Returning a function
See also the article about [Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
```
function magic() {
return function calc(x) { return x \* 42; };
}
const answer = magic();
answer(1337); // 56154
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-return-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-return-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `return` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Functions](../functions)
* [Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
javascript for...of for...of
========
The `for...of` statement executes a loop that operates on a sequence of values sourced from an [iterable object](../iteration_protocols#the_iterable_protocol). Iterable objects include instances of built-ins such as [`Array`](../global_objects/array), [`String`](../global_objects/string), [`TypedArray`](../global_objects/typedarray), [`Map`](../global_objects/map), [`Set`](../global_objects/set), [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) (and other DOM collections), as well as the [`arguments`](../functions/arguments) object, [generators](../global_objects/generator) produced by [generator functions](function*), and user-defined iterables.
Try it
------
Syntax
------
```
for (variable of iterable)
statement
```
`variable` Receives a value from the sequence on each iteration. May be either a declaration with [`const`](const), [`let`](let), or [`var`](var), or an [assignment](../operators/assignment) target (e.g. a previously declared variable or an object property).
`iterable` An iterable object. The source of the sequence of values on which the loop operates.
`statement` A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](block) to execute multiple statements.
Description
-----------
A `for...of` loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an *iteration*, and the loop is said to *iterate over the iterable*. Each iteration executes statements that may refer to the current sequence value.
When a `for...of` loop iterates over an iterable, it first calls the iterable's [`[@@iterator]()`](../global_objects/symbol/iterator) method, which returns an [iterator](../iteration_protocols#the_iterator_protocol), and then repeatedly calls the resulting iterator's [`next()`](../iteration_protocols#the_iterator_protocol) method to produce the sequence of values to be assigned to `variable`.
A `for...of` loop exits when the iterator has completed (the iterator's `next()` method returns an object containing `done: true`). You may also use control flow statements to change the normal control flow. [`break`](break) exits the loop and goes to the first statement after the loop body, while [`continue`](continue) skips the rest of the statements of the current iteration and proceeds to the next iteration.
If the `for...of` loop exited early (e.g. a `break` statement is encountered or an error is thrown), the [`return()`](../iteration_protocols#the_iterator_protocol) method of the iterator is called to perform any cleanup.
The `variable` part of `for...of` accepts anything that can come before the `=` operator. You can use [`const`](const) to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use [`let`](let).
```
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
```
**Note:** Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).
You can use [destructuring](../operators/destructuring_assignment) or an object property like `for (x.y of iterable)` as well.
However, a special rule forbids using `async` as the variable name. This is invalid syntax:
```
let async;
for (async of [1, 2, 3]); // SyntaxError: The left-hand side of a for-of loop may not be 'async'.
```
This is to avoid syntax ambiguity with the valid code `for (async of => {};;)`, which is a [`for`](for) loop.
Examples
--------
### Iterating over an Array
```
const iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30
```
### Iterating over a string
Strings are [iterated by Unicode code points](../global_objects/string/@@iterator).
```
const iterable = "boo";
for (const value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
```
### Iterating over a TypedArray
```
const iterable = new Uint8Array([0x00, 0xff]);
for (const value of iterable) {
console.log(value);
}
// 0
// 255
```
### Iterating over a Map
```
const iterable = new Map([
["a", 1],
["b", 2],
["c", 3],
]);
for (const entry of iterable) {
console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (const [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over a Set
```
const iterable = new Set([1, 1, 2, 2, 3, 3]);
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over the arguments object
You can iterate over the [`arguments`](../functions/arguments) object to examine all parameters passed into a function.
```
function foo() {
for (const value of arguments) {
console.log(value);
}
}
foo(1, 2, 3);
// 1
// 2
// 3
```
### Iterating over a NodeList
The following example adds a `read` class to paragraphs that are direct descendants of the [`<article>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article) element by iterating over a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) DOM collection.
```
const articleParagraphs = document.querySelectorAll("article > p");
for (const paragraph of articleParagraphs) {
paragraph.classList.add("read");
}
```
### Iterating over a user-defined iterable
Iterating over an object with an `@@iterator` method that returns a custom iterator:
```
const iterable = {
[Symbol.iterator]() {
let i = 1;
return {
next() {
if (i <= 3) {
return { value: i++, done: false };
}
return { value: undefined, done: true };
},
};
},
};
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
Iterating over an object with an `@@iterator` generator method:
```
const iterable = {
\*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
*Iterable iterators* (iterators with a `[@@iterator]()` method that returns `this`) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such as `for...of`.
```
let i = 1;
const iterator = {
next() {
if (i <= 3) {
return { value: i++, done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
},
};
for (const value of iterator) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over a generator
```
function\* source() {
yield 1;
yield 2;
yield 3;
}
const generator = source();
for (const value of generator) {
console.log(value);
}
// 1
// 2
// 3
```
### Early exiting
Execution of the `break` statement in the first loop causes it to exit early. The iterator is not finished yet, so the second loop will continue from where the first one stopped at.
```
const source = [1, 2, 3];
const iterator = source[Symbol.iterator]();
for (const value of iterator) {
console.log(value);
if (value === 1) {
break;
}
console.log("This string will not be logged.");
}
// 1
// Another loop using the same iterator
// picks up where the last loop left off.
for (const value of iterator) {
console.log(value);
}
// 2
// 3
// The iterator is used up.
// This loop will execute no iterations.
for (const value of iterator) {
console.log(value);
}
// [No output]
```
Generators implement the [`return()`](../global_objects/generator/return) method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.
```
function\* source() {
yield 1;
yield 2;
yield 3;
}
const generator = source();
for (const value of generator) {
console.log(value);
if (value === 1) {
break;
}
console.log("This string will not be logged.");
}
// 1
// The generator is used up.
// This loop will execute no iterations.
for (const value of generator) {
console.log(value);
}
// [No output]
```
### Difference between for...of and for...in
Both `for...in` and `for...of` statements iterate over something. The main difference between them is in what they iterate over.
The [`for...in`](for...in) statement iterates over the [enumerable string properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of an object, while the `for...of` statement iterates over values that the [iterable object](../iteration_protocols#the_iterable_protocol) defines to be iterated over.
The following example shows the difference between a `for...of` loop and a `for...in` loop when used with an [`Array`](../global_objects/array).
```
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
const iterable = [3, 5, 7];
iterable.foo = "hello";
for (const i in iterable) {
console.log(i);
}
// "0", "1", "2", "foo", "arrCustom", "objCustom"
for (const i in iterable) {
if (Object.hasOwn(iterable, i)) {
console.log(i);
}
}
// "0" "1" "2" "foo"
for (const i of iterable) {
console.log(i);
}
// 3 5 7
```
The object `iterable` inherits the properties `objCustom` and `arrCustom` because it contains both `Object.prototype` and `Array.prototype` in its [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
The `for...in` loop logs only [enumerable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of the `iterable` object. It doesn't log array *elements* `3`, `5`, `7` or `"hello"` because those are not *properties* — they are *values*. It logs array *indexes* as well as `arrCustom` and `objCustom`, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of how [array iteration and `for...in`](for...in#array_iteration_and_for...in) work.
The second loop is similar to the first one, but it uses [`Object.hasOwn()`](../global_objects/object/hasown) to check if the found enumerable property is the object's own, i.e. not inherited. If it is, the property is logged. Properties `0`, `1`, `2` and `foo` are logged because they are own properties. Properties `arrCustom` and `objCustom` are not logged because they are inherited.
The `for...of` loop iterates and logs *values* that `iterable`, as an array (which is [iterable](../global_objects/array/@@iterator)), defines to be iterated over. The object's *elements* `3`, `5`, `7` are shown, but none of the object's *properties* are.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-for-in-and-for-of-statements](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-for-in-and-for-of-statements) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `for...of` | 38 | 12 | 13
Before Firefox 51, using the `for...of` loop construct with the `const` keyword threw a `SyntaxError` ("missing = in const declaration"). | No | 25 | 7 | 38 | 38 | 14
Before Firefox 51, using the `for...of` loop construct with the `const` keyword threw a `SyntaxError` ("missing = in const declaration"). | 25 | 7 | 3.0 | 1.0 | 0.12.0 |
| `async_iterators` | 63 | 12 | 57 | No | 50 | 7 | 63 | 63 | 57 | 46 | 7 | 8.0 | 1.0 | 10.0.0 |
| `closing_iterators` | 51 | 14 | 53 | No | 38 | 7 | 51 | 51 | 53 | 41 | 7 | 5.0 | 1.0 | 6.5.0 |
See also
--------
* [`Array.prototype.forEach()`](../global_objects/array/foreach)
* [`Map.prototype.forEach()`](../global_objects/map/foreach)
* [`Object.entries()`](../global_objects/object/entries) – Useful when using `for...of` over an object.
| programming_docs |
javascript Expression statement Expression statement
====================
An **expression statement** evaluates an expression and discards its result. It allows the expression to perform side effects, such as executing a function or updating a variable.
Syntax
------
```
expression;
```
`expression` An arbitrary [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) to be evaluated. There are [certain expressions](#forbidden_expressions) that may be ambiguous with other statements and are thus forbidden.
Description
-----------
Apart from the [dedicated statement syntaxes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements), you can also use almost any [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) as a statement on its own. The expression statement syntax requires a semicolon at the end, but the [automatic semicolon insertion](../lexical_grammar#automatic_semicolon_insertion) process may insert one for you if the lack of a semicolon results in invalid syntax.
Because the expression is evaluated and then discarded, the result of the expression is not available. Therefore, the expression must have some side effect for it to be useful. Expression statements are commonly:
* Function calls (`console.log("Hello");`, `[1, 2, 3].forEach((i) => console.log(i));`)
* [Tagged template literals](../template_literals#tagged_templates)
* [Assignment expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators), including compound assignments
* [Increment and decrement operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement)
* [`delete`](../operators/delete)
* [`import()`](../operators/import)
* [`yield`](../operators/yield) and [`yield*`](../operators/yield*)
Others may also have side effects if they invoke [getters](../functions/get) or trigger [type coercions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion).
### Forbidden expressions
In order for an expression to be used as a statement, it must not be ambiguous with other statement syntaxes. Therefore, the expression must not start with any of the following tokens:
* `function`: which would be a [`function` declaration](function) or [`function*` declaration](function*), not a [`function` expression](../operators/function) or [`function*` expression](../operators/function*)
* `async function`: which would be an [`async function` declaration](async_function) or [`async function*` declaration](async_function*), not an [`async function` expression](../operators/async_function) or [`async function*` expression](../operators/async_function*)
* `class`: which would be a [`class` declaration](class), not a [`class` expression](../operators/class)
* `let[`: which would be a [`let` declaration](let) with [array destructuring](../operators/destructuring_assignment), not a [property accessor](../operators/property_accessors) on a variable called `let` (`let` can only be an identifier in [non-strict mode](../strict_mode#extra_reserved_words))
* `{`: which would be a [block statement](block), not an [object literal](../operators/object_initializer)
Therefore, all of the following are invalid:
```
function foo() {
console.log("foo");
}(); // SyntaxError: Unexpected token '('
// For some reason, you have a variable called `let`
var let = [1, 2, 3];
let[0] = 4; // SyntaxError: Invalid destructuring assignment target
{
foo: 1,
bar: 2, // SyntaxError: Unexpected token ':'
};
```
More dangerously, sometimes the code happens to be valid syntax, but is not what you intend.
```
// For some reason, you have a variable called `let`
var let = [1, 2, 3];
function setIndex(index, value) {
if (index >= 0) {
// Intend to assign to the array `let`, but instead creates an extra variable!
let[index] = value;
}
}
setIndex(0, [1, 2]);
console.log(let); // [1, 2, 3]
// This is not an object literal, but a block statement,
// where `foo` is a label and `1` is an expression statement.
// This often happens in the console
{ foo: 1 };
```
To avoid these problems, you can use parentheses, so that the statement is unambiguously an expression statement.
```
(function foo() {
console.log("foo");
})();
```
Examples
--------
### Avoiding control flow statements
You can avoid almost all use of control flow statements using expression statements. For example, `if...else` can be replaced with [ternary operators](../operators/conditional_operator) and [logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#binary_logical_operators). Iterative statements like `for` or `for...of` can be replaced with [array methods](../global_objects/array#instance_methods).
```
// Using control flow statements
function range(start, end) {
if (start > end) {
[start, end] = [end, start];
}
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
}
// Using expression statements
function range2(start, end) {
start > end && ([start, end] = [end, start]);
return Array.from({ length: end - start }, (\_, i) => start + i);
}
```
**Warning:** This only demonstrates a capability of the language. Excessive use of expression statements as a substitute for control-flow statements can make code much less readable.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-expression-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-expression-statement) |
See also
--------
* [Statements and declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements)
* [Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators)
javascript export export
======
The `export` declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the [`import`](import) declaration or [dynamic import](../operators/import). The value of an imported binding is subject to change in the module that exports it — when a module updates the value of a binding that it exports, the update will be visible in its imported value.
In order to use the `export` declaration in a source file, the file must be interpreted by the runtime as a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). In HTML, this is done by adding `type="module"` to the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) tag, or by being imported by another module. Modules are automatically interpreted in [strict mode](../strict_mode).
Syntax
------
```
// Exporting declarations
export let name1, name2/\*, … \*/; // also var
export const name1 = 1, name2 = 2/\*, … \*/; // also var, let
export function functionName() { /\* … \*/ }
export class ClassName { /\* … \*/ }
export function\* generatorFunctionName() { /\* … \*/ }
export const { name1, name2: bar } = o;
export const [ name1, name2 ] = array;
// Export list
export { name1, /\* …, \*/ nameN };
export { variable1 as name1, variable2 as name2, /\* …, \*/ nameN };
export { variable1 as "string name" };
export { name1 as default /\*, … \*/ };
// Default exports
export default expression;
export default function functionName() { /\* … \*/ }
export default class ClassName { /\* … \*/ }
export default function\* generatorFunctionName() { /\* … \*/ }
export default function () { /\* … \*/ }
export default class { /\* … \*/ }
export default function\* () { /\* … \*/ }
// Aggregating modules
export \* from "module-name";
export \* as name1 from "module-name";
export { name1, /\* …, \*/ nameN } from "module-name";
export { import1 as name1, import2 as name2, /\* …, \*/ nameN } from "module-name";
export { default, /\* …, \*/ } from "module-name";
```
`nameN` Identifier to be exported (so that it can be imported via [`import`](import) in another script). If you use an alias with `as`, the actual exported name can be specified as a string literal, which may not be a valid identifier.
Description
-----------
Every module can have two different types of export, *named export* and *default export*. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.
Named exports:
```
// export features declared elsewhere
export { myFunction2, myVariable2 };
// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() { /\* ... \*/ };
```
After the `export` keyword, you can use `let`, `const`, and `var` declarations, as well as function or class declarations. You can also use the `export { name1, name2 }` syntax to export a list of names declared elsewhere. Note that `export {}` does not export an empty object — it's a no-op declaration that exports nothing (an empty name list).
Export declarations are not subject to [temporal dead zone](let#temporal_dead_zone_tdz) rules. You can declare that the module exports `X` before the name `X` itself is declared.
```
export { x };
const x = 1;
// This works, because `export` is only a declaration, but doesn't
// utilize the value of `x`.
```
Default exports:
```
// export feature declared elsewhere as default
export { myFunction as default };
// This is equivalent to:
export default myFunction;
// export individual features as default
export default function () { /\* … \*/ }
export default class { /\* … \*/ }
```
**Note:** Names for export declarations must be distinct from each other. Having exports with duplicate names or using more than one `default` export will result in a [`SyntaxError`](../global_objects/syntaxerror) and prevent the module from being evaluated.
The `export default` syntax allows any expression.
```
export default 1 + 1;
```
As a special case, functions and classes are exported as *declarations*, not expressions, and these declarations can be anonymous. This means functions will be hoisted.
```
// Works because `foo` is a function declaration,
// not a function expression
foo();
export default function foo() {
console.log("Hi");
}
// It's still technically a declaration, but it's allowed
// to be anonymous
export default function () {
console.log("Hi");
}
```
Named exports are useful when you need to export several values. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with `as`), but the default export can be imported with any name. For example:
```
// file test.js
const k = 12;
export default k;
```
```
// some other file
import m from './test'; // note that we have the freedom to use import m instead of import k, because k was default export
console.log(m); // will log 12
```
You can also rename named exports to avoid naming conflicts:
```
export {
myFunction as function1,
myVariable as variable,
};
```
You can rename a name to something that's not a valid identifier by using a string literal. For example:
```
export { myFunction as "my-function" };
```
### Re-exporting / Aggregating
A module can also "relay" values exported from other modules without the hassle of writing two separate import/export statements. This is often useful when creating a single module concentrating various exports from various modules (usually called a "barrel module").
This can be achieved with the "export from" syntax:
```
export {
default as function1,
function2,
} from 'bar.js';
```
Which is comparable to a combination of import and export, except that `function1` and `function2` do not become available inside the current module:
```
import { default as function1, function2 } from 'bar.js';
export { function1, function2 };
```
Most of the "import from" syntaxes have "export from" counterparts.
```
export { x } from "mod";
export { x as v } from "mod";
export \* as ns from "mod";
```
There is also `export * from "mod"`, although there's no `import * from "mod"`. This re-exports all **named** exports from `mod` as the named exports of the current module, but the default export of `mod` is not re-exported. If there are two wildcard exports statements that implicitly re-export the same name, neither one is re-exported.
```
// -- mod1.js --
export const a = 1;
// -- mod2.js --
export const a = 3;
// -- barrel.js --
export \* from "./mod1.js";
export \* from "./mod2.js";
// -- main.js --
import \* as ns from "./barrel.js";
console.log(ns.a); // undefined
```
Attempting to import the duplicate name directly will throw an error.
```
import { a } from "./barrel.js";
// SyntaxError: The requested module './barrel.js' contains conflicting star exports for name 'a'
```
The following is syntactically invalid despite its import equivalent:
```
export DefaultExport from 'bar.js'; // Invalid
```
The correct way of doing this is to rename the export:
```
export { default as DefaultExport } from 'bar.js';
```
The "export from" syntax allows the `as` token to be omitted, which makes the default export still re-exported as default export.
```
export { default, function2 } from 'bar.js';
```
Examples
--------
### Using named exports
In a module `my-module.js`, we could include the following code:
```
// module "my-module.js"
function cube(x) {
return x \* x \* x;
}
const foo = Math.PI + Math.SQRT2;
const graph = {
options: {
color: 'white',
thickness: '2px',
},
draw() {
console.log('From graph draw function');
}
};
export { cube, foo, graph };
```
Then in the top-level module included in your HTML page, we could have:
```
import { cube, foo, graph } from './my-module.js';
graph.options = {
color: 'blue',
thickness: '3px',
};
graph.draw();
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
```
It is important to note the following:
* You need to include this script in your HTML with a [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element of `type="module"`, so that it gets recognized as a module and dealt with appropriately.
* You can't run JS modules via a `file://` URL — you'll get [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) errors. You need to run it via an HTTP server.
### Using the default export
If we want to export a single value or to have a fallback value for your module, you could use a default export:
```
// module "my-module.js"
export default function cube(x) {
return x \* x \* x;
}
```
Then, in another script, it is straightforward to import the default export:
```
import cube from './my-module.js';
console.log(cube(3)); // 27
```
### Using export from
Let's take an example where we have the following hierarchy:
* `childModule1.js`: exporting `myFunction` and `myVariable`
* `childModule2.js`: exporting `MyClass`
* `parentModule.js`: acting as an aggregator (and doing nothing else)
* top level module: consuming the exports of `parentModule.js`
This is what it would look like using code snippets:
```
// In childModule1.js
function myFunction() {
console.log("Hello!");
}
const myVariable = 1;
export { myFunction, myVariable };
```
```
// In childModule2.js
class MyClass {
constructor(x) {
this.x = x;
}
}
export { MyClass };
```
```
// In parentModule.js
// Only aggregating the exports from childModule1 and childModule2
// to re-export them
export { myFunction, myVariable } from 'childModule1.js';
export { MyClass } from 'childModule2.js';
```
```
// In top-level module
// We can consume the exports from a single module since parentModule
// "collected"/"bundled" them in a single source
import { myFunction, myVariable, MyClass } from 'parentModule.js'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-exports](https://tc39.es/ecma262/multipage/ecmascript-language-scripts-and-modules.html#sec-exports) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `export` | 61 | 16 | 60 | No | 48 | 10.1 | 61 | 61 | 60 | 45 | 10.3 | 8.0 | 1.0 | 13.2.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_enabling) for more details.
12.0.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_enabling) for more details.
8.5.0
Module filenames must end with `.mjs`, not `.js`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v8.x/api/esm.html#esm_enabling) for more details. |
| `default` | 61 | 16 | 60 | No | 48 | 10.1 | No | 61 | 60 | 45 | 10.3 | 8.0 | 1.0 | 13.2.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_enabling) for more details.
12.0.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_enabling) for more details.
8.5.0
Module filenames must end with `.mjs`, not `.js`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v8.x/api/esm.html#esm_enabling) for more details. |
| `namespace` | 72 | 79 | 80 | No | 60 | 14.1 | No | 72 | 80 | 51 | 14.5 | 11.0 | 1.0 | 13.2.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/api/esm.html#esm_enabling) for more details.
12.0.0
Modules must either have a filename ending in `.mjs`, or the nearest parent `package.json` file must contain `"type": "module"`. See Node's [ECMAScript Modules documentation](https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_enabling) for more details. |
See also
--------
* [`import`](import)
* [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) guide
* [ES6 in Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/), Hacks blog post by Jason Orendorff
* [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/), Hacks blog post by Lin Clark
* [Axel Rauschmayer's book: "Exploring JS: Modules"](https://exploringjs.com/es6/ch_modules.html)
javascript break break
=====
The `break` statement terminates the current loop, [`switch`](switch), or <label> statement and transfers program control to the statement following the terminated statement.
Try it
------
Syntax
------
```
break;
break label;
```
`label` Optional
Identifier associated with the label of the statement. If the statement is not a loop or [`switch`](switch), this is required.
Description
-----------
The `break` statement includes an optional label that allows the program to break out of a labeled statement. The `break` statement needs to be nested within the referenced label. The labeled statement can be any <block> statement; it does not have to be preceded by a loop statement.
A `break` statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the `break` statement is intended to break out of.
Examples
--------
### break in while loop
The following function has a `break` statement that terminates the [`while`](while) loop when `i` is 3, and then returns the value 3 \* `x`.
```
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i += 1;
}
return i \* x;
}
```
### break in switch statements
The following code has a `break` statement that terminates the [`switch`](switch) statement when a case is matched and the corresponding code has run.
```
const food = "sushi";
switch (food) {
case "sushi":
console.log("Sushi is originally from Japan.");
break;
case "pizza":
console.log("Pizza is originally from Italy.");
break;
default:
console.log("I have never heard of that dish.");
break;
}
```
### break in labeled blocks
The following code uses `break` statements with labeled blocks. A `break` statement must be nested within any label it references. Notice that `innerBlock` is nested within `outerBlock`.
```
outerBlock: {
innerBlock: {
console.log("1");
break outerBlock; // breaks out of both inner\_block and outer\_block
console.log(":-("); // skipped
}
console.log("2"); // skipped
}
```
### break in labeled blocks that throw
The following code also uses `break` statements with labeled blocks, but generates a `SyntaxError` because its `break` statement is within `block1` but references `block2`. A `break` statement must always be nested within any label it references.
```
block1: {
console.log('1');
break block2; // SyntaxError: label not found
}
block2: {
console.log('2');
}
```
### break within functions
`SyntaxError`s are also generated in the following code examples which use `break` statements within functions that are nested within a loop, or labeled block that the `break` statements are intended to break out of.
```
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
(function () {
break;
})();
}
i += 1;
}
return i \* x;
}
testBreak(1); // SyntaxError: Illegal break statement
```
```
block\_1: {
console.log('1');
(function () {
break block_1; // SyntaxError: Undefined label 'block\_1'
})();
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-break-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-break-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `break` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`continue`](continue)
* <label>
* [`switch`](switch)
| programming_docs |
javascript const const
=====
The `const` declaration creates block-scoped constants, much like variables declared using the [`let`](let) keyword. The value of a constant can't be changed through reassignment (i.e. by using the [assignment operator](../operators/assignment)), and it can't be redeclared (i.e. through a [variable declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations)). However, if a constant is an [object](../global_objects/object) or [array](../global_objects/array) its properties or items can be updated or removed.
Try it
------
Syntax
------
```
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]
```
`nameN` The constant's name, which can be any legal [identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier).
`valueN` The constant's value. This can be any legal expression, including a function expression.
The [destructuring assignment](../operators/destructuring_assignment) syntax can also be used to declare variables.
```
const { bar } = foo; // where foo = { bar:10, baz:12 };
/\* This creates a constant with the name 'bar', which has a value of 10 \*/
```
Description
-----------
This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do **not** become properties of the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object, unlike [`var`](var) variables.
An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)
The `const` 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 the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
All the considerations about the [temporal dead zone](let#temporal_dead_zone_tdz) apply to both [`let`](let) and `const`. For this reason, `const` declarations are commonly regarded as [non-hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting).
A constant cannot share its name with a function or a variable in the same scope.
If you're experimenting in a REPL, such as the Firefox web console (**Tools** > **Web Developer** > **Web Console**), and you run two `const` declarations with the same name in two separate inputs, you may get a syntax error due to re-declaration. See further discussion of this issue in [bug 1580891](https://bugzilla.mozilla.org/show_bug.cgi?id=1580891). The Chrome console allows `const` re-declarations between different REPL inputs.
Unlike `var`, `const` begins [*declarations*, not *statements*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). That means you cannot use a lone `const` declaration as the body of a block (which makes sense, since there's no way to access the variable).
```
if (true) const a = 1; // SyntaxError: Unexpected token 'const'
```
Examples
--------
### Basic const usage
Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
```
// define MY\_FAV as a constant and give it the value 7
const MY\_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY\_FAV = 20;
// MY\_FAV is 7
console.log("my favorite number is: " + MY\_FAV);
// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY\_FAV' has already been declared
const MY\_FAV = 20;
// the name MY\_FAV is reserved for constant above, so this will fail too
var MY\_FAV = 20;
// this throws an error too
let MY\_FAV = 20;
```
### Block scoping
It's important to note the nature of block scoping.
```
if (MY\_FAV === 7) {
// this is fine and creates a block scoped MY\_FAV variable
// (works equally well with let to declare a block scoped non const variable)
let MY\_FAV = 20;
// MY\_FAV is now 20
console.log("my favorite number is " + MY\_FAV);
// this gets hoisted into the global context and throws an error
var MY\_FAV = 20;
}
// MY\_FAV is still 7
console.log("my favorite number is " + MY\_FAV);
```
### const needs to be initialized
```
// throws an error
// Uncaught SyntaxError: Missing initializer in const declaration
const FOO;
```
### const in objects and arrays
`const` also works on objects and arrays. Attempting to overwrite the object throws an error "Assignment to constant variable".
```
const MY\_OBJECT = { key: "value" };
MY\_OBJECT = { OTHER\_KEY: "value" };
```
However, object keys are not protected, so the following statement is executed without problem.
```
MY\_OBJECT.key = "otherValue";
```
You would need to use [`Object.freeze()`](../global_objects/object/freeze) to make an object immutable.
The same applies to arrays. Assigning a new array to the variable throws an error "Assignment to constant variable".
```
const MY\_ARRAY = [];
MY\_ARRAY = ["B"];
```
Still, it's possible to push items into the array and thus mutate it.
```
MY\_ARRAY.push("A"); // ["A"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-let-and-const-declarations](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-let-and-const-declarations) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `const` | 21 | 12 | 36
["Before Firefox 13, `const` is implemented, but re-assignment is not failing.", "Before Firefox 46, a `TypeError` was thrown on redeclaration instead of a `SyntaxError`."] | 11 | 9 | 5.1 | 4.4 | 25 | 36
["Before Firefox 13, `const` is implemented, but re-assignment is not failing.", "Before Firefox 46, a `TypeError` was thrown on redeclaration instead of a `SyntaxError`."] | 10.1 | 5 | 1.5 | 1.0 | 6.0.0 |
See also
--------
* [`var`](var)
* [`let`](let)
* [Constants in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#constants)
javascript debugger debugger
========
The `debugger` statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect.
Syntax
------
```
debugger;
```
Examples
--------
### Using the debugger statement
The following example shows code where a `debugger` statement has been inserted, to invoke a debugger (if one exists) when the function is called.
```
function potentiallyBuggyCode() {
debugger;
// do potentially buggy stuff to examine, step through, etc.
}
```
When the debugger is invoked, execution is paused at the `debugger` statement. It is like a breakpoint in the script source.

Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-debugger-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-debugger-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `debugger` | 5 | 12 | 1 | 4 | 10 | 5 | 4.4 | 18 | 4 | 10.1 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [The Debugger in the Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html)
javascript function* function\*
==========
The `function*` declaration (`function` keyword followed by an asterisk) defines a *generator function*, which returns a [`Generator`](../global_objects/generator) object.
Try it
------
You can also define generator functions using the [`GeneratorFunction`](../global_objects/generatorfunction) constructor, or the function expression syntax.
Syntax
------
```
function\* name(param0) {
statements
}
function\* name(param0, param1) {
statements
}
function\* name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
**Note:** Generator functions do not have arrow function counterparts.
### Parameters
`name` The function name.
`param` Optional
The name of a formal parameter for the function.
`statements` Optional
The statements comprising the body of the function.
Description
-----------
Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
Generators in JavaScript — especially when combined with Promises — are a very powerful tool for asynchronous programming as they mitigate — if not entirely eliminate -- the problems with callbacks, such as [Callback Hell](http://callbackhell.com/) and [Inversion of Control](https://frontendmasters.com/courses/rethinking-async-js/callback-problems-inversion-of-control/). However, an even simpler solution to these problems can be achieved with [async functions](async_function).
Calling a generator function does not execute its body immediately; a [generator](../global_objects/generator) object for the function is returned instead. When the iterator's `next()` method is called, the generator function's body is executed until the first [`yield`](../operators/yield) expression, which specifies the value to be returned from the iterator or, with [`yield*`](../operators/yield*), delegates to another generator function. The `next()` method returns an object with a `value` property containing the yielded value and a `done` property which indicates whether the generator has yielded its last value, as a boolean. Calling the `next()` method with an argument will resume the generator function execution, replacing the `yield` expression where an execution was paused with the argument from `next()`.
A `return` statement in a generator, when executed, will make the generator finish (i.e. the `done` property of the object returned by it will be set to `true`). If a value is returned, it will be set as the `value` property of the object returned by the generator. Much like a `return` statement, an error thrown inside the generator will make the generator finished — unless caught within the generator's body. When a generator is finished, subsequent `next()` calls will not execute any of that generator's code, they will just return an object of this form: `{value: undefined, done: true}`.
`function*` declarations are [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope.
Examples
--------
### Simple example
```
function\* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// …
```
### Example with yield\*
```
function\* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function\* generator(i) {
yield i;
yield\* anotherGenerator(i);
yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
```
### Passing arguments into Generators
```
function\* logGenerator() {
console.log(0);
console.log(1, yield);
console.log(2, yield);
console.log(3, yield);
}
const gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next(); // 0
gen.next("pretzel"); // 1 pretzel
gen.next("california"); // 2 california
gen.next("mayonnaise"); // 3 mayonnaise
```
### Return statement in a generator
```
function\* yieldAndReturn() {
yield "Y";
return "R";
yield "unreachable";
}
const gen = yieldAndReturn();
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as an object property
```
const someObj = {
\*generator() {
yield "a";
yield "b";
},
};
const gen = someObj.generator();
console.log(gen.next()); // { value: 'a', done: false }
console.log(gen.next()); // { value: 'b', done: false }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as an object method
```
class Foo {
\*generator() {
yield 1;
yield 2;
yield 3;
}
}
const f = new Foo();
const gen = f.generator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as a computed property
```
class Foo {
\*[Symbol.iterator]() {
yield 1;
yield 2;
}
}
const SomeObj = {
\*[Symbol.iterator]() {
yield "a";
yield "b";
},
};
console.log(Array.from(new Foo())); // [ 1, 2 ]
console.log(Array.from(SomeObj)); // [ 'a', 'b' ]
```
### Generators are not constructable
```
function\* f() {}
const obj = new f(); // throws "TypeError: f is not a constructor
```
### Generator defined in an expression
```
const foo = function\* () {
yield 10;
yield 20;
};
const bar = foo();
console.log(bar.next()); // {value: 10, done: false}
```
### Generator example
```
function\* powers(n) {
//endless loop to generate
for (let current = n; ; current \*= n) {
yield current;
}
}
for (const power of powers(2)) {
// controlling generator
if (power > 32) {
break;
}
console.log(power);
// 2
// 4
// 8
// 16
// 32
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-generator-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `IteratorResult_object` | 49 | 13 | 29 | No | 36 | 10 | 49 | 49 | 29 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `function*` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `not_constructable_with_new` | 50 | 13 | 43 | No | 37 | 10 | 50 | 50 | 43 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `trailing_comma_in_parameters` | 58 | 14 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
See also
--------
* [`function*`](../operators/function*) expression
* [`GeneratorFunction`](../global_objects/generatorfunction) object
* [Iteration protocols](../iteration_protocols)
* [`yield`](../operators/yield)
* [`yield*`](../operators/yield*)
* [`Function`](../global_objects/function) object
* [`function`](function) declaration
* [`function`](../operators/function) expression
* [Functions and function scope](../functions)
* Other web resources:
+ [Regenerator](https://facebook.github.io/regenerator/) an ES2015 generator compiler to ES5
+ [Forbes Lindesay: Promises and Generators: control flow utopia — JSConf EU 2013](https://www.youtube.com/watch?v=qbKWsbJ76-s)
+ [Task.js](https://github.com/mozilla/task.js)
+ [Iterating generators asynchronously](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch4.md#iterating-generators-asynchronously)
javascript empty empty
=====
An **empty statement** is used to provide no statement, although the JavaScript syntax would expect one.
Try it
------
Syntax
------
```
;
```
Description
-----------
The empty statement is a semicolon (`;`) indicating that no statement will be executed, even if JavaScript syntax requires one.
The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a [block statement](block), which combines several statements into a single one.
Examples
--------
### Empty loop body
The empty statement is sometimes used with loop statements. See the following example with an empty loop body:
```
const arr = [1, 2, 3];
// Assign all array values to 0
for (let i = 0; i < arr.length; arr[i++] = 0) /\* empty statement \*/ ;
console.log(arr);
// [0, 0, 0]
```
### Unintentional usage
It is a good idea to comment *intentional* use of the empty statement, as it is not really obvious to distinguish from a normal semicolon.
In the following example, the usage is probably not intentional:
```
if (condition); // Caution, this "if" does nothing!
killTheUniverse(); // So this always gets executed!!!
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-empty-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-empty-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Empty` | 3 | 12 | 1 | 3 | 3 | 5 | 4.4 | 18 | 4 | 10.1 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Block statement](block)
javascript block block
=====
A **block statement** is used to group zero or more statements. The block is delimited by a pair of braces ("curly brackets") and contains a list of zero or more statements and declarations.
Try it
------
Syntax
------
```
{
StatementList
}
```
`StatementList` Statements and declarations grouped within the block statement.
Description
-----------
The block statement is often called the *compound statement* in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript, especially when used in association with control flow statements like [`if...else`](if...else) and [`for`](for). The opposite behavior is possible using an [empty statement](empty), where you provide no statement, although one is required.
In addition, combined with block-scoped declarations like [`let`](let), [`const`](const), and [`class`](class), blocks can prevent temporary variables from polluting the global namespace, just like [IIFEs](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) do.
### Block scoping rules with var or function declaration in non-strict mode
Variables declared with `var` or created by [function declarations](function) in non-strict mode **do not** have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:
```
var x = 1;
{
var x = 2;
}
console.log(x); // 2
```
This logs 2 because the `var x` statement within the block is in the same scope as the `var x` statement before the block.
In non-strict code, function declarations inside blocks behave strangely. Do not use them.
### Block scoping rules with let, const, class, or function declaration in strict mode
By contrast, identifiers declared with [`let`](let), [`const`](const), and [`class`](class) do have block scope:
```
let x = 1;
{
let x = 2;
}
console.log(x); // 1
```
The `x = 2` is limited in scope to the block in which it was defined.
The same is true of `const`:
```
const c = 1;
{
const c = 2;
}
console.log(c); // 1; does not throw SyntaxError
```
Note that the block-scoped `const c = 2` *does not* throw a `SyntaxError: Identifier 'c' has already been declared` because it can be declared uniquely within the block.
In [strict mode](../strict_mode), function declarations inside blocks are scoped to that block and are hoisted.
```
"use strict";
{
foo(); // Logs "foo"
function foo() {
console.log("foo");
}
}
foo(); // ReferenceError: foo is not defined
```
Examples
--------
### Using a block statement as the body of a for loop
A [`for`](for) loop accepts a single statement as its body.
```
for (let i = 0; i < 10; i++) console.log(i);
```
If you want to use more than one statement in the loop body, you can group them into one block statement:
```
for (let i = 0; i < 10; i++) {
console.log(i);
console.log(i \*\* 2);
}
```
### Using a block statement to encapsulate data
`let` and `const` declarations are scoped to the containing block. This allows you to hide data from the global scope without wrapping it in a function.
```
let sector;
{
// These variables are scoped to this block and are not
// accessible after the block
const angle = Math.PI / 3;
const radius = 10;
sector = {
radius,
angle,
area: (angle / 2) \* radius \*\* 2,
perimeter: 2 \* radius + angle \* radius,
};
}
console.log(sector);
// {
// radius: 10,
// angle: 1.0471975511965976,
// area: 52.35987755982988,
// perimeter: 30.471975511965976
// }
console.log(typeof radius); // "undefined"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-block](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-block) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `block` | 1 | 12 | 1 | 11 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`while`](while)
* [`if...else`](if...else)
* [`let`](let)
| programming_docs |
javascript function declaration function declaration
====================
The `function` declaration defines a function with the specified parameters.
You can also define functions using the [`Function`](../global_objects/function) constructor and a [function expression](../operators/function).
Try it
------
Syntax
------
```
function name(param0) {
statements
}
function name(param0, param1) {
statements
}
function name(param0, param1, /\* … ,\*/ paramN) {
statements
}
```
`name` The function name.
`param` Optional
The name of an argument to be passed to the function. Maximum number of arguments varies in different engines.
`statements` Optional
The statements which comprise the body of the function.
Description
-----------
A function created with a function declaration is a `Function` object and has all the properties, methods and behavior of `Function` objects. See [`Function`](../global_objects/function) for detailed information on functions.
A function can also be created using an expression (see [function expression](../operators/function)).
By default, functions return `undefined`. To return any other value, the function must have a [`return`](return) statement that specifies the value to return.
### Block-level function declaration
**Warning:** In [non-strict mode](../strict_mode), function declarations inside blocks behave strangely. Only declare functions in blocks if you are in strict mode.
Functions can be conditionally declared — that is, a function statement can be nested within an [`if`](if...else) statement. However, in non-strict mode, the results are inconsistent across implementations.
```
console.log(`'foo' name ${"foo" in globalThis ? "is" : "is not"} global. typeof foo is ${typeof foo}`);
if (false) {
function foo() { return 1; }
}
// In Chrome:
// 'foo' name is global. typeof foo is undefined
//
// In Firefox:
// 'foo' name is global. typeof foo is undefined
//
// In Safari:
// 'foo' name is global. typeof foo is function
```
The scoping and hoisting effect won't change regardless of whether the `if` body is actually executed.
```
console.log(`'foo' name ${"foo" in globalThis ? "is" : "is not"} global. typeof foo is ${typeof foo}`);
if (true) {
function foo() { return 1; }
}
// In Chrome:
// 'foo' name is global. typeof foo is undefined
//
// In Firefox:
// 'foo' name is global. typeof foo is undefined
//
// In Safari:
// 'foo' name is global. typeof foo is function
```
In [strict mode](../strict_mode), <block>-level function declarations are scoped to that block and are hoisted to the top of the block.
```
"use strict";
{
foo(); // Logs "foo"
function foo() {
console.log("foo");
}
}
console.log(`'foo' name ${"foo" in globalThis ? "is" : "is not"} global. typeof foo is ${typeof foo}`);
// 'foo' name is not global. typeof foo is undefined
```
### Function declaration hoisting
Function declarations in JavaScript are [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) to the top of the enclosing function or global scope. You can use the function before you declared it:
```
hoisted(); // Logs "foo"
function hoisted() {
console.log('foo');
}
```
Note that [function expressions](../operators/function) are not hoisted:
```
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
```
Examples
--------
### Using function
The following code declares a function that returns the total amount of sales, when given the number of units sold of three products.
```
function calcSales(unitsA, unitsB, unitsC) {
return unitsA \* 79 + unitsB \* 129 + unitsC \* 699;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-definitions](https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-function-definitions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `function` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `trailing_comma_in_parameters` | 58 | 14 | 52 | No | 45 | 10 | 58 | 58 | 52 | 43 | 10 | 7.0 | 1.0 | 8.0.0 |
See also
--------
* [`Function`](../global_objects/function)
* [function expression](../operators/function)
* [function\* statement](function*)
* [function\* expression](../operators/function*)
* [Arrow functions](../functions/arrow_functions)
* [`GeneratorFunction`](../global_objects/generatorfunction)
* [async function](async_function)
* [async function expression](../operators/async_function)
javascript switch switch
======
The `switch` statement evaluates an [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators), matching the expression's value against a series of `case` clauses, and executes [statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements) after the first `case` clause with a matching value, until a `break` statement is encountered. The `default` clause of a `switch` statement will be jumped to if no `case` matches the expression's value.
Try it
------
Syntax
------
```
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the
//result of expression matches valueN
[break;]
[default:
//Statements executed when none of
//the values match the value of the expression
[break;]]
}
```
`expression` An expression whose result is matched against each `case` clause.
`case valueN` Optional
A `case` clause used to match against `expression`. If the `expression` matches the specified `valueN` (which can be any expression), execution starts from the first statement after that `case` clause until either the end of the `switch` statement or the first encountered `break`.
`default` Optional
A `default` clause; if provided, this clause is executed if the value of `expression` doesn't match any of the `case` clauses. A `switch` statement can only have one `default` clause.
Description
-----------
A `switch` statement first evaluates its expression. It then looks for the first `case` clause whose expression evaluates to the same value as the result of the input expression (using the [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators), `===`) and transfers control to that clause, executing all statements following that clause.
The clause values are only evaluated when necessary — if a match is already found, subsequent `case` clause values will not be evaluated, even when they will be visited by [fall-through](#breaking_and_fall-through).
```
switch (undefined) {
case console.log(1):
case console.log(2):
}
// Only logs 1
```
If no matching `case` clause is found, the program looks for the optional `default` clause, and if found, transfers control to that clause, executing statements following that clause. If no `default` clause is found, the program continues execution at the statement following the end of `switch`. By convention, the `default` clause is the last clause, but it does not need to be so. A `switch` statement may only have one `default` clause; multiple `default` clauses will result in a [`SyntaxError`](../global_objects/syntaxerror).
### Breaking and fall-through
You can use the [`break`](break) statement within a `switch` statement's body to break out early, often when all statements between two `case` clauses have been executed. Execution will continue at the first statement following `switch`.
If `break` is omitted, execution will proceed to the next `case` clause, even to the `default` clause, regardless of whether the value of that clause matches. This behavior is called "fall-through".
```
const foo = 0;
switch (foo) {
case -1:
console.log('negative 1');
break;
case 0: // Value of foo matches this criteria; execution starts from here
console.log(0);
// Forgotten break! Execution falls through
case 1: // no break statement in 'case 0:' so this case will run as well
console.log(1);
break; // Break encountered; will not continue into 'case 2:'
case 2:
console.log(2);
break;
default:
console.log('default');
}
// Logs 0 and 1
```
You can use other control-flow statements to replace `break`, such as a [`return`](return) statement.
### Lexical scoping
The `case` and `default` clauses are like [labels](label): they indicate possible places that control flow may jump to. However, they don't create lexical [scopes](https://developer.mozilla.org/en-US/docs/Glossary/Scope) themselves (neither do they automatically break out — as demonstrated above). For example:
```
const action = 'say\_hello';
switch (action) {
case 'say\_hello':
const message = 'hello';
console.log(message);
break;
case 'say\_hi':
const message = 'hi';
console.log(message);
break;
default:
console.log('Empty action received.');
}
```
This example will output the error "Uncaught SyntaxError: Identifier 'message' has already been declared", because the first `const message = 'hello';` conflicts with the second `const message = 'hi';` declaration, even when they're within their own separate case clauses. Ultimately, this is due to both `const` declarations being within the same block scope created by the `switch` body.
To fix this, whenever you need to use `let` or `const` declarations in a `case` clause, wrap it in a block.
```
const action = 'say\_hello';
switch (action) {
case 'say\_hello': { // added brackets
const message = 'hello';
console.log(message);
break;
} // added brackets
case 'say\_hi': { // added brackets
const message = 'hi';
console.log(message);
break;
} // added brackets
default: { // added brackets
console.log('Empty action received.');
} // added brackets
}
```
This code will now output `hello` in the console as it should, without any errors.
Examples
--------
### Using switch
In the following example, if `expr` evaluates to `Bananas`, the program matches the value with case `case 'Bananas'` and executes the associated statement. When `break` is encountered, the program breaks out of `switch` and executes the statement following `switch`. If `break` were omitted, the statement for the `case 'Cherries'` would also be executed.
```
switch (expr) {
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':
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
console.log("Is there anything else you'd like?");
```
### Putting the default clause between two case clauses
If no match is found, execution will start from the `default` clause, and execute all statements after that.
```
const foo = 5;
switch (foo) {
case 2:
console.log(2);
break; // it encounters this break so will not continue into 'default:'
default:
console.log('default')
// fall-through
case 1:
console.log('1');
}
```
It also works when you put `default` before all other `case` clauses.
### Taking advantage of fall-through
This method takes advantage of the fact that if there is no `break` below a `case` clause, execution will continue to the next `case` clause regardless if that `case` meets the criteria.
The following is an example of a single operation sequential `case` statement, where four different values perform exactly the same.
```
const Animal = 'Giraffe';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This animal is not extinct.');
break;
case 'Dinosaur':
default:
console.log('This animal is extinct.');
}
```
The following is an example of a multiple-operation sequential `case` clause, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the `case` clauses, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these `case` statements as well.
```
const foo = 1;
let output = 'Output: ';
switch (foo) {
case 0:
output += 'So ';
case 1:
output += 'What ';
output += 'Is ';
case 2:
output += 'Your ';
case 3:
output += 'Name';
case 4:
output += '?';
console.log(output);
break;
case 5:
output += '!';
console.log(output);
break;
default:
console.log('Please pick a number from 0 to 5!');
}
```
The output from this example:
| Value | Log text |
| --- | --- |
| `foo` is `NaN` or not `1`, `2`, `3`, `4`, `5`, or `0` | Please pick a number from 0 to 5! |
| `0` | Output: So What Is Your Name? |
| `1` | Output: What Is Your Name? |
| `2` | Output: Your Name? |
| `3` | Output: Name? |
| `4` | Output: ? |
| `5` | Output: ! |
### An alternative to if...else chains
You may often find yourself doing a series of [`if...else`](if...else) matches.
```
if ('fetch' in globalThis) {
// Fetch a resource with fetch
} else if ('XMLHttpRequest' in globalThis) {
// Fetch a resource with XMLHttpRequest
} else {
// Fetch a resource with some custom AJAX logic
}
```
This pattern is not doing a sequence of `===` comparisons, but you can still convert it to a `switch` construct.
```
switch (true) {
case 'fetch' in globalThis:
// Fetch a resource with fetch
break;
case 'XMLHttpRequest' in globalThis:
// Fetch a resource with XMLHttpRequest
break;
default:
// Fetch a resource with some custom AJAX logic
break;
}
```
The `switch (true)` pattern as an alternative to `if...else` is especially useful if you want to utilize the fall-through behavior.
```
switch (true) {
case isSquare(shape):
console.log('This shape is a square.');
// Fall-through, since a square is a rectangle as well!
case isRectangle(shape):
console.log('This shape is a rectangle.');
case isQuadrilateral(shape):
console.log('This shape is a quadrilateral.');
break;
case isCircle(shape):
console.log('This shape is a circle.');
break;
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-switch-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-switch-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `switch` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`if...else`](if...else)
javascript do...while do...while
==========
The `do...while` statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
Try it
------
Syntax
------
```
do
statement
while (condition)
```
`statement` A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a <block> statement (`{ /* ... */ }`) to group those statements.
`condition` An expression evaluated after each pass through the loop. If `condition` [evaluates to true](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), the `statement` is re-executed. When `condition` [evaluates to false](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), control passes to the statement following the `do...while`.
Note: Use the [`break`](break) statement to stop a loop before `condition` evaluates to false.
Examples
--------
### Using `do...while`
In the following example, the `do...while` loop iterates at least once and reiterates until `i` is no longer less than 5.
```
let result = "";
let i = 0;
do {
i += 1;
result += `${i}`;
} while (i > 0 && i < 5);
// Despite i === 0 this will still loop as it starts off without the test
console.log(result);
```
### Using an assignment as a condition
In some cases, it can make sense to use an assignment as a condition — but when you do, there's a right way to do it, and a wrong way; the [`while`](while) documentation has a [Using an assignment as a condition](while#using_an_assignment_as_a_condition) section with an example showing a general best-practice syntax you should know about and follow.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-do-while-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-do-while-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `do...while` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`while`](while)
* [`for`](for)
* [`break`](break)
* [`continue`](continue)
javascript for for
===
The `for` statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a [block statement](block)) to be executed in the loop.
Try it
------
Syntax
------
```
for (initialization; condition; afterthought)
statement
```
`initialization` Optional
An expression (including [assignment expressions](../operators/assignment)) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with `var` or `let` keywords. Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for` loop is in. Variables declared with `let` are local to the statement.
The result of this expression is discarded.
`condition` Optional
An expression to be evaluated before each loop iteration. If this expression [evaluates to true](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), `statement` is executed. If the expression [evaluates to false](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), execution exits the loop and goes to the first statement after the `for` construct.
This conditional test is optional. If omitted, the condition always evaluates to true.
`afterthought` Optional
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of `condition`. Generally used to update or increment the counter variable.
`statement` A statement that is executed as long as the condition evaluates to true. You can use a [block statement](block) to execute multiple statements. To execute no statement within the loop, use an [empty statement](empty) (`;`).
Examples
--------
### Using for
The following `for` statement starts by declaring the variable `i` and initializing it to `0`. It checks that `i` is less than nine, performs the two succeeding statements, and increments `i` by 1 after each pass through the loop.
```
for (let i = 0; i < 9; i++) {
console.log(i);
// more statements
}
```
### Initialization block syntax
The initialization block accepts both expressions and variable declarations. However, expressions cannot use the [`in`](../operators/in) operator unparenthesized, because that is ambiguous with a [`for...in`](for...in) loop.
```
for (let i = "start" in window ? window.start : 0; i < 9; i++) {
console.log(i);
}
// SyntaxError: 'for-in' loop variable declaration may not have an initializer.
```
```
// Parenthesize the whole initializer
for (let i = ("start" in window ? window.start : 0); i < 9; i++) {
console.log(i);
}
// Parenthesize the `in` expression
for (let i = ("start" in window) ? window.start : 0; i < 9; i++) {
console.log(i);
}
```
### Optional for expressions
All three expressions in the head of the `for` loop are optional. For example, it is not required to use the `initialization` block to initialize variables:
```
let i = 0;
for (; i < 9; i++) {
console.log(i);
// more statements
}
```
Like the `initialization` block, the `condition` part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.
```
for (let i = 0; ; i++) {
console.log(i);
if (i > 3) break;
// more statements
}
```
You can also omit all three expressions. Again, make sure to use a [`break`](break) statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.
```
let i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
```
However, in the case where you are not fully using all three expression positions — especially if you are not declaring variables with the first expression but mutating something in the upper scope — consider using a [`while`](while) loop instead, which makes the intention clearer.
```
let i = 0;
while (i <= 3) {
console.log(i);
i++;
}
```
### Lexical declarations in the initialization block
Declaring a variable within the initialization block has important differences from declaring it in the upper [scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope), especially when creating a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) within the loop body. For example, for the code below:
```
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
```
It logs `0`, `1`, and `2`, as expected. However, if the variable is defined in the upper scope:
```
let i = 0;
for (; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
```
It logs `3`, `3`, and `3`. The reason is that each `setTimeout` creates a new closure that closes over the `i` variable, but if the `i` is not scoped to the loop body, all closures will reference the same variable when they eventually get called — and due to the asynchronous nature of [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), it will happen after the loop has already exited, causing the value of `i` in all queued callbacks' bodies to have the value of `3`.
This also happens if you use a `var` statement as the initialization, because variables declared with `var` are only function-scoped, but not lexically scoped (i.e. they can't be scoped to the loop body).
```
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
// Logs 3, 3, 3
```
The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within the `condition` and `afterthought` parts. More precisely, `let` declarations are special-cased by `for` loops — if `initialization` is a `let` declaration, then every time, after the loop body is evaluated, the following happens:
1. A new lexical scope is created with new `let`-declared variables.
2. The binding values from the last iteration are used to re-initialize the new variables.
3. `afterthought` is evaluated in the new scope.
So re-assigning the new variables within `afterthought` does not affect the bindings from the previous iteration.
Creating closures allows you to get hold of a binding during any particular iteration. This explains why closures created within the `initialization` section do not get updated by re-assignments of `i` in the `afterthought`.
```
for (let i = 0, getI = () => i; i < 3; i++) {
console.log(getI());
}
// Logs 0, 0, 0
```
This does not log "0, 1, 2", like what would happen if `getI` is declared in the loop body. This is because `getI` is not re-evaluated on each iteration — rather, the function is created once and closes over the `i` variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value of `i` actually create new variables called `i`, which `getI` does not see. A way to fix this is to re-compute `getI` every time `i` updates:
```
for (let i = 0, getI = () => i; i < 3; i++, getI = () => i) {
console.log(getI());
}
// Logs 0, 1, 2
```
In fact, you can capture the initial binding of the `i` variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding of `i`.
```
for (
let i = 0, getI = () => i, incrementI = () => i++;
getI() < 3;
incrementI()
) {
console.log(i);
}
// Logs 0, 0, 0
```
This logs "0, 0, 0", because the `i` variable in each loop evaluation is actually a separate variable, but `getI` and `incrementI` both read and write the *initial* binding of `i`, not what was subsequently declared.
### Using for without a body
The following `for` cycle calculates the offset position of a node in the `afterthought` section, and therefore it does not require the use of a `statement` section, a semicolon is used instead.
```
function showOffsetPos(id) {
let left = 0;
let top = 0;
for (
let itNode = document.getElementById(id); // initialization
itNode; // condition
left += itNode.offsetLeft,
top += itNode.offsetTop,
itNode = itNode.offsetParent // afterthought
); // semicolon
console.log(
`Offset position of "${id}" element:
left: ${left}px;
top: ${top}px;`,
);
}
showOffsetPos("content");
// Logs:
// Offset position of "content" element:
// left: 0px;
// top: 153px;
```
Note that the semicolon after the `for` statement is mandatory, because it stands as an [empty statement](empty). Otherwise, the `for` statement acquires the following `console.log` line as its `statement` section, which makes the `log` execute multiple times.
### Using for with two iterating variables
You can create two counters that are updated simultaneously in a for loop using the [comma operator](../operators/comma_operator). Multiple `let` and `var` declarations can also be joined with commas.
```
const arr = [1, 2, 3, 4, 5, 6];
for (let l = 0, r = arr.length - 1; l < r; l++, r--) {
console.log(arr[l], arr[r]);
}
// 1 6
// 2 5
// 3 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-for-statement](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-for-statement) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `for` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [empty statement](empty)
* [`break`](break)
* [`continue`](continue)
* [`while`](while)
* [`do...while`](do...while)
* [`for...in`](for...in)
* [`for...of`](for...of)
| programming_docs |
javascript for await...of for await...of
==============
The `for await...of` statement creates a loop iterating over [async iterable objects](../iteration_protocols#the_async_iterator_and_async_iterable_protocols) as well as [sync iterables](../iteration_protocols#the_iterable_protocol). This statement can only be used in contexts where [`await`](../operators/await) can be used, which includes inside an [async function](async_function) body and in a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).
Try it
------
**Note:** `for await...of` doesn't work with async iterators that are not async iterables.
Syntax
------
```
for await (variable of iterable)
statement
```
`variable` Receives a value from the sequence on each iteration. May be either a declaration with [`const`](const), [`let`](let), or [`var`](var), or an [assignment](../operators/assignment) target (e.g. a previously declared variable or an object property).
`iterable` An async iterable or sync iterable. The source of the sequence of values on which the loop operates.
`statement` A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](block) to execute multiple statements.
Description
-----------
When a `for await...of` loop iterates over an iterable, it first gets the iterable's [`[@@asyncIterator]()`](../global_objects/symbol/asynciterator) method and calls it, which returns an [async iterator](../iteration_protocols#the_async_iterator_and_async_iterable_protocols). If the `@asyncIterator` method does not exist, it then looks for an [`[@@iterator]()`](../global_objects/symbol/iterator) method, which returns a [sync iterator](../iteration_protocols#the_iterator_protocol). The sync iterator returned is then wrapped into an async iterator by wrapping every object returned from the `next()`, `return()`, and `throw()` methods into a resolved or rejected promise, with the `value` property resolved if it's also a promise. The loop then repeatedly calls the final async iterator's [`next()`](../iteration_protocols#the_iterator_protocol) method and [awaits](../operators/await) the returned promise, producing the sequence of values to be assigned to `variable`.
If the `for await...of` loop exited early (e.g. a `break` statement is encountered or an error is thrown), the [`return()`](../iteration_protocols#the_iterator_protocol) method of the iterator is called to perform any cleanup. The returned promise is awaited before the loop exits.
`for await...of` generally functions the same as the [`for...of`](for...of) loop and shares many of the same syntax and semantics. There are a few differences:
* `for await...of` works on both sync and async iterables, while `for...of` only works on sync iterables.
* `for await...of` can only be used in contexts where [`await`](../operators/await) can be used, which includes inside an [async function](async_function) body and in a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). Even when the iterable is sync, the loop still awaits the return value for every iteration, leading to slower execution due to repeated promise unwrapping.
* If the `iterable` is a sync iterable that yields promises, `for await...of` would produce a sequence of resolved values, while `for...of` would produce a sequence of promises. (However, beware of error handling and cleanup — see [Iterating over sync iterables and generators](#iterating_over_sync_iterables_and_generators))
* For `for await...of`, the `variable` can be the identifier `async` (e.g. `for await (async of foo)`); `for...of` forbids this case.
Examples
--------
### Iterating over async iterables
You can also iterate over an object that explicitly implements async iterable protocol:
```
const LIMIT = 3;
const asyncIterable = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
const done = i === LIMIT;
const value = done ? undefined : i++;
return Promise.resolve({ value, done });
},
return() {
// This will be reached if the consumer called 'break' or 'return' early in the loop.
return { done: true };
},
};
},
};
(async () => {
for await (const num of asyncIterable) {
console.log(num);
}
})();
// 0
// 1
// 2
```
### Iterating over async generators
Since the return values of async generator functions conform to the async iterable protocol, they can be looped using `for await...of`.
```
async function\* asyncGenerator() {
let i = 0;
while (i < 3) {
yield i++;
}
}
(async () => {
for await (const num of asyncGenerator()) {
console.log(num);
}
})();
// 0
// 1
// 2
```
For a more concrete example of iterating over an async generator using `for await...of`, consider iterating over data from an API.
This example first creates an async iterable for a stream of data, then uses it to find the size of the response from the API.
```
async function\* streamAsyncIterable(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
reader.releaseLock();
}
}
// Fetches data from URL and calculates response size using the async generator.
async function getResponseSize(url) {
const response = await fetch(url);
// Will hold the size of the response, in bytes.
let responseSize = 0;
// The for-await-of loop. Async iterates over each portion of the response.
for await (const chunk of streamAsyncIterable(response.body)) {
// Incrementing the total response length.
responseSize += chunk.length;
}
console.log(`Response Size: ${responseSize} bytes`); // "Response Size: 1071472"
return responseSize;
}
getResponseSize("https://jsonplaceholder.typicode.com/photos");
```
### Iterating over sync iterables and generators
`for await...of` loop also consumes sync iterables and generators. In that case it internally awaits emitted values before assign them to the loop control variable.
```
function\* generator() {
yield 0;
yield 1;
yield Promise.resolve(2);
yield Promise.resolve(3);
yield 4;
}
(async () => {
for await (const num of generator()) {
console.log(num);
}
})();
// 0
// 1
// 2
// 3
// 4
// compare with for-of loop:
for (const numOrPromise of generator()) {
console.log(numOrPromise);
}
// 0
// 1
// Promise { 2 }
// Promise { 3 }
// 4
```
**Note:** Be aware of yielding rejected promises from a sync generator. In such case, `for await...of` throws when consuming the rejected promise and DOESN'T CALL `finally` blocks within that generator. This can be undesirable if you need to free some allocated resources with `try/finally`.
```
function\* generatorWithRejectedPromises() {
try {
yield 0;
yield 1;
yield Promise.resolve(2);
yield Promise.reject(3);
yield 4;
throw 5;
} finally {
console.log("called finally");
}
}
(async () => {
try {
for await (const num of generatorWithRejectedPromises()) {
console.log(num);
}
} catch (e) {
console.log("caught", e);
}
})();
// 0
// 1
// 2
// caught 3
// compare with for-of loop:
try {
for (const numOrPromise of generatorWithRejectedPromises()) {
console.log(numOrPromise);
}
} catch (e) {
console.log("caught", e);
}
// 0
// 1
// Promise { 2 }
// Promise { <rejected> 3 }
// 4
// caught 5
// called finally
```
To make `finally` blocks of a sync generator always called, use the appropriate form of the loop — `for await...of` for the async generator and `for...of` for the sync one — and await yielded promises explicitly inside the loop.
```
(async () => {
try {
for (const numOrPromise of generatorWithRejectedPromises()) {
console.log(await numOrPromise);
}
} catch (e) {
console.log("caught", e);
}
})();
// 0
// 1
// 2
// caught 3
// called finally
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-for-in-and-for-of-statements](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-for-in-and-for-of-statements) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `for-await...of` | 63 | 79 | 57 | No | 50 | 11 | 63 | 63 | 57 | 46 | 11 | 8.0 | 1.0 | 10.0.0
8.10.0-10.0.0 |
See also
--------
* [`Symbol.asyncIterator`](../global_objects/symbol/asynciterator)
* [`for...of`](for...of)
javascript URIError URIError
========
The `URIError` object represents an error when a global URI handling function was used in a wrong way.
`URIError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`URIError()`](urierror/urierror) Creates a new `URIError` object.
Instance properties
-------------------
[`URIError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`URIError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`URIError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`URIError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`URIError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`URIError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`URIError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Catching an URIError
```
try {
decodeURIComponent('%')
} catch (e) {
console.log(e instanceof URIError) // true
console.log(e.message) // "malformed URI sequence"
console.log(e.name) // "URIError"
console.log(e.fileName) // "Scratchpad/1"
console.log(e.lineNumber) // 2
console.log(e.columnNumber) // 2
console.log(e.stack) // "@Scratchpad/2:2:3\n"
}
```
### Creating an URIError
```
try {
throw new URIError('Hello', 'someFile.js', 10)
} catch (e) {
console.log(e instanceof URIError) // true
console.log(e.message) // "Hello"
console.log(e.name) // "URIError"
console.log(e.fileName) // "someFile.js"
console.log(e.lineNumber) // 10
console.log(e.columnNumber) // 0
console.log(e.stack) // "@Scratchpad/2:2:9\n"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-urierror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-urierror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `URIError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `URIError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
* [`decodeURI()`](decodeuri)
* [`decodeURIComponent()`](decodeuricomponent)
* [`encodeURI()`](encodeuri)
* [`encodeURIComponent()`](encodeuricomponent)
javascript parseFloat() parseFloat()
============
The `parseFloat()` function parses a string argument and returns a floating point number.
Try it
------
Syntax
------
```
parseFloat(string)
```
### Parameters
`string` The value to parse, [coerced to a string](string#string_coercion). Leading [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) in this argument is ignored.
### Return value
A floating point number parsed from the given `string`, or [`NaN`](nan) when the first non-whitespace character cannot be converted to a number.
**Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. [`parseInt()`](parseint) and `parseFloat()` only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a [`Number`](number) 42.
Description
-----------
The `parseFloat` function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or `NaN`. The number syntax it accepts can be summarized as:
* The characters accepted by `parseFloat()` are plus sign (`+`), minus sign (`-` U+002D HYPHEN-MINUS), decimal digits (`0` – `9`), decimal point (`.`), exponent indicator (`e` or `E`), and the `"Infinity"` literal.
* The `+`/`-` signs can only appear strictly at the beginning of the string, or immediately following the `e`/`E` character. The decimal point can only appear once, and only before the `e`/`E` character. The `e`/`E` character can only appear once, and only if there is at least one digit before it.
* Leading spaces in the argument are trimmed and ignored.
* `parseFloat()` can also parse and return [`Infinity`](infinity) or `-Infinity` if the string starts with `"Infinity"` or `"-Infinity"` preceded by none or more white spaces.
* `parseFloat()` picks the longest substring starting from the beginning that generates a valid number literal. If it encounters an invalid character, it returns the number represented up to that point, ignoring the invalid character and all characters following it.
* If the argument's first character can't start a legal number literal per the syntax above, `parseFloat` returns [`NaN`](nan).
Syntax-wise, `parseFloat()` parses a subset of the syntax that the [`Number()`](number/number) function accepts. Namely, `parseFloat()` does not support non-decimal literals with `0x`, `0b`, or `0o` prefixes but supports everything else. However, `parseFloat()` is more lenient than `Number()` because it ignores trailing invalid characters, which would cause `Number()` to return `NaN`.
Similar to number literals and `Number()`, the number returned from `parseFloat()` may not be exactly equal to the number represented by the string, due to floating point range and inaccuracy. For numbers outside the `-1.7976931348623158e+308` – `1.7976931348623158e+308` range (see [`Number.MAX_VALUE`](number/max_value)), `-Infinity` or `Infinity` is returned.
Examples
--------
### Using parseFloat()
The following examples all return `3.14`:
```
parseFloat(3.14);
parseFloat("3.14");
parseFloat(" 3.14 ");
parseFloat("314e-2");
parseFloat("0.0314E+2");
parseFloat("3.14some non-digit characters");
parseFloat({
toString() {
return "3.14";
},
});
```
### parseFloat() returning NaN
The following example returns `NaN`:
```
parseFloat("FF2");
```
Anecdotally, because the string `NaN` itself is invalid syntax as accepted by `parseFloat()`, passing `"NaN"` returns `NaN` as well.
```
parseFloat("NaN"); // NaN
```
### Returning Infinity
Infinity values are returned when the number is outside the double-precision 64-bit IEEE 754-2019 format range:
```
parseFloat("1.7976931348623159e+308"); // Infinity
parseFloat("-1.7976931348623159e+308"); // -Infinity
```
Infinity is also returned when the string starts with `"Infinity"` or `"-Infinity"`:
```
parseFloat("Infinity"); // Infinity
parseFloat("-Infinity"); // -Infinity
```
### Interaction with BigInt values
`parseFloat()` does not handle [`BigInt`](bigint) values. It stops at the `n` character, and treats the preceding string as a normal integer, with possible loss of precision. If a BigInt value is passed to `parseFloat()`, it will be converted to a string, and the string will be parsed as a floating-point number, which may result in loss of precision as well.
```
parseFloat(900719925474099267n); // 900719925474099300
parseFloat("900719925474099267n"); // 900719925474099300
```
You should pass the string to the [`BigInt()`](bigint/bigint) function instead, without the trailing `n` character.
```
BigInt("900719925474099267");
// 900719925474099267n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-parsefloat-string](https://tc39.es/ecma262/multipage/global-object.html#sec-parsefloat-string) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `parseFloat` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`parseInt()`](parseint)
* [`Number.parseFloat()`](number/parsefloat)
* [`Number.parseInt()`](number/parseint)
* [`Number.prototype.toFixed()`](number/tofixed)
javascript BigInt BigInt
======
`BigInt` values represent numeric values which are [too large](number/max_safe_integer) to be represented by the `number` [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
Description
-----------
A **BigInt value**, also sometimes just called a **BigInt**, is a `bigint` [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive), created by appending `n` to the end of an integer literal, or by calling the [`BigInt()`](bigint/bigint) function (without the `new` operator) and giving it an integer value or string value.
```
const previouslyMaxSafeInteger = 9007199254740991n
const alsoHuge = BigInt(9007199254740991)
// 9007199254740991n
const hugeString = BigInt("9007199254740991")
// 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff")
// 9007199254740991n
const hugeOctal = BigInt("0o377777777777777777")
// 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111")
// 9007199254740991n
```
BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in [`Math`](math) object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.
### Type information
When tested against `typeof`, a BigInt value (`bigint` primitive) will give `"bigint"`:
```
typeof 1n === 'bigint' // true
typeof BigInt('1') === 'bigint' // true
```
A BigInt value can also be wrapped in an `Object`:
```
typeof Object(1n) === 'object' // true
```
### Operators
The following operators may be used with BigInt values or object-wrapped BigInt values:
```
+ * - % **
```
[Bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) are supported as well, except `>>>` (zero-fill right shift), as every BigInt value is signed.
Also unsupported is the unary operator (`+`), [in order to not break asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs).
```
const previousMaxSafe = BigInt(Number.MAX\_SAFE\_INTEGER)
// 9007199254740991n
const maxPlusOne = previousMaxSafe + 1n
// 9007199254740992n
const theFuture = previousMaxSafe + 2n
// 9007199254740993n, this works now!
const multi = previousMaxSafe \* 2n
// 18014398509481982n
const subtr = multi - 10n
// 18014398509481972n
const mod = multi % 10n
// 2n
const bigN = 2n \*\* 54n
// 18014398509481984n
bigN \* -1n
// -18014398509481984n
```
The `/` operator also works as expected with whole numbers — but operations with a fractional result will be truncated when used with a BigInt value — they won't return any fractional digits.
```
const expected = 4n / 2n
// 2n
const truncated = 5n / 2n
// 2n, not 2.5n
```
### Comparisons
A BigInt value is not strictly equal to a Number value, but it *is* loosely so:
```
0n === 0
// false
0n == 0
// true
```
A Number value and a BigInt value may be compared as usual:
```
1n < 2
// true
2n > 1
// true
2 > 2
// false
2n > 2
// false
2n >= 2
// true
```
BigInt values and Number values may be mixed in arrays and sorted:
```
const mixed = [4n, 6, -12n, 10, 4, 0, 0n]
// [4n, 6, -12n, 10, 4, 0, 0n]
mixed.sort() // default sorting behavior
// [ -12n, 0, 0n, 10, 4n, 4, 6 ]
mixed.sort((a, b) => a - b)
// won't work since subtraction will not work with mixed types
// TypeError: can't convert BigInt value to Number value
// sort with an appropriate numeric comparator
mixed.sort((a, b) => (a < b) ? -1 : ((a > b) ? 1 : 0))
// [ -12n, 0, 0n, 4n, 4, 6, 10 ]
```
Note that comparisons with `Object`-wrapped BigInt values act as with other objects, only indicating equality when the same object instance is compared:
```
Object(0n) === 0n // false
Object(0n) === Object(0n) // false
const o = Object(0n)
o === o // true
```
### Conditionals
A BigInt value follows the same conversion rules as Numbers when:
* it is converted to a [`Boolean`](boolean): via the [`Boolean`](boolean) function;
* when used with [logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) `||`, `&&`, and `!`; or
* within a conditional test like an [`if`](../statements/if...else) statement.
Namely, only `0n` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy); everything else is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
```
if (0n) {
console.log('Hello from the if!')
} else {
console.log('Hello from the else!')
}
// "Hello from the else!"
0n || 12n
// 12n
0n && 12n
// 0n
Boolean(0n)
// false
Boolean(12n)
// true
!12n
// false
!0n
// true
```
### BigInt coercion
Many built-in operations that expect BigInts first coerce their arguments to BigInts. [The operation](https://tc39.es/ecma262/#sec-tobigint) can be summarized as follows:
* BigInts are returned as-is.
* [`undefined`](undefined) and [`null`](../operators/null) throw a [`TypeError`](typeerror).
* `true` turns into `1n`; `false` turns into `0n`.
* Strings are converted by parsing them as if they contain an integer literal. Any parsing failure results in a [`SyntaxError`](syntaxerror). The syntax is a subset of [string numeric literals](number#number_coercion), where decimal points or exponent indicators are not allowed.
* [Numbers](number) throw a [`TypeError`](typeerror) to prevent unintended implicit coercion causing loss of precision.
* [Symbols](symbol) throw a [`TypeError`](typeerror).
* Objects are first [converted to a primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling their [`[@@toPrimitive]()`](symbol/toprimitive) (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. The resulting primitive is then converted to a BigInt.
The best way to achieve nearly the same effect in JavaScript is through the [`BigInt()`](bigint/bigint) function: `BigInt(x)` uses the same algorithm to convert `x`, except that [Numbers](number) don't throw a [`TypeError`](typeerror), but are converted to BigInts if they are integers.
Note that built-in operations expecting BigInts often truncate the BigInt to a fixed width after coercion. This includes [`BigInt.asIntN()`](bigint/asintn), [`BigInt.asUintN()`](bigint/asuintn), and methods of [`BigInt64Array`](bigint64array) and [`BigUint64Array`](biguint64array).
Constructor
-----------
[`BigInt()`](bigint/bigint) Creates a new BigInt value.
Static methods
--------------
[`BigInt.asIntN()`](bigint/asintn) Clamps a BigInt value to a signed integer value, and returns that value.
[`BigInt.asUintN()`](bigint/asuintn) Clamps a BigInt value to an unsigned integer value, and returns that value.
Instance properties
-------------------
`BigInt.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"BigInt"`. This property is used in [`Object.prototype.toString()`](object/tostring). However, because `BigInt` also has its own [`toString()`](bigint/tostring) method, this property is not used unless you call [`Object.prototype.toString.call()`](function/call) with a BigInt as `thisArg`.
Instance methods
----------------
[`BigInt.prototype.toLocaleString()`](bigint/tolocalestring) Returns a string with a language-sensitive representation of this BigInt value. Overrides the [`Object.prototype.toLocaleString()`](object/tolocalestring) method.
[`BigInt.prototype.toString()`](bigint/tostring) Returns a string representing this BigInt value in the specified radix (base). Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`BigInt.prototype.valueOf()`](bigint/valueof) Returns this BigInt value. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
Usage recommendations
---------------------
### Coercion
Because coercing between Number values and BigInt values can lead to loss of precision, the following are recommended:
* Only use a BigInt value when values greater than 2^53 are reasonably expected.
* Don't coerce between BigInt values and Number values.
### Cryptography
The operations supported on BigInt values are not constant-time and are thus open to [timing attacks](https://en.wikipedia.org/wiki/Timing_attack). JavaScript BigInts therefore could be dangerous for use in cryptography without mitigating factors. As a very generic example, an attacker could measure the time difference between `101n ** 65537n` and `17n ** 9999n`, and deduce the magnitude of secrets, such as private keys, based on the time elapsed. If you still have to use BigInts, take a look at the [Timing attack FAQ](https://timing.attacks.cr.yp.to/programming.html) for general advice regarding the issue.
### Use within JSON
Using [`JSON.stringify()`](json/stringify) with any BigInt value will raise a `TypeError`, as BigInt values aren't serialized in JSON by default. However, `JSON.stringify()` specifically leaves a backdoor for BigInt values: it would try to call the BigInt's `toJSON()` method. (It doesn't do so for any other primitive values.) Therefore, you can implement your own `toJSON()` method (which is one of the few cases where patching built-in objects is not explicitly discouraged):
```
BigInt.prototype.toJSON = function () {
return this.toString();
};
```
Instead of throwing, `JSON.stringify()` now produces a string like this:
```
console.log(JSON.stringify({ a: 1n }));
// {"a":"1"}
```
If you do not wish to patch `BigInt.prototype`, you can use the [`replacer`](json/stringify#the_replacer_parameter) parameter of `JSON.stringify` to serialize BigInt values:
```
const replacer = (key, value) =>
typeof value === "bigint" ? value.toString() : value;
const data = {
number: 1,
big: 18014398509481982n,
};
const stringified = JSON.stringify(data, replacer);
console.log(stringified);
// {"number":1,"big":"18014398509481982"}
```
If you have JSON data containing values you know will be large integers, you can use the [`reviver`](json/parse#using_the_reviver_parameter) parameter of `JSON.parse` to handle them:
```
const reviver = (key, value) => key === "big" ? BigInt(value) : value;
const payload = '{"number":1,"big":"18014398509481982"}';
const parsed = JSON.parse(payload, reviver);
console.log(parsed);
// { number: 1, big: 18014398509481982n }
```
**Note:** While it's possible to make the replacer of `JSON.stringify()` generic and properly serialize BigInt values for all objects, the reviver of `JSON.parse()` must be specific to the payload shape you expect, because the serialization is *lossy*: it's not possible to distinguish between a string that represents a BigInt and a normal string.
Examples
--------
### Calculating Primes
```
// Returns true if the passed BigInt value is a prime number
function isPrime(p) {
for (let i = 2n; i \* i <= p; i++) {
if (p % i === 0n) return false;
}
return true
}
// Takes a BigInt value as an argument, returns nth prime number as a BigInt value
function nthPrime(nth) {
let maybePrime = 2n
let prime = 0n
while (nth >= 0n) {
if (isPrime(maybePrime)) {
nth--
prime = maybePrime
}
maybePrime++
}
return prime
}
nthPrime(20n)
// 73n
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint-objects](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `BigInt` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `BigInt` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `asIntN` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `asUintN` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `toLocaleString` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `toString` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `valueOf` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`Number`](number)
* [`Number.MAX_SAFE_INTEGER`](number/max_safe_integer)
| programming_docs |
javascript Reflect Reflect
=======
`Reflect` is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of [proxy handlers](proxy/proxy). `Reflect` is not a function object, so it's not constructible.
Description
-----------
Unlike most global objects, `Reflect` is not a constructor. You cannot use it with a [`new` operator](../operators/new) or invoke the `Reflect` object as a function. All properties and methods of `Reflect` are static (just like the [`Math`](math) object).
The `Reflect` object provides the following static functions which have the same names as the [proxy handler methods](proxy/proxy).
Some of these methods are also the same as corresponding methods on [`Object`](object), although they do have [some subtle differences](reflect/comparing_reflect_and_object_methods) between them.
Static properties
-----------------
`Reflect[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Reflect"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Static methods
--------------
[`Reflect.apply()`](reflect/apply) Calls a `target` function with arguments as specified by the `argumentsList` parameter. See also [`Function.prototype.apply()`](function/apply).
[`Reflect.construct()`](reflect/construct) The [`new` operator](../operators/new) as a function. Equivalent to calling `new target(...argumentsList)`. Also provides the option to specify a different prototype.
[`Reflect.defineProperty()`](reflect/defineproperty) Similar to [`Object.defineProperty()`](object/defineproperty). Returns a boolean that is `true` if the property was successfully defined.
[`Reflect.deleteProperty()`](reflect/deleteproperty) The [`delete` operator](../operators/delete) as a function. Equivalent to calling `delete target[propertyKey]`.
[`Reflect.get()`](reflect/get) Returns the value of the property. Works like getting a property from an object (`target[propertyKey]`) as a function.
[`Reflect.getOwnPropertyDescriptor()`](reflect/getownpropertydescriptor) Similar to [`Object.getOwnPropertyDescriptor()`](object/getownpropertydescriptor). Returns a property descriptor of the given property if it exists on the object, [`undefined`](undefined) otherwise.
[`Reflect.getPrototypeOf()`](reflect/getprototypeof) Same as [`Object.getPrototypeOf()`](object/getprototypeof).
[`Reflect.has()`](reflect/has) Returns a boolean indicating whether the target has the property. Either as own or inherited. Works like the [`in` operator](../operators/in) as a function.
[`Reflect.isExtensible()`](reflect/isextensible) Same as [`Object.isExtensible()`](object/isextensible). Returns a boolean that is `true` if the target is extensible.
[`Reflect.ownKeys()`](reflect/ownkeys) Returns an array of the target object's own (not inherited) property keys.
[`Reflect.preventExtensions()`](reflect/preventextensions) Similar to [`Object.preventExtensions()`](object/preventextensions). Returns a boolean that is `true` if the update was successful.
[`Reflect.set()`](reflect/set) A function that assigns values to properties. Returns a boolean that is `true` if the update was successful.
[`Reflect.setPrototypeOf()`](reflect/setprototypeof) A function that sets the prototype of an object. Returns a boolean that is `true` if the update was successful.
Examples
--------
### Detecting whether an object contains certain properties
```
const duck = {
name: "Maurice",
color: "white",
greeting() {
console.log(`Quaaaack! My name is ${this.name}`);
},
};
Reflect.has(duck, "color");
// true
Reflect.has(duck, "haircut");
// false
```
### Returning the object's own keys
```
Reflect.ownKeys(duck);
// [ "name", "color", "greeting" ]
```
### Adding a new property to the object
```
Reflect.set(duck, "eyes", "black");
// returns "true" if successful
// "duck" now contains the property "eyes: 'black'"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-reflect-object](https://tc39.es/ecma262/multipage/reflection.html#sec-reflect-object) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Reflect` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `apply` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `construct` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `defineProperty` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `deleteProperty` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `get` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `getOwnPropertyDescriptor` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `getPrototypeOf` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `has` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `isExtensible` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `ownKeys` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `preventExtensions` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `set` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `setPrototypeOf` | 49 | 12 | 42 | No | 36 | 10 | 49 | 49 | 42 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* The [`Proxy`](proxy) global object
* The [`Proxy()` constructor](proxy/proxy)
javascript Uint32Array Uint32Array
===========
The `Uint32Array` typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Uint32Array()`](uint32array/uint32array) Creates a new `Uint32Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Uint32Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of `Uint32Array`.
[`Uint32Array.name`](typedarray/name) Returns the string value of the constructor name. `"Uint32Array"` in the case of `Uint32Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Uint32Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of a `Uint32Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a Uint32Array
```
// From a length
const uint32 = new Uint32Array(2);
uint32[0] = 42;
console.log(uint32[0]); // 42
console.log(uint32.length); // 2
console.log(uint32.BYTES\_PER\_ELEMENT); // 4
// From an array
const x = new Uint32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Uint32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uint32FromIterable = new Uint32Array(iterable);
console.log(uint32FromIterable);
// Uint32Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Uint32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Uint32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript AsyncGenerator AsyncGenerator
==============
The `AsyncGenerator` object is returned by an [async generator function](../statements/async_function*) and it conforms to both the [async iterable protocol and the async iterator protocol](../iteration_protocols#the_async_iterator_and_async_iterable_protocols).
Async generator methods always yield [`Promise`](promise) objects.
Try it
------
Constructor
-----------
The `AsyncGenerator` constructor is not available globally. Instances of `AsyncGenerator` must be returned from [async generator functions](../statements/async_function*)
```
async function\* createAsyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next()
.then((res) => console.log(res.value)); // 1
asyncGen.next()
.then((res) => console.log(res.value)); // 2
asyncGen.next()
.then((res) => console.log(res.value)); // 3
```
Instance properties
-------------------
`AsyncGenerator.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"AsyncGenerator"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`AsyncGenerator.prototype.next()`](asyncgenerator/next) Returns a [`Promise`](promise) which will be resolved with the given value yielded by the [`yield`](../operators/yield) expression.
[`AsyncGenerator.prototype.return()`](asyncgenerator/return) Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](../statements/try...catch#the_finally-block) block.
[`AsyncGenerator.prototype.throw()`](asyncgenerator/throw) Acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.
Examples
--------
### Async generator iteration
The following example iterates over an async generator, logging values 1–6 to the console at decreasing time intervals. Notice how each time a Promise is yielded, but it's automatically resolved within the `for await...of` loop.
```
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
return new Promise((resolve /\*, reject\*/) => {
setTimeout(() => resolve(value), time);
});
}
async function\* generate() {
yield delayedValue(2000, 1);
yield delayedValue(100, 2);
yield delayedValue(500, 3);
yield delayedValue(250, 4);
yield delayedValue(125, 5);
yield delayedValue(50, 6);
console.log('All done!');
}
async function main() {
for await (const value of generate()) {
console.log('value', value);
}
}
main()
.catch((e) => console.error(e));
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgenerator-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgenerator-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `AsyncGenerator` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
| `next` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
| `return` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
| `throw` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [function\*](../statements/function*)
* [async function\*](../statements/async_function*)
* [`function*` expression](../operators/function*)
* [Generator Function](generatorfunction)
* [Async Generator Function](asyncgeneratorfunction)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
javascript Infinity Infinity
========
The global property `Infinity` is a numeric value representing infinity.
Try it
------
Value
-----
The same number value as [`Number.POSITIVE_INFINITY`](number/positive_infinity).
| Property attributes of `Infinity` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`Infinity` is a property of the *global object*. In other words, it is a variable in global scope.
The value `Infinity` (positive infinity) is greater than any other number.
This value behaves slightly differently than mathematical infinity; see [`Number.POSITIVE_INFINITY`](number/positive_infinity) for details.
Examples
--------
### Using Infinity
```
console.log(Infinity); /\* Infinity \*/
console.log(Infinity + 1); /\* Infinity \*/
console.log(Math.pow(10, 1000)); /\* Infinity \*/
console.log(Math.log(0)); /\* -Infinity \*/
console.log(1 / Infinity); /\* 0 \*/
console.log(1 / 0); /\* Infinity \*/
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-value-properties-of-the-global-object-infinity](https://tc39.es/ecma262/multipage/global-object.html#sec-value-properties-of-the-global-object-infinity) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Infinity` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.NEGATIVE_INFINITY`](number/negative_infinity)
* [`Number.POSITIVE_INFINITY`](number/positive_infinity)
* [`Number.isFinite`](number/isfinite)
javascript Map Map
===
The `Map` object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and [primitive values](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)) may be used as either a key or a value.
Try it
------
Description
-----------
`Map` objects are collections of key-value pairs. A key in the `Map` **may only occur once**; it is unique in the `Map`'s collection. A `Map` object is iterated by key-value pairs — a [`for...of`](../statements/for...of) loop returns a 2-member array of `[key, value]` for each iteration. Iteration happens in *insertion order*, which corresponds to the order in which each key-value pair was first inserted into the map by the [`set()`](map/set) method (that is, there wasn't a key with the same value already in the map when `set()` was called).
The specification requires maps to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).
### Key equality
Value equality is based on the [SameValueZero](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) algorithm. (It used to use [SameValue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is), which treated `0` and `-0` as different. Check [browser compatibility](#browser_compatibility).) This means [`NaN`](nan) is considered the same as `NaN` (even though `NaN !== NaN`) and all other values are considered equal according to the semantics of the `===` operator.
### Objects vs. Maps
[`Object`](object) is similar to `Map`—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), `Object` has been used as `Map` historically.
However, there are important differences that make `Map` preferable in some cases:
| | Map | Object |
| --- | --- | --- |
| Accidental Keys | A `Map` does not contain any keys by default. It only contains what is explicitly put into it. | An `Object` has a prototype, so it contains default keys that could collide with your own keys if you're not careful. **Note:** This can be bypassed by using [`Object.create(null)`](object/create), but this is seldom done. |
| Security | A `Map` is safe to use with user-provided keys and values. | Setting user-provided key-value pairs on an `Object` may allow an attacker to override the object's prototype, which can lead to [object injection attacks](https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md) . Like the accidental keys issue, this can also be mitigated by using a `null`-prototype object. |
| Key Types | A `Map`'s keys can be any value (including functions, objects, or any primitive). | The keys of an `Object` must be either a [`String`](string) or a [`Symbol`](symbol). |
| Key Order | The keys in `Map` are ordered in a simple, straightforward way: A `Map` object iterates entries, keys, and values in the order of entry insertion. | Although the keys of an ordinary `Object` are ordered now, this was not always the case, and the order is complex. As a result, it's best not to rely on property order. The order was first defined for own properties only in ECMAScript 2015; ECMAScript 2020 defines order for inherited properties as well. See the [OrdinaryOwnPropertyKeys](https://tc39.es/ecma262/#sec-ordinaryownpropertykeys) and [EnumerateObjectProperties](https://tc39.es/ecma262/#sec-enumerate-object-properties) abstract specification operations. But note that no single mechanism iterates **all** of an object's properties; the various mechanisms each include different subsets of properties. ([`for-in`](../statements/for...in) includes only enumerable string-keyed properties; [`Object.keys`](object/keys) includes only own, enumerable, string-keyed properties; [`Object.getOwnPropertyNames`](object/getownpropertynames) includes own, string-keyed properties even if non-enumerable; [`Object.getOwnPropertySymbols`](object/getownpropertysymbols) does the same for just `Symbol`-keyed properties, etc.) |
| Size | The number of items in a `Map` is easily retrieved from its [`size`](map/size) property. | The number of items in an `Object` must be determined manually. |
| Iteration | A `Map` is an [iterable](../iteration_protocols), so it can be directly iterated. | `Object` does not implement an [iteration protocol](../iteration_protocols#the_iterable_protocol), and so objects are not directly iterable using the JavaScript [for...of](../statements/for...of) statement (by default). **Note:** * An object can implement the iteration protocol, or you can get an iterable for an object using [`Object.keys`](object/keys) or [`Object.entries`](object/entries).
* The [for...in](../statements/for...in) statement allows you to iterate over the *enumerable* properties of an object.
|
| Performance | Performs better in scenarios involving frequent additions and removals of key-value pairs. | Not optimized for frequent additions and removals of key-value pairs. |
| Serialization and parsing | No native support for serialization or parsing. (But you can build your own serialization and parsing support for `Map` by using [`JSON.stringify()`](json/stringify) with its *replacer* argument, and by using [`JSON.parse()`](json/parse) with its *reviver* argument. See the Stack Overflow question [How do you JSON.stringify an ES6 Map?](https://stackoverflow.com/q/29085197/)). | Native support for serialization from [`Object`](object) to JSON, using [`JSON.stringify()`](json/stringify). Native support for parsing from JSON to [`Object`](object), using [`JSON.parse()`](json/parse). |
### Setting object properties
Setting Object properties works for Map objects as well, and can cause considerable confusion.
Therefore, this appears to work in a way:
```
const wrongMap = new Map();
wrongMap['bla'] = 'blaa';
wrongMap['bla2'] = 'blaaa2';
console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }
```
But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Other operations on the data fail:
```
wrongMap.has('bla') // false
wrongMap.delete('bla') // false
console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' }
```
The correct usage for storing data in the Map is through the `set(key, value)` method.
```
const contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1
```
Constructor
-----------
[`Map()`](map/map) Creates a new `Map` object.
Static properties
-----------------
[`get Map[@@species]`](map/@@species) The constructor function that is used to create derived objects.
Instance properties
-------------------
`Map.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Map"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`Map.prototype.size`](map/size) Returns the number of key/value pairs in the `Map` object.
Instance methods
----------------
[`Map.prototype.clear()`](map/clear) Removes all key-value pairs from the `Map` object.
[`Map.prototype.delete()`](map/delete) Returns `true` if an element in the `Map` object existed and has been removed, or `false` if the element does not exist. `map.has(key)` will return `false` afterwards.
[`Map.prototype.get()`](map/get) Returns the value associated to the passed key, or `undefined` if there is none.
[`Map.prototype.has()`](map/has) Returns a boolean indicating whether a value has been associated with the passed key in the `Map` object or not.
[`Map.prototype.set()`](map/set) Sets the value for the passed key in the `Map` object. Returns the `Map` object.
[`Map.prototype[@@iterator]()`](map/@@iterator) Returns a new Iterator object that contains a two-member array of `[key, value]` for each element in the `Map` object in insertion order.
[`Map.prototype.keys()`](map/keys) Returns a new Iterator object that contains the keys for each element in the `Map` object in insertion order.
[`Map.prototype.values()`](map/values) Returns a new Iterator object that contains the values for each element in the `Map` object in insertion order.
[`Map.prototype.entries()`](map/entries) Returns a new Iterator object that contains a two-member array of `[key, value]` for each element in the `Map` object in insertion order.
[`Map.prototype.forEach()`](map/foreach) Calls `callbackFn` once for each key-value pair present in the `Map` object, in insertion order. If a `thisArg` parameter is provided to `forEach`, it will be used as the `this` value for each callback.
Examples
--------
### Using the Map object
```
const myMap = new Map();
const keyString = 'a string';
const keyObj = {};
const keyFunc = function() {};
// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, 'value associated with keyObj');
myMap.set(keyFunc, 'value associated with keyFunc');
console.log(myMap.size); // 3
// getting the values
console.log(myMap.get(keyString)); // "value associated with 'a string'"
console.log(myMap.get(keyObj)); // "value associated with keyObj"
console.log(myMap.get(keyFunc)); // "value associated with keyFunc"
console.log(myMap.get('a string')); // "value associated with 'a string'", because keyString === 'a string'
console.log(myMap.get({})); // undefined, because keyObj !== {}
console.log(myMap.get(function() {})); // undefined, because keyFunc !== function () {}
```
### Using NaN as Map keys
[`NaN`](nan) can also be used as a key. Even though every `NaN` is not equal to itself (`NaN !== NaN` is true), the following example works because `NaN`s are indistinguishable from each other:
```
const myMap = new Map();
myMap.set(NaN, 'not a number');
myMap.get(NaN);
// "not a number"
const otherNaN = Number('foo');
myMap.get(otherNaN);
// "not a number"
```
### Iterating Map with for...of
Maps can be iterated using a `for...of` loop:
```
const myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (const [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
// 0 = zero
// 1 = one
for (const key of myMap.keys()) {
console.log(key);
}
// 0
// 1
for (const value of myMap.values()) {
console.log(value);
}
// zero
// one
for (const [key, value] of myMap.entries()) {
console.log(`${key} = ${value}`);
}
// 0 = zero
// 1 = one
```
### Iterating Map with forEach()
Maps can be iterated using the [`forEach()`](map/foreach) method:
```
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
// 0 = zero
// 1 = one
```
### Relation with Array objects
```
const kvArray = [['key1', 'value1'], ['key2', 'value2']];
// Use the regular Map constructor to transform a 2D key-value Array into a map
const myMap = new Map(kvArray);
console.log(myMap.get('key1')); // "value1"
// Use Array.from() to transform a map into a 2D key-value Array
console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray
// A succinct way to do the same, using the spread syntax
console.log([...myMap]);
// Or use the keys() or values() iterators, and convert them to an array
console.log(Array.from(myMap.keys())); // ["key1", "key2"]
```
### Cloning and merging Maps
Just like `Array`s, `Map`s can be cloned:
```
const original = new Map([
[1, 'one'],
]);
const clone = new Map(original);
console.log(clone.get(1)); // one
console.log(original === clone); // false (useful for shallow comparison)
```
**Note:** Keep in mind that *the data itself* is not cloned.
Maps can be merged, maintaining key uniqueness:
```
const first = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
const second = new Map([
[1, 'uno'],
[2, 'dos'],
]);
// Merge two maps. The last repeated key wins.
// Spread syntax essentially converts a Map to an Array
const merged = new Map([...first, ...second]);
console.log(merged.get(1)); // uno
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three
```
Maps can be merged with Arrays, too:
```
const first = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
const second = new Map([
[1, 'uno'],
[2, 'dos'],
]);
// Merge maps with an array. The last repeated key wins.
const merged = new Map([...first, ...second, [1, 'eins']]);
console.log(merged.get(1)); // eins
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-map-objects](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 10 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
| `@@species` | 51 | 13 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `@@toStringTag` | 44 | 79 | 51 | No | 31 | 9.1 | 44 | 44 | 51 | 32 | 9.3 | 4.0 | 1.0 | 6.0.0 |
| `Map` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `Map` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `clear` | 38 | 12 | 19 | 11 | 25 | 8 | 38 | 38 | 19 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `delete` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `entries` | 38 | 12 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `forEach` | 38 | 12 | 25 | 11 | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `get` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `has` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `key_equality_for_zeros` | 38 | 12 | 29 | No | 25 | 9 | 38 | 38 | 29 | 25 | 9 | 3.0 | 1.0 | 4.0.0 |
| `keys` | 38 | 12 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `set` | 38 | 12 | 13 | 11
Returns 'undefined' instead of the 'Map' object. | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `size` | 38 | 12 | 19
From Firefox 13 to Firefox 18, the `size` property was implemented as a `Map.prototype.size()` method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification. | 11 | 25 | 8 | 38 | 38 | 19
From Firefox 13 to Firefox 18, the `size` property was implemented as a `Map.prototype.size()` method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification. | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `values` | 38 | 12 | 20 | No | 25 | 8 | 38 | 38 | 20 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* A polyfill of `Map` is available in [`core-js`](https://github.com/zloirock/core-js#map)
* [`Set`](set)
* [`WeakMap`](weakmap)
* [`WeakSet`](weakset)
| programming_docs |
javascript eval() eval()
======
**Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [Never use eval()!](#never_use_eval!), below.
The `eval()` function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
Try it
------
Syntax
------
```
eval(script)
```
### Parameters
`script` A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](../statements/import) declarations (which can only exist in modules) are not allowed.
### Return value
The completion value of evaluating the given code. If the completion value is empty, [`undefined`](undefined) is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged.
### Exceptions
Throws any exception that occurs during evaluation of the code, including [`SyntaxError`](syntaxerror) if `script` fails to be parsed as a script.
Description
-----------
`eval()` is a function property of the global object.
The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](../statements/let) is undefined), so it's recommended to not rely on statements' completion values.
In strict mode, declaring a variable named `eval` or re-assigning `eval` is a [`SyntaxError`](syntaxerror).
```
"use strict";
const eval = 1; // SyntaxError: Unexpected eval or arguments in strict mode
```
If the argument of `eval()` is not a string, `eval()` returns the argument unchanged. In the following example, passing a `String` object instead of a primitive causes `eval()` to return the `String` object rather than evaluating the string.
```
eval(new String("2 + 2")); // returns a String object containing "2 + 2"
eval("2 + 2"); // returns 4
```
To work around the issue in a generic fashion, you can [coerce the argument to a string](string#string_coercion) yourself before passing it to `eval()`.
```
const expression = new String("2 + 2");
eval(String(expression)); // returns 4
```
### Direct and indirect eval
There are two modes of `eval()` calls: *direct* eval and *indirect* eval. Direct eval only has one form: `eval( )` (the invoked function's name is `eval` and its value is the global `eval` function). Everything else, including invoking it via an aliased variable, via a member access or other expression, or through the optional chaining [`?.`](../operators/optional_chaining) operator, is indirect.
```
// Indirect call using the comma operator to return eval
(0, eval)("x + y");
// Indirect call through optional chaining
eval?.("x + y");
// Indirect call using a variable to store and return eval
const geval = eval;
geval("x + y");
// Indirect call through member access
const obj = { eval };
obj.eval("x + y");
```
Indirect eval can be seen as if the code is evaluated within a separate `<script>` tag. This means:
* Indirect eval works in the global scope rather than the local scope, and the code being evaluated doesn't have access to local variables within the scope where it's being called.
```
function test() {
const x = 2;
const y = 4;
// Direct call, uses local scope
console.log(eval("x + y")); // Result is 6
console.log(eval?.("x + y")); // Uses global scope, throws because x is undefined
}
```
* Indirect `eval` would not inherit the strictness of the surrounding context, and would only be in [strict mode](../strict_mode) if the source string itself has a `"use strict"` directive.
```
function strictContext() {
"use strict";
eval?.(`with (Math) console.log(PI);`);
}
function strictContextStrictEval() {
"use strict";
eval?.(`"use strict"; with (Math) console.log(PI);`);
}
strictContext(); // Logs 3.141592653589793
strictContextStrictEval(); // Throws a SyntaxError because the source string is in strict mode
```
On the other hand, direct eval inherits the strictness of the invoking context.
```
function nonStrictContext() {
eval(`with (Math) console.log(PI);`);
}
function strictContext() {
"use strict";
eval(`with (Math) console.log(PI);`);
}
nonStrictContext(); // Logs 3.141592653589793
strictContext(); // Throws a SyntaxError because it's in strict mode
```
* `var`-declared variables and [function declarations](../statements/function) would go into the surrounding scope if the source string is not interpreted in strict mode — for indirect eval, they become global variables. If it's a direct eval in a strict mode context, or if the `eval` source string itself is in strict mode, then `var` and function declarations do not "leak" into the surrounding scope.
```
// Neither context nor source string is strict,
// so var creates a variable in the surrounding scope
eval("var a = 1;");
console.log(a); // 1
// Context is not strict, but eval source is strict,
// so b is scoped to the evaluated script
eval("'use strict'; var b = 1;");
console.log(b); // ReferenceError: b is not defined
function strictContext() {
"use strict";
// Context is strict, but this is indirect and the source
// string is not strict, so c is still global
eval?.("var c = 1;");
// Direct eval in a strict context, so d is scoped
eval("var d = 1;");
}
strictContext();
console.log(c); // 1
console.log(d); // ReferenceError: d is not defined
```
[`let`](../statements/let) and [`const`](../statements/const) declarations within the evaluated string are always scoped to that script.
* Direct eval may have access to additional contextual expressions. For example, in a function's body, one can use [`new.target`](../operators/new.target):
```
function Ctor() {
eval("console.log(new.target)");
}
new Ctor(); // [Function: Ctor]
```
### Never use eval()!
Using direct `eval()` suffers from multiple problems:
* `eval()` executes the code it's passed with the privileges of the caller. If you run `eval()` with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, allowing third-party code to access the scope in which `eval()` was invoked (if it's a direct eval) can lead to possible attacks that reads or changes local variables.
* `eval()` is slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.
* Modern JavaScript interpreters convert JavaScript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of `eval()` will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through `eval()`, such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.
* Minifiers give up on any minification if the scope is transitively depended on by `eval()`, because otherwise `eval()` cannot read the correct variable at runtime.
There are many cases where the use of `eval()` or related methods can be optimized or avoided altogether.
#### Using indirect eval()
Consider this code:
```
function looseJsonParse(obj) {
return eval(`(${obj})`);
}
console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }"));
```
Simply using indirect eval and forcing strict mode can make the code much better:
```
function looseJsonParse(obj) {
return eval?.(`"use strict";(${obj})`);
}
console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }"));
```
The two code snippets above may seem to work the same way, but they do not; the first one using direct eval suffers from multiple problems.
* It is a great deal slower, due to more scope inspections. Notice `c: new Date()` in the evaluated string. In the indirect eval version, the object is being evaluated in the global scope, so it is safe for the interpreter to assume that `Date` refers to the global `Date()` constructor instead of a local variable called `Date`. However, in the code using direct eval, the interpreter cannot assume this. For example, in the following code, `Date` in the evaluated string doesn't refer to `window.Date()`.
```
function looseJsonParse(obj) {
function Date() {}
return eval(`(${obj})`);
}
console.log(looseJsonParse(`{ a: 4 - 1, b: function () {}, c: new Date() }`));
```
Thus, in the `eval()` version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called `Date()`.
* If not using strict mode, `var` declarations within the `eval()` source becomes variables in the surrounding scope. This leads to hard-to-debug issues if the string is acquired from external input, especially if there's an existing variable with the same name.
* Direct eval can read and mutate bindings in the surrounding scope, which may lead to external input corrupting local data.
* When using direct `eval`, especially when the eval source cannot be proven to be in strict mode, the engine — and build tools — have to disable all optimizations related to inlining, because the `eval()` source can depend on any variable name in its surrounding scope.
However, using indirect `eval()` does not allow passing extra bindings other than existing global variables for the evaluated source to read. If you need to specify additional variables that the evaluated source should have access to, consider using the `Function()` constructor.
#### Using the Function() constructor
The [`Function()`](function) constructor is very similar to the indirect eval example above: it also evaluates the JavaScript source passed to it in the global scope without reading or mutating any local bindings, and therefore allows engines to do more optimizations than direct `eval()`.
The difference between `eval()` and `Function()` is that the source string passed to `Function()` is parsed as a function body, not as a script. There are a few nuances — for example, you can use `return` statements at the top level of a function body, but not in a script.
The `Function()` constructor is useful if you wish to create local bindings within your eval source, by passing the variables as parameter bindings.
```
function Date(n) {
return [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
][n % 7 || 0];
}
function runCodeWithDateFunction(obj) {
return Function("Date", `"use strict";return (${obj});`)(Date);
}
console.log(runCodeWithDateFunction("Date(5)")); // Saturday
```
Both `eval()` and `Function()` implicitly evaluate arbitrary code, and are forbidden in strict [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) settings. There are also additional safer (and faster!) alternatives to `eval()` or `Function()` for common use-cases.
#### Using bracket accessors
You should not use `eval()` to access properties dynamically. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with `eval()`:
```
const obj = { a: 20, b: 30 };
const propName = getPropName(); // returns "a" or "b"
const result = eval(`obj.${propName}`);
```
However, `eval()` is not necessary here — in fact, it's more error-prone, because if `propName` is not a valid identifier, it leads to a syntax error. Moreover, if `getPropName` is not a function you control, this may lead to execution of arbitrary code. Instead, use the [property accessors](../operators/property_accessors), which are much faster and safer:
```
const obj = { a: 20, b: 30 };
const propName = getPropName(); // returns "a" or "b"
const result = obj[propName]; // obj["a"] is the same as obj.a
```
You can even use this method to access descendant properties. Using `eval()`, this would look like:
```
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath(); // suppose it returns "a.b.c"
const result = eval(`obj.${propPath}`); // 0
```
Avoiding `eval()` here could be done by splitting the property path and looping through the different properties:
```
function getDescendantProp(obj, desc) {
const arr = desc.split(".");
while (arr.length) {
obj = obj[arr.shift()];
}
return obj;
}
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath(); // suppose it returns "a.b.c"
const result = getDescendantProp(obj, propPath); // 0
```
Setting a property that way works similarly:
```
function setDescendantProp(obj, desc, value) {
const arr = desc.split(".");
while (arr.length > 1) {
obj = obj[arr.shift()];
}
return (obj[arr[0]] = value);
}
const obj = { a: { b: { c: 0 } } };
const propPath = getPropPath(); // suppose it returns "a.b.c"
const result = setDescendantProp(obj, propPath, 1); // obj.a.b.c is now 1
```
However, beware that using bracket accessors with unconstrained input is not safe either — it may lead to [object injection attacks](https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md).
#### Using callbacks
JavaScript has [first-class functions](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function), which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:
```
// Instead of setTimeout("…", 1000) use:
setTimeout(() => {
// …
}, 1000);
// Instead of elt.setAttribute("onclick", "…") use:
elt.addEventListener("click", () => {
// …
});
```
[Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) are also helpful as a way to create parameterized functions without concatenating strings.
#### Using JSON
If the string you're calling `eval()` on contains data (for example, an array: `"[1, 2, 3]"`), as opposed to code, you should consider switching to [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON), which allows the string to use a subset of JavaScript syntax to represent data.
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
Passing carefully constrained data instead of arbitrary code is a good idea in general. For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in [XPath](https://developer.mozilla.org/en-US/docs/Web/XPath) instead of JavaScript code.
Examples
--------
### Using eval()
In the following code, both of the statements containing `eval()` return 42. The first evaluates the string `"x + y + 1"`; the second evaluates the string `"42"`.
```
const x = 2;
const y = 39;
const z = "42";
eval("x + y + 1"); // 42
eval(z); // 42
```
### eval() returns the completion value of statements
`eval()` returns the completion value of statements. For `if`, it would be the last expression or statement evaluated.
```
const str = "if (a) { 1 + 1 } else { 1 + 2 }";
let a = true;
let b = eval(str);
console.log(`b is: ${b}`); // b is: 2
a = false;
b = eval(str);
console.log(`b is: ${b}`); // b is: 3
```
The following example uses `eval()` to evaluate the string `str`. This string consists of JavaScript statements that assign `z` a value of 42 if `x` is five, and assign 0 to `z` otherwise. When the second statement is executed, `eval()` will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to `z`, because the completion value of an assignment is the assigned value.
```
const x = 5;
const str = `if (x === 5) {
console.log("z is 42");
z = 42;
} else {
z = 0;
}`;
console.log("z is ", eval(str)); // z is 42 z is 42
```
If you assign multiple values then the last value is returned.
```
let x = 5;
const str = `if (x === 5) {
console.log("z is 42");
z = 42;
x = 420;
} else {
z = 0;
}`;
console.log("x is ", eval(str)); // z is 42 x is 420
```
### eval() as a string defining function requires "(" and ")" as prefix and suffix
```
// This is a function declaration
const fctStr1 = "function a() {}";
// This is a function expression
const fctStr2 = "(function b() {})";
const fct1 = eval(fctStr1); // return undefined, but `a` is available as a global function now
const fct2 = eval(fctStr2); // return the function `b`
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-eval-x](https://tc39.es/ecma262/multipage/global-object.html#sec-eval-x) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `eval` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Property accessors](../operators/property_accessors)
* [WebExtensions: Using eval in content scripts](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts)
javascript globalThis globalThis
==========
The global `globalThis` property contains the [global `this`](../operators/this#global_context) value, which is usually akin to the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object).
Try it
------
Value
-----
The global `this` object.
| Property attributes of `globalThis` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |
**Note:** The `globalThis` property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object.
Description
-----------
Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window), [`self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self), or [`frames`](https://developer.mozilla.org/en-US/docs/Web/API/Window/frames) - but in [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) only `self` will work. In Node.js none of these work, and you must instead use `global`. The `this` keyword could be used inside functions running in non–strict mode, but `this` will be `undefined` in modules and inside functions running in strict mode. You can also use `Function('return this')()`, but environments that disable [`eval()`](eval), like [CSP](https://developer.mozilla.org/en-US/docs/Glossary/CSP) in browsers, prevent use of [`Function`](function) in this way.
The `globalThis` property provides a standard way of accessing the global `this` value (and hence the global object itself) across environments. Unlike similar properties such as `window` and `self`, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the `this` value is `globalThis`.
**Note:** `globalThis` is generally the same concept as the global object (i.e. adding properties to `globalThis` makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for `globalThis` that's unrelated to the global object.
### HTML and the WindowProxy
In many engines `globalThis` will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a [`Proxy`](proxy) around the actual global object (which you can't directly access). This distinction is rarely relevant in common usage, but important to be aware of.
### Naming
Several other popular name choices such as `self` and `global` were removed from consideration because of their potential to break compatibility with existing code. See the [language proposal's "naming" document](https://github.com/tc39/proposal-global/blob/master/NAMING.md) for more details.
`globalThis` is, quite literally, the global `this` value. It's the same value as the `this` value in a non-strict function called without an object. It's also the value of `this` in the global scope of a script.
Examples
--------
### Search for the global across environments
Usually, the global object does not need to be explicitly specified — its properties are automatically accessible as global variables.
```
console.log(window.Math === Math); // true
```
However, one case where one needs to explicitly access the global object is when *writing* to it, usually for the purpose of [polyfills](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill).
Prior to `globalThis`, the only reliable cross-platform way to get the global object for an environment was `Function('return this')()`. However, this causes [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) violations in some settings, so authors would use a piecewise definition like this (slightly adapted from the [original core-js source](https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/global.js)):
```
function check(it) {
// Math is known to exist as a global in every environment.
return it && it.Math === Math && it;
}
const globalObject =
check(typeof window === 'object' && window) ||
check(typeof self === 'object' && self) ||
check(typeof global === 'object' && global) ||
// This returns undefined when running in strict mode
(function () { return this; })() ||
Function('return this')();
```
After obtaining the global object, we can define new globals on it. For example, adding an implementation for [`Intl`](intl):
```
if (typeof globalObject.Intl === 'undefined') {
// No Intl in this environment; define our own on the global scope
Object.defineProperty(globalObject, 'Intl', {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
```
With `globalThis` available, the additional search for the global across environments is not necessary anymore:
```
if (typeof globalThis.Intl === 'undefined') {
Object.defineProperty(globalThis, 'Intl', {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-globalthis](https://tc39.es/ecma262/multipage/global-object.html#sec-globalthis) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `globalThis` | 71 | 79 | 65 | No | 58 | 12.1 | 71 | 71 | 65 | 50 | 12.2 | 10.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `globalThis` in `core-js`](https://github.com/zloirock/core-js#ecmascript-globalthis)
* [`this`](../operators/this)
| programming_docs |
javascript Intl Intl
====
The `Intl` object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The `Intl` object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions.
Description
-----------
The internationalization constructors as well as several language sensitive methods of other constructors (listed under [See also](#see_also)) use a common pattern for identifying locales and determining the one they will actually use: they all accept `locales` and `options` arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the `options.localeMatcher` property.
### locales argument
The `locales` argument is used to determine the locale used in a given operation. The JavaScript implementation examines `locales`, and then computes a locale it understands that comes closest to satisfying the expressed preference. `locales` may be:
* `undefined` (or omitted): The implementation's default locale will be used.
* A locale: A locale identifier or an [`Intl.Locale`](intl/locale) object that wraps a locale identifier.
* A list of locales: Any other value, that will be converted into an object and then treated as an array of locales.
In the latter two cases, the actual locale used is the best-supported locale determined by [locale negotiation](#locale_identification_and_negotiation).
A locale identifier is a string that consists of:
1. a language subtag,
2. (optionally) a script subtag,
3. (optionally) a region (or country) subtag,
4. (optionally) one or more variant subtags (all of which must be unique),
5. (optionally) one or more BCP 47 extension sequences, and
6. (optionally) a private-use extension sequence
Each subtag and sequence are separated by hyphens. Locale identifiers are case-insensitive ASCII. However, it's conventional to use title case (the first letter is capitalized, successive letters are lower case) for script subtags, upper case for region subtags, and lower case for everything else. For example:
* `"hi"`: Hindi (language)
* `"de-AT"`: German (language) as used in Austria (region)
* `"zh-Hans-CN"`: Chinese (language) written in simplified characters (script) as used in China (region)
* `"en-emodeng"`: English (language) in the "Early modern English" dialect (variant)
Subtags identifying languages, scripts, regions (including countries), and (rarely used) variants are registered in the [IANA Language Subtag Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). This registry is periodically updated over time, and implementations may not always be up to date, so don't rely too much on subtags being universally supported.
BCP 47 extension sequences consist of a single digit or letter (other than `"x"`) and one or more two- to eight-letter or digit subtags separated by hyphens. Only one sequence is permitted for each digit or letter: `"de-a-foo-a-foo"` is invalid. BCP 47 extension subtags are defined in the [Unicode CLDR Project](https://github.com/unicode-org/cldr/tree/main/common/bcp47). Currently only two extensions have defined semantics:
* The `"u"` (Unicode) extension can be used to request additional customization of `Intl` API objects. Examples:
+ `"de-DE-u-co-phonebk"`: Use the phonebook variant of the German sort order, which interprets umlauted vowels as corresponding character pairs: ä → ae, ö → oe, ü → ue.
+ `"th-TH-u-nu-thai"`: Use Thai digits (๐, ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙) in number formatting.
+ `"ja-JP-u-ca-japanese"`: Use the Japanese calendar in date and time formatting, so that 2013 is expressed as the year 25 of the Heisei period, or 平成 25.
+ `"en-GB-u-ca-islamic"`: use British English with the Islamic (Hijri) calendar, where the Gregorian date 14 October, 2017 is the Hijri date 24 Muharram, 1439.
* The `"t"` (transformed) extension indicates transformed content: for example, text that was translated from another locale. No `Intl` functionality currently considers the `"t"` extension. However, this extension sometimes contains a nested locale (with no extensions): for example, the transformed extension in `"de-t-en"` contains the locale identifier for English. If a nested locale is present, it must be a valid locale identifier. For example, because `"en-emodeng-emodeng"` is invalid (because it contains a duplicate `emodeng` variant subtag), `"de-t-en-emodeng-emodeng"` is also invalid.
Finally, a private-use extension sequence using the letter `"x"` may appear, followed by one or more one- to eight-letter or digit subtags separated by hyphens. This allows applications to encode information for their own private use, that will be ignored by all `Intl` operations.
### options argument
The `options` argument must be an object with properties that vary between constructors and functions. If the `options` argument is not provided or is undefined, default values are used for all properties.
One property is supported by all language sensitive constructors and functions: The `localeMatcher` property, whose value must be a string `"lookup"` or `"best fit"` and which selects one of the locale matching algorithms described below.
### Locale identification and negotiation
The list of locales specified by the `locales` argument, after Unicode extensions have been removed from them, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the `"lookup"` matcher follows the Lookup algorithm specified in [BCP 47](https://datatracker.ietf.org/doc/html/rfc4647#section-3.4); the `"best fit"` matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a `locales` argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the `options` argument (see below).
If the selected locale identifier had a Unicode extension sequence, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the locale identifier. For example, the `"co"` key (collation) is only supported by [`Intl.Collator`](intl/collator), and its `"phonebk"` value is only supported for German.
Constructor properties
----------------------
[`Intl.Collator()`](intl/collator/collator) Constructor for collators, which are objects that enable language-sensitive string comparison.
[`Intl.DateTimeFormat()`](intl/datetimeformat/datetimeformat) Constructor for objects that enable language-sensitive date and time formatting.
[`Intl.DisplayNames()`](intl/displaynames/displaynames) Constructor for objects that enable the consistent translation of language, region and script display names.
[`Intl.ListFormat()`](intl/listformat/listformat) Constructor for objects that enable language-sensitive list formatting.
[`Intl.Locale()`](intl/locale/locale) Constructor for objects that represents a Unicode locale identifier.
[`Intl.NumberFormat()`](intl/numberformat/numberformat) Constructor for objects that enable language-sensitive number formatting.
[`Intl.PluralRules()`](intl/pluralrules/pluralrules) Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals.
[`Intl.RelativeTimeFormat()`](intl/relativetimeformat/relativetimeformat) Constructor for objects that enable language-sensitive relative time formatting.
[`Intl.Segmenter()`](intl/segmenter/segmenter) Constructor for objects that enable locale-sensitive text segmentation.
Static methods
--------------
[`Intl.getCanonicalLocales()`](intl/getcanonicallocales) Returns canonical locale names.
[`Intl.supportedValuesOf()`](intl/supportedvaluesof) Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.
Examples
--------
### Formatting dates and numbers
You can use `Intl` to format dates and numbers in a form that's conventional for a specific language and region:
```
const count = 26254.39;
const date = new Date("2012-05-24");
function log(locale) {
console.log(
`${new Intl.DateTimeFormat(locale).format(date)}${new Intl.NumberFormat(locale).format(count)}`
);
}
log("en-US"); // 5/24/2012 26,254.39
log("de-DE"); // 24.5.2012 26.254,39
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # intl-object](https://tc39.es/ecma402/#intl-object) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@toStringTag` | 86 | 86 | 83 | No | 72 | 14 | 86 | 86 | 83 | 61 | 14 | 14.0 | 1.8 | 15.0.0 |
| `Collator` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
| `DateTimeFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `DisplayNames` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
| `ListFormat` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
| `Locale` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `NumberFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `PluralRules` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
| `RelativeTimeFormat` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `Segmenter` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `Segments` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `Intl` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0 |
| `getCanonicalLocales` | 54 | 16 | 48 | No | 41 | 10.1 | 54 | 54 | 56 | 41 | 10.3 | 6.0 | 1.8 | 7.0.0 |
| `supportedValuesOf` | 99 | 99 | 93 | No | 85 | 15.4 | 99 | 99 | 93 | 68 | 15.4 | 18.0 | 1.19 | 18.0.0 |
See also
--------
* Introduction: [The ECMAScript Internationalization API](https://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html)
* Constructors
+ [`Intl.Collator()`](intl/collator)
+ [`Intl.DateTimeFormat()`](intl/datetimeformat)
+ [`Intl.ListFormat()`](intl/listformat)
+ [`Intl.NumberFormat()`](intl/numberformat)
+ [`Intl.PluralRules()`](intl/pluralrules)
+ [`Intl.RelativeTimeFormat()`](intl/relativetimeformat)
+ [`Intl.Locale()`](intl/locale)
+ [`Intl.Segmenter()`](intl/segmenter)
* Methods
+ [`String.prototype.localeCompare()`](string/localecompare)
+ [`Number.prototype.toLocaleString()`](number/tolocalestring)
+ [`Date.prototype.toLocaleString()`](date/tolocalestring)
+ [`Date.prototype.toLocaleDateString()`](date/tolocaledatestring)
+ [`Date.prototype.toLocaleTimeString()`](date/tolocaletimestring)
javascript WeakMap WeakMap
=======
A `WeakMap` is a collection of key/value pairs whose keys must be objects, with values of any arbitrary [JavaScript type](https://developer.mozilla.org/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.
`WeakMap` allows associating data to objects in a way that doesn't prevent the key objects from being collected, even if the values reference the keys. However, a `WeakMap` doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration; if a `WeakMap` exposed any method to obtain a list of its keys, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a [`Map`](map) rather than a `WeakMap`.
You can learn more about `WeakMap` in the [WeakMap object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object) section of the [Keyed collections](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections) guide.
Description
-----------
Keys of WeakMaps are of the type `Object` only. [Primitive data types](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) as keys are not allowed (e.g. a [`Symbol`](symbol) can't be a `WeakMap` key).
### Why WeakMap?
A map API *could* be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. As a result, the indices of the key and value would correspond to both arrays. Getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values.
Such an implementation would have two main inconveniences:
1. The first one is an `O(n)` set and search (*n* being the number of keys in the map) since both operations must iterate through the list of keys to find a matching value.
2. The second inconvenience is a memory leak because the arrays ensure that references to each key and each value are maintained indefinitely. These references prevent the keys from being garbage collected, even if there are no other references to the object. This would also prevent the corresponding values from being garbage collected.
By contrast, in a `WeakMap`, a key object refers strongly to its contents as long as the key is not garbage collected, but weakly from then on. As such, a `WeakMap`:
* does not prevent garbage collection, which eventually removes references to the key object
* allows garbage collection of any values if their key objects are not referenced from somewhere other than a `WeakMap`
A `WeakMap` can be a particularly useful construct when mapping keys to information about the key that is valuable *only if* the key has not been garbage collected.
But because a `WeakMap` doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys. If there were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a [`Map`](map).
Constructor
-----------
[`WeakMap()`](weakmap/weakmap) Creates a new `WeakMap` object.
Instance properties
-------------------
`WeakMap.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"WeakMap"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`WeakMap.prototype.delete()`](weakmap/delete) Removes any value associated to the `key`. `WeakMap.prototype.has(key)` will return `false` afterwards.
[`WeakMap.prototype.get()`](weakmap/get) Returns the value associated to the `key`, or `undefined` if there is none.
[`WeakMap.prototype.has()`](weakmap/has) Returns a Boolean asserting whether a value has been associated to the `key` in the `WeakMap` object or not.
[`WeakMap.prototype.set()`](weakmap/set) Sets the `value` for the `key` in the `WeakMap` object. Returns the `WeakMap` object.
Examples
--------
### Using WeakMap
```
const wm1 = new WeakMap();
const wm2 = new WeakMap();
const wm3 = new WeakMap();
const o1 = {};
const o2 = function () {};
const o3 = window;
wm1.set(o1, 37);
wm1.set(o2, 'azerty');
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value
wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')
wm3.set(o1, 37);
wm3.get(o1); // 37
wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false
```
### Implementing a WeakMap-like class with a .clear() method
```
class ClearableWeakMap {
#wm;
constructor(init) {
this.#wm = new WeakMap(init);
}
clear() {
this.#wm = new WeakMap();
}
delete(k) {
return this.#wm.delete(k);
}
get(k) {
return this.#wm.get(k);
}
has(k) {
return this.#wm.has(k);
}
set(k, v) {
this.#wm.set(k, v);
return this;
}
}
```
### Emulating private members
Developers can use a [`WeakMap`](weakmap) to associate private data to an object, with the following benefits:
* Compared to a [`Map`](map), a WeakMap does not hold strong references to the object used as the key, so the metadata shares the same lifetime as the object itself, avoiding memory leaks.
* Compared to using non-enumerable and/or [`Symbol`](symbol) properties, a WeakMap is external to the object and there is no way for user code to retrieve the metadata through reflective methods like [`Object.getOwnPropertySymbols`](object/getownpropertysymbols).
* Compared to a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), the same WeakMap can be reused for all instances created from a constructor, making it more memory-efficient, and allows different instances of the same class to read the private members of each other.
```
let Thing;
{
const privateScope = new WeakMap();
let counter = 0;
Thing = function() {
this.someProperty = 'foo';
privateScope.set(this, {
hidden: ++counter,
});
};
Thing.prototype.showPublic = function() {
return this.someProperty;
};
Thing.prototype.showPrivate = function() {
return privateScope.get(this).hidden;
};
}
console.log(typeof privateScope);
// "undefined"
const thing = new Thing();
console.log(thing);
// Thing {someProperty: "foo"}
thing.showPublic();
// "foo"
thing.showPrivate();
// 1
```
This is roughly equivalent to the following, using [private fields](../classes/private_class_fields):
```
class Thing {
static #counter = 0;
#hidden;
constructor() {
this.someProperty = 'foo';
this.#hidden = ++Thing.#counter;
}
showPublic() {
return this.someProperty;
}
showPrivate() {
return this.#hidden;
}
}
console.log(thing);
// Thing {someProperty: "foo"}
thing.showPublic();
// "foo"
thing.showPrivate();
// 1
```
### Associating metadata
A [`WeakMap`](weakmap) can be used to associate metadata with an object, without affecting the lifetime of the object itself. This is very similar to the private members example, since private members are also modelled as external metadata that doesn't participate in [prototypical inheritance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
This use case can be extended to already-created objects. For example, on the web, we may want to associate extra data with a DOM element, which the DOM element may access later. A common approach is to attach the data as a property:
```
const buttons = document.querySelectorAll(".button");
buttons.forEach((button) => {
button.clicked = false;
button.addEventListener("click", () => {
button.clicked = true;
const currentButtons = [...document.querySelectorAll(".button")];
if (currentButtons.every((button) => button.clicked)) {
console.log("All buttons have been clicked!");
}
});
});
```
This approach works, but it has a few pitfalls:
* The `clicked` property is enumerable, so it will show up in [`Object.keys(button)`](object/keys), [`for...in`](../statements/for...in) loops, etc. This can be mitigated by using [`Object.defineProperty()`](object/defineproperty), but that makes the code more verbose.
* The `clicked` property is a normal string property, so it can be accessed and overwritten by other code. This can be mitigated by using a [`Symbol`](symbol) key, but the key would still be accessible via [`Object.getOwnPropertySymbols()`](object/getownpropertysymbols).
Using a `WeakMap` fixes these:
```
const buttons = document.querySelectorAll(".button");
const clicked = new WeakMap();
buttons.forEach((button) => {
clicked.set(button, false);
buttons.addEventListener("click", () => {
clicked.set(button, true);
const currentButtons = [...document.querySelectorAll(".button")];
if (currentButtons.every((button) => clicked.get(button))) {
console.log("All buttons have been clicked!");
}
});
});
```
Here, only code that has access to `clicked` knows the clicked state of each button, and external code can't modify the states. In addition, if any of the buttons gets removed from the DOM, the associated metadata will automatically get garbage-collected.
### Caching
You can associate objects passed to a function with the result of the function, so that if the same object is passed again, the cached result can be returned without re-executing the function. This is useful if the function is pure (i.e. it doesn't mutate any outside objects or cause other observable side effects).
```
const cache = new WeakMap();
function handleObjectValues(obj) {
if (cache.has(obj)) {
return cache.get(obj);
}
const result = Object.values(obj).map(heavyComputation);
cache.set(obj, result);
return result;
}
```
This only works if your function's input is an object. Moreover, even if the input is never passed in again, the result still remains forever in the cache. A more effective way is to use a [`Map`](map) paired with [`WeakRef`](weakref) objects, which allows you to associate any type of input value with its respective (potentially large) computation result. See the [WeakRefs and FinalizationRegistry](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#weakrefs_and_finalizationregistry) example for more details.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap-objects](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `WeakMap` | 36 | 12 | 6 | 11 | 23 | 8 | 37 | 36 | 6 | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `WeakMap` | 36 | 12 | 6 | 11 | 23 | 8 | 37 | 36 | 6 | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `delete` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `get` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. However, the ES2015 specification specifies to return `undefined` instead. Furthermore, `WeakMap.prototype.get` accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. However, the ES2015 specification specifies to return `undefined` instead. Furthermore, `WeakMap.prototype.get` accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `has` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `set` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11
Returns 'undefined' instead of the 'Map' object. | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [Polyfill of `WeakMap` in `core-js`](https://github.com/zloirock/core-js#weakmap)
* [WeakMap object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object) in the [Keyed collections](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections) guide
* [Hiding Implementation Details with ECMAScript 6 WeakMaps](https://fitzgeraldnick.com/2014/01/13/hiding-implementation-details-with-e6-weakmaps.html)
* [`Map`](map)
* [`Set`](set)
* [`WeakSet`](weakset)
| programming_docs |
javascript WeakRef WeakRef
=======
A `WeakRef` object lets you hold a weak reference to another object, without preventing that object from getting garbage-collected.
Description
-----------
A `WeakRef` object contains a weak reference to an object, which is called its *target* or *referent*. A *weak reference* to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or *strong*) reference keeps an object in memory. When an object no longer has any strong references to it, the JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore.
### Avoid where possible
Correct use of `WeakRef` takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.
Here are some specific points that the authors of the WeakRef proposal included in its [explainer document](https://github.com/tc39/proposal-weakrefs/blob/master/README.md):
> [Garbage collectors](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:
>
> * One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
> * Garbage collection work can be split up over time using incremental and concurrent techniques.
> * Various runtime heuristics can be used to balance memory usage, responsiveness.
> * The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
> * Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
> * Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
>
>
### Notes on WeakRefs
* If your code has just created a `WeakRef` for a target object, or has gotten a target object from a `WeakRef`'s `deref` method, that target object will not be reclaimed until the end of the current JavaScript [job](https://tc39.es/ecma262/#job) (including any promise reaction jobs that run at the end of a script job). That is, you can only "see" an object get reclaimed between turns of the event loop. This is primarily to avoid making the behavior of any given JavaScript engine's garbage collector apparent in code — because if it were, people would write code relying on that behavior, which would break when the garbage collector's behavior changed. (Garbage collection is a hard problem; JavaScript engine implementers are constantly refining and improving how it works.)
* If multiple `WeakRef`s have the same target, they're consistent with one another. The result of calling `deref` on one of them will match the result of calling `deref` on another of them (in the same job), you won't get the target object from one of them but `undefined` from another.
* If the target of a `WeakRef` is also in a [`FinalizationRegistry`](finalizationregistry), the `WeakRef`'s target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls `deref` on a `WeakRef` for the object, it will receive `undefined`.
* You cannot change the target of a `WeakRef`, it will always only ever be the original target object or `undefined` when that target has been reclaimed.
* A `WeakRef` might never return `undefined` from `deref`, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object.
Constructor
-----------
[`WeakRef()`](weakref/weakref) Creates a new `WeakRef` object.
Instance properties
-------------------
`WeakRef.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"WeakRef"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`WeakRef.prototype.deref()`](weakref/deref) Returns the `WeakRef` object's target object, or `undefined` if the target object has been reclaimed.
Examples
--------
### Using a WeakRef object
This example starts a counter shown in a DOM element, stopping when the element doesn't exist anymore:
```
class Counter {
constructor(element) {
// Remember a weak reference to the DOM element
this.ref = new WeakRef(element);
this.start();
}
start() {
if (this.timer) {
return;
}
this.count = 0;
const tick = () => {
// Get the element from the weak reference, if it still exists
const element = this.ref.deref();
if (element) {
element.textContent = ++this.count;
} else {
// The element doesn't exist anymore
console.log("The element is gone.");
this.stop();
this.ref = null;
}
};
tick();
this.timer = setInterval(tick, 1000);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = 0;
}
}
}
const counter = new Counter(document.getElementById("counter"));
setTimeout(() => {
document.getElementById("counter").remove();
}, 5000);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weak-ref-objects](https://tc39.es/ecma262/multipage/managing-memory.html#sec-weak-ref-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `WeakRef` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
| `WeakRef` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
| `deref` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
See also
--------
* [`FinalizationRegistry`](finalizationregistry)
* [`WeakSet`](weakset)
* [`WeakMap`](weakmap)
javascript SharedArrayBuffer SharedArrayBuffer
=================
The `SharedArrayBuffer` object is used to represent a generic, fixed-length raw binary data buffer, similar to the [`ArrayBuffer`](arraybuffer) object, but in a way that they can be used to create views on shared memory. A `SharedArrayBuffer` is not a [Transferable Object](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects), unlike an `ArrayBuffer` which is transferable.
Description
-----------
To share memory using [`SharedArrayBuffer`](sharedarraybuffer) objects from one agent in the cluster to another (an agent is either the web page's main program or one of its web workers), [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and [structured cloning](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) is used.
The structured clone algorithm accepts `SharedArrayBuffer` objects and typed arrays mapped onto `SharedArrayBuffer` objects. In both cases, the `SharedArrayBuffer` object is transmitted to the receiver resulting in a new, private `SharedArrayBuffer` object in the receiving agent (just as for [`ArrayBuffer`](arraybuffer)). However, the shared data block referenced by the two `SharedArrayBuffer` objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent.
```
const sab = new SharedArrayBuffer(1024);
worker.postMessage(sab);
```
Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, [atomic](atomics) operations are needed.
`SharedArrayBuffer` objects are used by some web APIs, such as:
* [`WebGLRenderingContext.bufferData()`](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData)
* [`WebGLRenderingContext.bufferSubData()`](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferSubData)
* [`WebGL2RenderingContext.getBufferSubData()`](https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/getBufferSubData)
### Security requirements
Shared memory and high-resolution timers were effectively [disabled at the start of 2018](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/) in light of [Spectre](https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)). In 2020, a new, secure approach has been standardized to re-enable shared memory.
As a baseline requirement, your document needs to be in a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
For top-level documents, two headers need to be set to cross-origin isolate your site:
* [`Cross-Origin-Opener-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) with `same-origin` as value (protects your origin from attackers)
* [`Cross-Origin-Embedder-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) with `require-corp` or `credentialless` as value (protects victims from your origin)
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
To check if cross origin isolation has been successful, you can test against the [`crossOriginIsolated`](https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated) property available to window and worker contexts:
```
const myWorker = new Worker('worker.js');
if (crossOriginIsolated) {
const buffer = new SharedArrayBuffer(16);
myWorker.postMessage(buffer);
} else {
const buffer = new ArrayBuffer(16);
myWorker.postMessage(buffer);
}
```
With these two headers set, `postMessage()` no longer throws for `SharedArrayBuffer` objects and shared memory across threads is therefore available.
Nested documents and dedicated workers need to set the [`Cross-Origin-Embedder-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) header as well, with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources need to set the [`Cross-Origin-Resource-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy) header with `same-site` as value. And their cross-origin (and cross-site) counterparts need to set the same header with `cross-origin` as value. Note that setting the [`Cross-Origin-Resource-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy) header to any other value than `same-origin` opens up the resource to potential attacks, such as [Spectre](https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)).
Note that the [`Cross-Origin-Opener-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) header limits your ability to retain a reference to popups. Direct access between two top-level window contexts essentially only work if they are same-origin and carry the same two headers with the same two values.
### API availability
Depending on whether the above security measures are taken, the various memory-sharing APIs have different availabilities:
* The `Atomics` object is always available.
* `SharedArrayBuffer` objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content. There is hope that this restriction can be removed in the future. [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Memory) can still be used to get an instance.
* Unless the two headers mentioned above are set, the various `postMessage()` APIs will throw for `SharedArrayBuffer` objects. If they are set, `postMessage()` on `Window` objects and dedicated workers will function and allow for memory sharing.
### WebAssembly shared memory
[`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects can be created with the [`shared`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Memory/Memory#shared) constructor flag. When this flag is set to `true`, the constructed `Memory` object can be shared between workers via `postMessage()`, just like `SharedArrayBuffer`, and the backing [`buffer`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) of the `Memory` object is a `SharedArrayBuffer`. Therefore, the requirements listed above for sharing a `SharedArrayBuffer` between workers also apply to sharing a `WebAssembly.Memory`.
The WebAssembly Threads proposal also defines a new set of [atomic](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) instructions. Just as `SharedArrayBuffer` and its methods are unconditionally enabled (and only sharing between threads is gated on the new headers), the WebAssembly atomic instructions are also unconditionally allowed.
Constructor
-----------
[`SharedArrayBuffer()`](sharedarraybuffer/sharedarraybuffer) Creates a new `SharedArrayBuffer` object.
Instance properties
-------------------
`SharedArrayBuffer.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"SharedArrayBuffer"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`SharedArrayBuffer.prototype.byteLength`](sharedarraybuffer/bytelength) The size, in bytes, of the array. This is established when the array is constructed and cannot be changed. **Read only.**
Instance methods
----------------
[`SharedArrayBuffer.prototype.slice()`](sharedarraybuffer/slice) Returns a new `SharedArrayBuffer` whose contents are a copy of this `SharedArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.
Examples
--------
### Creating a new SharedArrayBuffer
```
const sab = new SharedArrayBuffer(1024);
```
### Slicing the SharedArrayBuffer
```
sab.slice(); // SharedArrayBuffer { byteLength: 1024 }
sab.slice(2); // SharedArrayBuffer { byteLength: 1022 }
sab.slice(-2); // SharedArrayBuffer { byteLength: 2 }
sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 }
```
### Using it in a WebGL buffer
```
const canvas = document.querySelector("canvas");
const gl = canvas.getContext("webgl");
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY\_BUFFER, buffer);
gl.bufferData(gl.ARRAY\_BUFFER, sab, gl.STATIC\_DRAW);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-sharedarraybuffer-objects](https://tc39.es/ecma262/multipage/structured-data.html#sec-sharedarraybuffer-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `SharedArrayBuffer` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `SharedArrayBuffer` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `byteLength` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `slice` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`Atomics`](atomics)
* [`ArrayBuffer`](arraybuffer)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
* [parlib-simple](https://github.com/lars-t-hansen/parlib-simple) – a simple library providing synchronization and work distribution abstractions.
* [Shared Memory – a brief tutorial](https://github.com/tc39/proposal-ecmascript-sharedmem/blob/main/TUTORIAL.md)
* [A Taste of JavaScript's New Parallel Primitives – Mozilla Hacks](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/)
* [COOP and COEP explained](https://docs.google.com/document/d/1zDlfvfTJ_9e8Jdc8ehuV4zMEu9ySMCiTGMS9y0GU92k/edit).
* `Cross-Origin-Opener-Policy`: [whatwg/html issue #3740](https://github.com/whatwg/html/issues/3740), [draft specification](https://gist.github.com/annevk/6f2dd8c79c77123f39797f6bdac43f3e).
* `Cross-Origin-Embedder-Policy`: [whatwg/html issue #4175](https://github.com/whatwg/html/issues/4175), [draft specification](https://mikewest.github.io/corpp/).
* `Cross-Origin-Resource-Policy`: [standardized in Fetch](https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header), new `cross-origin` value is part of the `Cross-Origin-Embedder-Policy` effort.
* `postMessage()` changes and [`self.crossOriginIsolated`](https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated): [whatwg/html issue #4732](https://github.com/whatwg/html/issues/4732), [whatwg/html issue #4872](https://github.com/whatwg/html/issues/4872), [draft specification](https://github.com/whatwg/html/pull/4734).
* [SharedArrayBuffer updates in Android Chrome 88 and Desktop Chrome 92](https://developer.chrome.com/blog/enabling-shared-array-buffer/)
javascript encodeURIComponent() encodeURIComponent()
====================
The `encodeURIComponent()` function encodes a [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the [UTF-8](https://developer.mozilla.org/en-US/docs/Glossary/UTF-8) encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURI()`](encodeuri), this function encodes more characters, including those that are part of the URI syntax.
Try it
------
Syntax
------
```
encodeURIComponent(uriComponent)
```
### Parameters
`uriComponent` A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](string#string_coercion).
### Return value
A new string representing the provided `uriComponent` encoded as a URI component.
### Exceptions
[`URIError`](urierror) Thrown if `uriComponent` contains a [lone surrogate](string#utf-16_characters_unicode_codepoints_and_grapheme_clusters).
Description
-----------
`encodeURIComponent()` is a function property of the global object.
`encodeURIComponent()` uses the same encoding algorithm as described in [`encodeURI()`](encodeuri). It escapes all characters **except**:
```
A–Z a–z 0–9 - _ . ! ~ * ' ( )
```
Compared to [`encodeURI()`](encodeuri), `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.
For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`.
Examples
--------
### Encoding for Content-Disposition and Link headers
The following example provides the special encoding required within UTF-8 [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) and [`Link`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) server response header parameters (e.g., UTF-8 filenames):
```
const fileName = "my file(2).txt";
const header = `Content-Disposition: attachment; filename\*=UTF-8''${encodeRFC5987ValueChars(
fileName
)}`;
console.log(header);
// "Content-Disposition: attachment; filename\*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars(str) {
return (
encodeURIComponent(str)
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
.replace(/['()\*]/g, (c) => `%${c.charCodeAt(0).toString(16)}`) // i.e., %27 %28 %29 %2a (Note that valid encoding of "\*" is %2A
// which necessitates calling toUpperCase() to properly encode)
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
.replace(/%(7C|60|5E)/g, (str, hex) =>
String.fromCharCode(parseInt(hex, 16))
)
);
}
```
### Encoding for RFC3986
The more recent [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986) reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the [IPv6](https://developer.mozilla.org/en-US/docs/Glossary/IPv6) URI syntax. An RFC3986-compliant `encodeURI` implementation should not escape them, which is demonstrated in the [`encodeURI()` example](encodeuri#encoding_for_rfc3986).
```
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str)
.replace(
/[!'()\*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
);
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-encodeuricomponent-uricomponent](https://tc39.es/ecma262/multipage/global-object.html#sec-encodeuricomponent-uricomponent) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `encodeURIComponent` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`decodeURI()`](decodeuri)
* [`encodeURI()`](encodeuri)
* [`decodeURIComponent()`](decodeuricomponent)
| programming_docs |
javascript Uint8ClampedArray Uint8ClampedArray
=================
The `Uint8ClampedArray` typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Uint8ClampedArray()`](uint8clampedarray/uint8clampedarray) Creates a new `Uint8ClampedArray` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Uint8ClampedArray.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of `Uint8ClampedArray`.
[`Uint8ClampedArray.name`](typedarray/name) Returns the string value of the constructor name. `"Uint8ClampedArray"` in the case of `Uint8ClampedArray`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Uint8ClampedArray.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of a `Uint8ClampedArray`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a Uint8ClampedArray
```
// From a length
const uintc8 = new Uint8ClampedArray(2);
uintc8[0] = 42;
uintc8[1] = 1337;
console.log(uintc8[0]); // 42
console.log(uintc8[1]); // 255 (clamped)
console.log(uintc8.length); // 2
console.log(uintc8.BYTES\_PER\_ELEMENT); // 1
// From an array
const x = new Uint8ClampedArray([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8ClampedArray(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8ClampedArray(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uintc8FromIterable = new Uint8ClampedArray(iterable);
console.log(uintc8FromIterable);
// Uint8ClampedArray [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint8ClampedArray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Uint8ClampedArray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Uint8ClampedArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript undefined undefined
=========
The global `undefined` property represents the primitive value `[undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)`. It is one of JavaScript's [primitive types](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
Try it
------
Value
-----
The primitive value `[undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)`.
| Property attributes of `undefined` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`undefined` is a property of the *global object*. That is, it is a variable in global scope.
In all non-legacy browsers, `undefined` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.
A variable that has not been assigned a value is of type `undefined`. A method or statement also returns `undefined` if the variable that is being evaluated does not have an assigned value. A function returns `undefined` if a value was not [`returned`](../statements/return).
**Note:** While you can use `undefined` as an [identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier) (variable name) in any scope other than the global scope (because `undefined` is not a [reserved word](../lexical_grammar#reserved_words)), doing so is a very bad idea that will make your code difficult to maintain and debug.
```
// DON'T DO THIS
(() => {
const undefined = "foo";
console.log(undefined, typeof undefined); // foo string
})();
((undefined) => {
console.log(undefined, typeof undefined); // foo string
})("foo");
```
Examples
--------
### Strict equality and undefined
You can use `undefined` and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable `x` is not initialized, and the `if` statement evaluates to true.
```
let x;
if (x === undefined) {
// these statements execute
} else {
// these statements do not execute
}
```
**Note:** The *strict equality* operator (as opposed to the *standard equality* operator) must be used here, because `x == undefined` also checks whether `x` is `null`, while strict equality doesn't. This is because `null` is not equivalent to `undefined`.
See [Equality comparison and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) for details.
### typeof operator and undefined
Alternatively, [`typeof`](../operators/typeof) can be used:
```
let x;
if (typeof x === "undefined") {
// these statements execute
}
```
One reason to use [`typeof`](../operators/typeof) is that it does not throw an error if the variable has not been declared.
```
// x has not been declared before
// evaluates to true without errors
if (typeof x === 'undefined') {
// these statements execute
}
// Throws a ReferenceError
if (x === undefined) {
}
```
However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.
The global scope is bound to the [global object](globalthis), so checking the existence of a variable in the global context can be done by checking the existence of a property on the *global object*, using the [`in`](../operators/in) operator, for instance:
```
if ("x" in window) {
// These statements execute only if x is defined globally
}
```
### void operator and undefined
The [`void`](../operators/void) operator is a third alternative.
```
let x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws Uncaught ReferenceError: y is not defined
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-undefined](https://tc39.es/ecma262/multipage/global-object.html#sec-undefined) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `undefined` | 1 | 12 | 1 | 5.5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* JavaScript's [primitive types](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)
* [`null`](../operators/null)
javascript Promise Promise
=======
The `Promise` object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
To learn about the way promises work and how you can use them, we advise you to read [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) first.
Description
-----------
A `Promise` is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a *promise* to supply the value at some point in the future.
A `Promise` is in one of these states:
* *pending*: initial state, neither fulfilled nor rejected.
* *fulfilled*: meaning that the operation was completed successfully.
* *rejected*: meaning that the operation failed.
The *eventual state* of a pending promise can either be *fulfilled* with a value or *rejected* with a reason (error). When either of these options occur, the associated handlers queued up by a promise's `then` method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
A promise is said to be *settled* if it is either fulfilled or rejected, but not pending.
You will also hear the term *resolved* used with promises — this means that the promise is settled or "locked-in" to match the eventual state of another promise, and further resolving or rejecting it has no effect. The [States and fates](https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md) document from the original Promise proposal contains more details about promise terminology. Colloquially, "resolved" promises are often equivalent to "fulfilled" promises, but as illustrated in "States and fates", resolved promises can be pending or rejected as well. For example:
```
new Promise((resolveOuter) => {
resolveOuter(
new Promise((resolveInner) => {
setTimeout(resolveInner, 1000);
})
);
});
```
This promise is already *resolved* at the time when it's created (because the `resolveOuter` is called synchronously), but it is resolved with another promise, and therefore won't be *fulfilled* until 1 second later, when the inner promise fulfills. In practice, the "resolution" is often done behind the scenes and not observable, and only its fulfillment or rejection are.
**Note:** Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider using a function with no arguments e.g. `f = () => expression` to create the lazily-evaluated expression, and `f()` to evaluate the expression immediately.
### Chained Promises
The methods [`Promise.prototype.then()`](promise/then), [`Promise.prototype.catch()`](promise/catch), and [`Promise.prototype.finally()`](promise/finally) are used to associate further action with a promise that becomes settled. As these methods return promises, they can be chained.
The `.then()` method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining; for example:
```
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 300);
});
myPromise
.then(handleFulfilledA, handleRejectedA)
.then(handleFulfilledB, handleRejectedB)
.then(handleFulfilledC, handleRejectedC);
```
Processing continues to the next link of the chain even when a `.then()` lacks a callback function that returns a Promise object. Therefore, a chain can safely omit every *rejection* callback function until the final `.catch()`.
Handling a rejected promise in each `.then()` has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. In such cases we must throw an error of some type to maintain error state down the chain. On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final `.catch()` statement. A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is fulfilled.
```
myPromise
.then(handleFulfilledA)
.then(handleFulfilledB)
.then(handleFulfilledC)
.catch(handleRejectedAny);
```
Using [arrow functions](../functions/arrow_functions) for the callback functions, implementation of the promise chain might look something like this:
```
myPromise
.then((value) => `${value} and bar`)
.then((value) => `${value} and bar again`)
.then((value) => `${value} and again`)
.then((value) => `${value} and again`)
.then((value) => {
console.log(value);
})
.catch((err) => {
console.error(err);
});
```
**Note:** For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence.
The termination condition of a promise determines the "settled" state of the next promise in the chain. A "fulfilled" state indicates a successful completion of the promise, while a "rejected" state indicates a lack of success. The return value of each fulfilled promise in the chain is passed along to the next `.then()`, while the reason for rejection is passed along to the next rejection-handler function in the chain.
The promises of a chain are nested like Russian dolls, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop.
```
(promise D, (promise C, (promise B, (promise A) ) ) )
```
When a `nextValue` is a promise, the effect is a dynamic replacement. The `return` causes a promise to be popped, but the `nextValue` promise is pushed into its place. For the nesting shown above, suppose the `.then()` associated with "promise B" returns a `nextValue` of "promise X". The resulting nesting would look like this:
```
(promise D, (promise C, (promise X) ) )
```
A promise can participate in more than one nesting. For the following code, the transition of `promiseA` into a "settled" state will cause both instances of `.then()` to be invoked.
```
const promiseA = new Promise(myExecutorFunc);
const promiseB = promiseA.then(handleFulfilled1, handleRejected1);
const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
```
An action can be assigned to an already "settled" promise. In that case, the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed to be asynchronous. Therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. The effect is much like that of `setTimeout(action,10)`.
```
const promiseA = new Promise((resolve, reject) => {
resolve(777);
});
// At this point, "promiseA" is already settled.
promiseA.then((val) => console.log("asynchronous logging has val:", val));
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777
```
### Thenables
The JavaScript ecosystem had made multiple Promise implementations long before it became part of the language. Despite being represented differently internally, at the minimum, all Promise-like objects implement the *Thenable* interface. A thenable implements the [`.then()`](promise/then) method, which is called with two callbacks: one for when the promise is fulfilled, one for when it's rejected. Promises are thenables as well.
To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example, [`Promise.resolve`](promise/resolve) will not only resolve promises, but also trace thenables.
```
const aThenable = {
then(onFulfilled, onRejected) {
onFulfilled({
// The thenable is fulfilled with another thenable
then(onFulfilled, onRejected) {
onFulfilled(42);
},
});
},
};
Promise.resolve(aThenable); // A promise fulfilled with 42
```
### Promise concurrency
The `Promise` class offers four static methods to facilitate async task [concurrency](https://en.wikipedia.org/wiki/Concurrent_computing):
[`Promise.all()`](promise/all) Fulfills when **all** of the promises fulfill; rejects when **any** of the promises rejects.
[`Promise.allSettled()`](promise/allsettled) Fulfills when **all** promises settle.
[`Promise.any()`](promise/any) Fulfills when **any** of the promises fulfills; rejects when **all** of the promises reject.
[`Promise.race()`](promise/race) Settles when **any** of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.
All these methods take an [iterable](../iteration_protocols#the_iterable_protocol) of promises ([thenables](#thenables), to be exact) and return a new promise. They all support subclassing, which means they can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](promise/promise) constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. The subclass must also have a `resolve` static method that can be called like [`Promise.resolve()`](promise/resolve) to resolve values to promises.
Note that JavaScript is [single-threaded](https://developer.mozilla.org/en-US/docs/Glossary/Thread) by nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent. [Parallel execution](https://en.wikipedia.org/wiki/Parallel_computing) in JavaScript can only be achieved through [worker threads](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
Constructor
-----------
[`Promise()`](promise/promise) Creates a new `Promise` object. The constructor is primarily used to wrap functions that do not already support promises.
Static methods
--------------
[`Promise.all()`](promise/all) Wait for all promises to be fulfilled, or for any to be rejected.
If the returned promise fulfills, it is fulfilled with an aggregating array of the values from the fulfilled promises, in the same order as defined in the iterable of multiple promises.
If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected.
[`Promise.allSettled()`](promise/allsettled) Wait until all promises have settled (each may fulfill or reject).
Returns a Promise that fulfills after all of the given promises is either fulfilled or rejected, with an array of objects that each describe the outcome of each promise.
[`Promise.any()`](promise/any) Takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that fulfills with the value from that promise.
[`Promise.race()`](promise/race) Wait until any of the promises is fulfilled or rejected.
If the returned promise fulfills, it is fulfilled with the value of the first promise in the iterable that fulfilled.
If it rejects, it is rejected with the reason from the first promise that was rejected.
[`Promise.reject()`](promise/reject) Returns a new `Promise` object that is rejected with the given reason.
[`Promise.resolve()`](promise/resolve) Returns a new `Promise` object that is resolved with the given value. If the value is a thenable (i.e. has a `then` method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
Generally, if you don't know if a value is a promise or not, [`Promise.resolve(value)`](promise/resolve) it instead and work with the return value as a promise.
Instance properties
-------------------
`Promise.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Promise"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
See the [Microtask guide](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how these methods use the Microtask queue and services.
[`Promise.prototype.catch()`](promise/catch) Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
[`Promise.prototype.then()`](promise/then) Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler `onFulfilled` or `onRejected` is not a function).
[`Promise.prototype.finally()`](promise/finally) Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.
Examples
--------
### Basic Example
```
const myFirstPromise = new Promise((resolve, reject) => {
// We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
// In this example, we use setTimeout(...) to simulate async code.
// In reality, you will probably be using something like XHR or an HTML API.
setTimeout(() => {
resolve("Success!"); // Yay! Everything went well!
}, 250);
});
myFirstPromise.then((successMessage) => {
// successMessage is whatever we passed in the resolve(...) function above.
// It doesn't have to be a string, but if it is only a succeed message, it probably will be.
console.log(`Yay! ${successMessage}`);
});
```
### Example with diverse situations
This example shows diverse techniques for using Promise capabilities and diverse situations that can occur. To understand this, start by scrolling to the bottom of the code block, and examine the promise chain. Upon provision of an initial promise, a chain of promises can follow. The chain is composed of `.then()` calls, and typically (but not necessarily) has a single `.catch()` at the end, optionally followed by `.finally()`. In this example, the promise chain is initiated by a custom-written `new Promise()` construct; but in actual practice, promise chains more typically start with an API function (written by someone else) that returns a promise.
The example function `tetheredGetNumber()` shows that a promise generator will utilize `reject()` while setting up an asynchronous call, or within the call-back, or both. The function `promiseGetWord()` illustrates how an API function might generate and return a promise in a self-contained manner.
Note that the function `troubleWithGetNumber()` ends with a `throw`. That is forced because a promise chain goes through all the `.then()` promises, even after an error, and without the `throw`, the error would seem "fixed". This is a hassle, and for this reason, it is common to omit `onRejected` throughout the chain of `.then()` promises, and just have a single `onRejected` in the final `catch()`.
This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the `threshold` values.
```
// To experiment with error handling, "threshold" values cause errors randomly
const THRESHOLD\_A = 8; // can use zero 0 to guarantee error
function tetheredGetNumber(resolve, reject) {
setTimeout(() => {
const randomInt = Date.now();
const value = randomInt % 10;
if (value < THRESHOLD\_A) {
resolve(value);
} else {
reject(`Too large: ${value}`);
}
}, 500);
}
function determineParity(value) {
const isOdd = value % 2 === 1;
return { value, isOdd };
}
function troubleWithGetNumber(reason) {
const err = new Error("Trouble getting number", { cause: reason });
console.error(err);
throw err;
}
function promiseGetWord(parityInfo) {
return new Promise((resolve, reject) => {
const { value, isOdd } = parityInfo;
if (value >= THRESHOLD\_A - 1) {
reject(`Still too large: ${value}`);
} else {
parityInfo.wordEvenOdd = isOdd ? "odd" : "even";
resolve(parityInfo);
}
});
}
new Promise(tetheredGetNumber)
.then(determineParity, troubleWithGetNumber)
.then(promiseGetWord)
.then((info) => {
console.log(`Got: ${info.value}, ${info.wordEvenOdd}`);
return info;
})
.catch((reason) => {
if (reason.cause) {
console.error("Had previously handled error");
} else {
console.error(`Trouble with promiseGetWord(): ${reason}`);
}
})
.finally((info) => console.log("All done"));
```
### Advanced Example
This small example shows the mechanism of a `Promise`. The `testPromise()` method is called each time the [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) is clicked. It creates a promise that will be fulfilled, using [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), to the promise count (number starting from 1) every 1-3 seconds, at random. The `Promise()` constructor is used to create the promise.
The fulfillment of the promise is logged, via a fulfill callback set using [`p1.then()`](promise/then). A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.
By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.
#### HTML
```
<button id="make-promise">Make a promise!</button>
<div id="log"></div>
```
#### JavaScript
```
"use strict";
let promiseCount = 0;
function testPromise() {
const thisPromiseCount = ++promiseCount;
const log = document.getElementById("log");
// begin
log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Started<br>`);
// We make a new promise: we promise a numeric count of this promise,
// starting from 1 (after waiting 3s)
const p1 = new Promise((resolve, reject) => {
// The executor function is called with the ability
// to resolve or reject the promise
log.insertAdjacentHTML(
"beforeend",
`${thisPromiseCount}) Promise constructor<br>`
);
// This is only an example to create asynchronism
setTimeout(() => {
// We fulfill the promise
resolve(thisPromiseCount);
}, Math.random() \* 2000 + 1000);
});
// We define what to do when the promise is resolved with the then() call,
// and what to do when the promise is rejected with the catch() call
p1.then((val) => {
// Log the fulfillment value
log.insertAdjacentHTML("beforeend", `${val}) Promise fulfilled<br>`);
}).catch((reason) => {
// Log the rejection reason
console.log(`Handle rejected promise (${reason}) here.`);
});
// end
log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Promise made<br>`);
}
const btn = document.getElementById("make-promise");
btn.addEventListener("click", testPromise);
```
#### Result
### Loading an image with XHR
Another simple example using `Promise` and [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) to load an image is available at the MDN GitHub [js-examples](https://github.com/mdn/js-examples/tree/master/promises-test) repository. You can also [see it in action](https://mdn.github.io/js-examples/promises-test/). Each step is commented on and allows you to follow the Promise and XHR architecture closely.
### Incumbent settings object tracking
A settings object is an [environment](https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object) that provides additional information when JavaScript code is running. This includes the realm and module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one to use for a given piece of user code.
To better picture this, we can take a closer look at how the realm might be an issue. A **realm** can be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects like [`Array`](array) and [`Error`](error). Each settings object has its own "copy" of these and they are not shared. That can cause some unexpected behavior in relation to promises. In order to get around this, we track something called the **incumbent settings object**. This represents information specific to the context of the user code responsible for a certain function call.
To illustrate this a bit further we can take a look at how an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers:
```
<!DOCTYPE html> <iframe></iframe>
<!-- we have a realm here -->
<script>
// we have a realm here as well
const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
// bound is a built-in function — there is no user
// code on the stack, so which realm do we use?
setTimeout(bound);
// this still works, because we use the youngest
// realm (the incumbent) on the stack
</script>
```
The same concept applies to promises. If we modify the above example a little bit, we get this:
```
<!DOCTYPE html> <iframe></iframe>
<!-- we have a realm here -->
<script>
// we have a realm here as well
const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
// bound is a built in function — there is no user
// code on the stack — which realm do we use?
Promise.resolve(undefined).then(bound);
// this still works, because we use the youngest
// realm (the incumbent) on the stack
</script>
```
If we change this so that the `<iframe>` in the document is listening to post messages, we can observe the effect of the incumbent settings object:
```
<!-- y.html -->
<!DOCTYPE html>
<iframe src="x.html"></iframe>
<script>
const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
Promise.resolve(undefined).then(bound);
</script>
```
```
<!-- x.html -->
<!DOCTYPE html>
<script>
window.addEventListener(
"message",
(event) => {
document.querySelector("#text").textContent = "hello";
// this code will only run in browsers that track the incumbent settings object
console.log(event);
},
false
);
</script>
```
In the above example, the inner text of the `<iframe>` will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message.
**Note:** Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-promise-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Promise` | 32 | 12 | 29
Constructor requires a new operator since version 37. | No | 19 | 8
Constructor requires a new operator since version 10. | 4.4.3 | 32 | 29
Constructor requires a new operator since version 37. | 19 | 8
Constructor requires a new operator since version 10. | 2.0 | 1.0 | 0.12.0
Constructor requires a new operator since version 4. |
| `Promise` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `all` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `allSettled` | 76 | 79 | 71 | No | 63 | 13 | 76 | 76 | 79 | 54 | 13 | 12.0 | 1.0 | 12.9.0 |
| `any` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
| `catch` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `finally` | 63 | 18 | 58 | No | 50 | 11.1 | 63 | 63 | 58 | 46 | 11.3 | 8.0 | 1.0 | 10.0.0 |
| `incumbent_settings_object_tracking` | No | No | 50 | No | No | No | No | No | 50 | No | No | No | No | No |
| `race` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `reject` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `resolve` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
| `then` | 32 | 12 | 29 | No | 19 | 8 | 4.4.3 | 32 | 29 | 19 | 8 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Promise` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
* [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
* [Promises/A+ specification](https://promisesaplus.com/)
* [JavaScript Promises: an introduction](https://web.dev/promises/)
* [Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript](https://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript)
| programming_docs |
javascript JSON JSON
====
The `JSON` object contains methods for parsing [JavaScript Object Notation](https://json.org/) ([JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON)) and converting values to JSON. It can't be called or constructed.
Description
-----------
Unlike most global objects, `JSON` is not a constructor. You cannot use it with a [`new` operator](../operators/new) or invoke the `JSON` object as a function. All properties and methods of `JSON` are static (just like the [`Math`](math) object).
### JavaScript and JSON differences
JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and [`null`](../operators/null). It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is *not* JSON. For example:
Objects and Arrays Property names must be double-quoted strings; [trailing commas](../trailing_commas) are forbidden.
Numbers Leading zeros are prohibited. A decimal point must be followed by at least one digit. `NaN` and `Infinity` are unsupported.
Any JSON text is a valid JavaScript expression, but only after the [JSON superset](https://github.com/tc39/proposal-json-superset) revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a [`SyntaxError`](syntaxerror).
Other differences include allowing only double-quoted strings and no support for [`undefined`](undefined) or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is [JSON5](https://json5.org/), used by the Babel compiler, and the more commonly used [YAML](https://en.wikipedia.org/wiki/YAML).
The same text may represent different values in JavaScript object literals vs. JSON as well. For more information, see [Object literal syntax vs. JSON](../operators/object_initializer#object_literal_syntax_vs._json).
### Full JSON grammar
Valid JSON syntax is formally defined by the following grammar, expressed in [ABNF](https://en.wikipedia.org/wiki/Augmented_Backus%E2%80%93Naur_form), and copied from [IETF JSON standard (RFC)](https://datatracker.ietf.org/doc/html/rfc8259):
```
JSON-text = object / array
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
name-separator = ws %x3A ws ; : colon
value-separator = ws %x2C ws ; , comma
ws = *(
%x20 / ; Space
%x09 / ; Horizontal tab
%x0A / ; Line feed or New line
%x0D ; Carriage return
)
value = false / null / true / object / array / number / string
false = %x66.61.6c.73.65 ; false
null = %x6e.75.6c.6c ; null
true = %x74.72.75.65 ; true
object = begin-object [ member *( value-separator member ) ]
end-object
member = string name-separator value
array = begin-array [ value *( value-separator value ) ] end-array
number = [ minus ] int [ frac ] [ exp ]
decimal-point = %x2E ; .
digit1-9 = %x31-39 ; 1-9
e = %x65 / %x45 ; e E
exp = e [ minus / plus ] 1*DIGIT
frac = decimal-point 1*DIGIT
int = zero / ( digit1-9 *DIGIT )
minus = %x2D ; -
plus = %x2B ; +
zero = %x30 ; 0
string = quotation-mark *char quotation-mark
char = unescaped /
escape (
%x22 / ; " quotation mark U+0022
%x5C / ; \ reverse solidus U+005C
%x2F / ; / solidus U+002F
%x62 / ; b backspace U+0008
%x66 / ; f form feed U+000C
%x6E / ; n line feed U+000A
%x72 / ; r carriage return U+000D
%x74 / ; t tab U+0009
%x75 4HEXDIG ) ; uXXXX U+XXXX
escape = %x5C ; \
quotation-mark = %x22 ; "
unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
HEXDIG = DIGIT / %x41-46 / %x61-66 ; 0-9, A-F, or a-f
; HEXDIG equivalent to HEXDIG rule in [RFC5234]
DIGIT = %x30-39 ; 0-9
; DIGIT equivalent to DIGIT rule in [RFC5234]
```
Insignificant [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) may be present anywhere except within a `JSONNumber` (numbers must contain no whitespace) or `JSONString` (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character ([U+0009](https://unicode-table.com/en/0009/)), carriage return ([U+000D](https://unicode-table.com/en/000D/)), line feed ([U+000A](https://unicode-table.com/en/000A/)), and space ([U+0020](https://unicode-table.com/en/0020/)) characters are the only valid whitespace characters.
Static properties
-----------------
`JSON[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"JSON"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Static methods
--------------
[`JSON.parse()`](json/parse) Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.
[`JSON.stringify()`](json/stringify) Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
Examples
--------
### Example JSON
```
{
"browsers": {
"firefox": {
"name": "Firefox",
"pref\_url": "about:config",
"releases": {
"1": {
"release\_date": "2004-11-09",
"status": "retired",
"engine": "Gecko",
"engine\_version": "1.7"
}
}
}
}
}
```
You can use the [`JSON.parse()`](json/parse) method to convert the above JSON string into a JavaScript object:
```
const jsonText = `{
"browsers": {
"firefox": {
"name": "Firefox",
"pref\_url": "about:config",
"releases": {
"1": {
"release\_date": "2004-11-09",
"status": "retired",
"engine": "Gecko",
"engine\_version": "1.7"
}
}
}
}
}`;
console.log(JSON.parse(jsonText));
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-json-object](https://tc39.es/ecma262/multipage/structured-data.html#sec-json-object) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `JSON` | 3 | 12 | 3.5 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 4 | 1.0 | 1.0 | 0.10.0 |
| `json_superset` | 66 | 79 | 62 | No | 53 | 12 | 66 | 66 | 62 | 47 | 12 | 9.0 | 1.0 | 10.0.0 |
| `parse` | 3 | 12 | 3.5 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 4 | 1.0 | 1.0 | 0.10.0 |
| `stringify` | 3 | 12 | 3.5 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 4 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date.prototype.toJSON()`](date/tojson)
* [JSON Diff](https://json-diff.com/) checker
* [JSON Beautifier/editor](https://jsonbeautifier.org/)
* [JSON Parser](https://jsonparser.org/)
* [JSON Validator](https://tools.learningcontainer.com/json-validator/)
javascript ArrayBuffer ArrayBuffer
===========
The `ArrayBuffer` object is used to represent a generic, fixed-length raw binary data buffer.
It is an array of bytes, often referred to in other languages as a "byte array". You cannot directly manipulate the contents of an `ArrayBuffer`; instead, you create one of the [typed array objects](typedarray) or a [`DataView`](dataview) object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
The [`ArrayBuffer()`](arraybuffer/arraybuffer) constructor creates a new `ArrayBuffer` of the given length in bytes. You can also get an array buffer from existing data, for example, from a [Base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64) string or [from a local file](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer).
`ArrayBuffer` is a [transferable object](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects).
Constructor
-----------
[`ArrayBuffer()`](arraybuffer/arraybuffer) Creates a new `ArrayBuffer` object.
Static properties
-----------------
[`get ArrayBuffer[@@species]`](arraybuffer/@@species) The constructor function that is used to create derived objects.
Static methods
--------------
[`ArrayBuffer.isView()`](arraybuffer/isview) Returns `true` if `arg` is one of the ArrayBuffer views, such as [typed array objects](typedarray) or a [`DataView`](dataview). Returns `false` otherwise.
Instance properties
-------------------
`ArrayBuffer.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"ArrayBuffer"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`ArrayBuffer.prototype.byteLength`](arraybuffer/bytelength) The read-only size, in bytes, of the `ArrayBuffer`. This is established when the array is constructed and cannot be changed.
Instance methods
----------------
[`ArrayBuffer.prototype.slice()`](arraybuffer/slice) Returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin` (inclusive) up to `end` (exclusive). If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.
Examples
--------
### Creating an ArrayBuffer
In this example, we create a 8-byte buffer with a [`Int32Array`](int32array) view referring to the buffer:
```
const buffer = new ArrayBuffer(8);
const view = new Int32Array(buffer);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-arraybuffer-objects](https://tc39.es/ecma262/multipage/structured-data.html#sec-arraybuffer-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@species` | 51 | 13 | 48 | No | 38 | 10 | 51 | 51 | 48 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `ArrayBuffer` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `ArrayBuffer` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `byteLength` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `isView` | 32 | 12 | 29 | 11 | 19 | 7 | 4.4.3 | 32 | 29 | 19 | 7 | 2.0 | 1.0 | 4.0.0 |
| `slice` | 17 | 12 | 12
The non-standard `ArrayBuffer.slice()` method has been removed in Firefox 53 (but the standardized version `ArrayBuffer.prototype.slice()` is kept. | 11 | 12.1 | 5.1 | 4.4 | 18 | 14
The non-standard `ArrayBuffer.slice()` method has been removed in Firefox 53 (but the standardized version `ArrayBuffer.prototype.slice()` is kept. | 12.1 | 6 | 1.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `ArrayBuffer` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`SharedArrayBuffer`](sharedarraybuffer)
* [RangeError: invalid array length](../errors/invalid_array_length)
javascript RangeError RangeError
==========
The `RangeError` object indicates an error when a value is not in the set or range of allowed values.
Description
-----------
A `RangeError` is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.
This can be encountered when:
* passing a value that is not one of the allowed string values to [`String.prototype.normalize()`](string/normalize), or
* when attempting to create an array of an illegal length with the [`Array`](array) constructor, or
* when passing bad values to the numeric methods [`Number.prototype.toExponential()`](number/toexponential), [`Number.prototype.toFixed()`](number/tofixed) or [`Number.prototype.toPrecision()`](number/toprecision).
`RangeError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`RangeError()`](rangeerror/rangeerror) Creates a new `RangeError` object.
Instance properties
-------------------
[`RangeError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`RangeError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`RangeError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`RangeError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`RangeError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`RangeError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`RangeError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Using RangeError (for numeric values)
```
function check(n) {
if (!(n >= -500 && n <= 500)) {
throw new RangeError("The argument must be between -500 and 500.");
}
}
try {
check(2000);
} catch (error) {
if (error instanceof RangeError) {
// Handle the error
}
}
```
### Using RangeError (for non-numeric values)
```
function check(value) {
if (!["apple", "banana", "carrot"].includes(value)) {
throw new RangeError(
'The argument must be an "apple", "banana", or "carrot".'
);
}
}
try {
check("cabbage");
} catch (error) {
if (error instanceof RangeError) {
// Handle the error
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-rangeerror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-rangeerror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `RangeError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `RangeError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
* [`Array`](array)
* [`Number.prototype.toExponential()`](number/toexponential)
* [`Number.prototype.toFixed()`](number/tofixed)
* [`Number.prototype.toPrecision()`](number/toprecision)
* [`String.prototype.normalize()`](string/normalize)
javascript Atomics Atomics
=======
The `Atomics` object provides atomic operations as static methods. They are used with [`SharedArrayBuffer`](sharedarraybuffer) and [`ArrayBuffer`](arraybuffer) objects.
Description
-----------
The Atomic operations are installed on an `Atomics` module. Unlike the other global objects, `Atomics` is not a constructor. You cannot use it with a [`new` operator](../operators/new) or invoke the `Atomics` object as a function. All properties and methods of `Atomics` are static (as is the case with the [`Math`](math) object, for example).
### Atomic operations
When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted.
### Wait and notify
The `wait()` and `notify()` methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs.
Static properties
-----------------
`Atomics[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Atomics"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Static methods
--------------
[`Atomics.add()`](atomics/add) Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index.
[`Atomics.and()`](atomics/and) Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index.
[`Atomics.compareExchange()`](atomics/compareexchange) Stores a value at the specified index of the array, if it equals a value. Returns the old value.
[`Atomics.exchange()`](atomics/exchange) Stores a value at the specified index of the array. Returns the old value.
[`Atomics.isLockFree(size)`](atomics/islockfree) An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns `true` if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only.
[`Atomics.load()`](atomics/load) Returns the value at the specified index of the array.
[`Atomics.notify()`](atomics/notify) Notifies agents that are waiting on the specified index of the array. Returns the number of agents that were notified.
[`Atomics.or()`](atomics/or) Computes a bitwise OR on the value at the specified index of the array with the provided value. Returns the old value at that index.
[`Atomics.store()`](atomics/store) Stores a value at the specified index of the array. Returns the value.
[`Atomics.sub()`](atomics/sub) Subtracts a value at the specified index of the array. Returns the old value at that index.
[`Atomics.wait()`](atomics/wait) Verifies that the specified index of the array still contains a value and sleeps awaiting or times out. Returns either `"ok"`, `"not-equal"`, or `"timed-out"`. If waiting is not allowed in the calling agent then it throws an exception. (Most browsers will not allow `wait()` on the browser's main thread.)
[`Atomics.waitAsync()`](atomics/waitasync) Waits asynchronously (i.e. without blocking, unlike `Atomics.wait`) on a shared memory location and returns a [`Promise`](promise).
[`Atomics.xor()`](atomics/xor) Computes a bitwise XOR on the value at the specified index of the array with the provided value. Returns the old value at that index.
Examples
--------
### Using Atomics
```
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0]; // 0
ta[0] = 5; // 5
Atomics.add(ta, 0, 12); // 5
Atomics.load(ta, 0); // 17
Atomics.and(ta, 0, 1); // 17
Atomics.load(ta, 0); // 1
Atomics.compareExchange(ta, 0, 5, 12); // 1
Atomics.load(ta, 0); // 1
Atomics.exchange(ta, 0, 12); // 1
Atomics.load(ta, 0); // 12
Atomics.isLockFree(1); // true
Atomics.isLockFree(2); // true
Atomics.isLockFree(3); // false
Atomics.isLockFree(4); // true
Atomics.or(ta, 0, 1); // 12
Atomics.load(ta, 0); // 13
Atomics.store(ta, 0, 12); // 12
Atomics.sub(ta, 0, 2); // 12
Atomics.load(ta, 0); // 10
Atomics.xor(ta, 0, 1); // 10
Atomics.load(ta, 0); // 11
```
### Waiting and notifying
Given a shared `Int32Array`:
```
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);
```
A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).
```
Atomics.wait(int32, 0, 0);
console.log(int32[0]); // 123
```
A writing thread stores a new value and notifies the waiting thread once it has written:
```
console.log(int32[0]); // 0;
Atomics.store(int32, 0, 123);
Atomics.notify(int32, 0, 1);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-atomics-object](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics-object) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Atomic_operations_on_non_shared_buffers` | No | No | 79 | No | No | No | No | No | 79 | No | No | No | No | No |
| `Atomics` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `add` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `and` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `compareExchange` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `exchange` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `isLockFree` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `load` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `notify` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `or` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `store` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `sub` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `wait` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
| `waitAsync` | 87 | 87 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 | 1.4 | 16.0.0 |
| `xor` | 68 | 79 | 78 | No | 55 | 15.2 | 89 | 89 | 79 | 63 | 15.2 | 15.0 | 1.0 | 8.10.0 |
See also
--------
* [`ArrayBuffer`](arraybuffer)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
* [parlib-simple](https://github.com/lars-t-hansen/parlib-simple) – a simple library providing synchronization and work distribution abstractions.
* [Shared Memory – a brief tutorial](https://github.com/tc39/proposal-ecmascript-sharedmem/blob/main/TUTORIAL.md)
* [A Taste of JavaScript's New Parallel Primitives – Mozilla Hacks](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/)
| programming_docs |
javascript AsyncGeneratorFunction AsyncGeneratorFunction
======================
The `AsyncGeneratorFunction` object provides methods for [async generator functions](../statements/async_function*). In JavaScript, every async generator function is actually an `AsyncGeneratorFunction` object.
Note that `AsyncGeneratorFunction` is *not* a global object. It can be obtained with the following code:
```
const AsyncGeneratorFunction = async function\* () {}.constructor;
```
Try it
------
Constructor
-----------
[`AsyncGeneratorFunction()`](asyncgeneratorfunction/asyncgeneratorfunction) Creates a new `AsyncGeneratorFunction` object.
Instance properties
-------------------
*Also inherits instance properties from its parent [`Function`](function)*.
`AsyncGeneratorFunction.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"AsyncGeneratorFunction"`. This property is used in [`Object.prototype.toString()`](object/tostring).
`AsyncGeneratorFunction.prototype.prototype` All async generator functions share the same [`prototype`](function/prototype) property, which is [`AsyncGenerator.prototype`](asyncgenerator). When the function is called, this object becomes the prototype of the returned async generator object. An async generator function instance can also create its own `prototype` property, which will be used instead of `AsyncGeneratorFunction.prototype.prototype`.
Instance methods
----------------
*Inherits instance methods from its parent [`Function`](function)*.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgeneratorfunction-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgeneratorfunction-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `AsyncGeneratorFunction` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
| `AsyncGeneratorFunction` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*` declaration](../statements/async_function*)
* [`async function*` expression](../operators/async_function*)
* [`Function`](function)
* [`AsyncFunction`](asyncfunction)
* [`GeneratorFunction`](generatorfunction)
* [Functions](../functions)
javascript isFinite() isFinite()
==========
The global `isFinite()` function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.
Try it
------
Syntax
------
```
isFinite(testValue)
```
### Parameters
`testValue` The value to be tested for finiteness.
### Return value
`false` if the argument is (or will be coerced to) positive or negative [`Infinity`](infinity) or [`NaN`](nan) or [`undefined`](undefined); otherwise, `true`.
Description
-----------
`isFinite` is a function property of the global object.
You can use this function to determine whether a number is a finite number. The `isFinite` function examines the number in its argument. If the argument is `NaN`, positive infinity, or negative infinity, this method returns `false`; otherwise, it returns `true`.
Examples
--------
### Using isFinite
```
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite(910); // true
isFinite(null); // true, would've been false with the
// more robust Number.isFinite(null)
isFinite('0'); // true, would've been false with the
// more robust Number.isFinite("0")
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-isfinite-number](https://tc39.es/ecma262/multipage/global-object.html#sec-isfinite-number) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isFinite` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.isFinite()`](number/isfinite)
* [`Number.NaN`](number/nan)
* [`Number.POSITIVE_INFINITY`](number/positive_infinity)
* [`Number.NEGATIVE_INFINITY`](number/negative_infinity)
javascript AsyncFunction AsyncFunction
=============
The `AsyncFunction` object provides methods for [async functions](../statements/async_function). In JavaScript, every async function is actually an `AsyncFunction` object.
Note that `AsyncFunction` is *not* a global object. It can be obtained with the following code:
```
const AsyncFunction = async function () {}.constructor;
```
Constructor
-----------
[`AsyncFunction()`](asyncfunction/asyncfunction) Creates a new `AsyncFunction` object.
Instance properties
-------------------
*Also inherits instance properties from its parent [`Function`](function)*.
`AsyncFunction.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"AsyncFunction"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
*Inherits instance methods from its parent [`Function`](function)*.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-async-function-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-async-function-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `AsyncFunction` | 55 | 15 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
| `AsyncFunction` | 55 | 15 | 52 | No | 42 | 10.1 | 55 | 55 | 52 | 42 | 10.3 | 6.0 | 1.0 | 7.6.0
7.0.0 |
See also
--------
* [`async function` declaration](../statements/async_function)
* [`async function` expression](../operators/async_function)
* [`Function`](function)
* [`AsyncGeneratorFunction`](asyncgeneratorfunction)
* [`GeneratorFunction`](generatorfunction)
* [Functions](../functions)
javascript decodeURI() decodeURI()
===========
The `decodeURI()` function decodes a Uniform Resource Identifier (URI) previously created by [`encodeURI()`](encodeuri) or a similar routine.
Try it
------
Syntax
------
```
decodeURI(encodedURI)
```
### Parameters
`encodedURI` A complete, encoded Uniform Resource Identifier.
### Return value
A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI).
### Exceptions
[`URIError`](urierror) Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.
Description
-----------
`decodeURI()` is a function property of the global object.
The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a [`URIError`](urierror) is thrown.
`decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax):
```
; / ? : @ & = + $ , #
```
Examples
--------
### Decoding a Cyrillic URL
```
decodeURI(
"https://developer.mozilla.org/ru/docs/JavaScript\_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B",
);
// "https://developer.mozilla.org/ru/docs/JavaScript\_шеллы"
```
### decodeURI() vs decodeURIComponent()
`decodeURI()` assumes the input is a full URI, so it does not decode characters that are part of the URI syntax.
```
decodeURI(
"https://developer.mozilla.org/docs/JavaScript%3A%20a\_scripting\_language",
);
// "https://developer.mozilla.org/docs/JavaScript%3A a\_scripting\_language"
decodeURIComponent(
"https://developer.mozilla.org/docs/JavaScript%3A%20a\_scripting\_language",
);
// "https://developer.mozilla.org/docs/JavaScript: a\_scripting\_language"
```
### Catching errors
```
try {
const a = decodeURI("%E0%A4%A");
} catch (e) {
console.error(e);
}
// URIError: malformed URI sequence
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-decodeuri-encodeduri](https://tc39.es/ecma262/multipage/global-object.html#sec-decodeuri-encodeduri) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `decodeURI` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`decodeURIComponent()`](decodeuricomponent)
* [`encodeURI()`](encodeuri)
* [`encodeURIComponent()`](encodeuricomponent)
javascript Int8Array Int8Array
=========
The `Int8Array` typed array represents an array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Int8Array()`](int8array/int8array) Creates a new `Int8Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Int8Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of `Int8Array`.
[`Int8Array.name`](typedarray/name) Returns the string value of the constructor name. `"Int8Array"` in the case of `Int8Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Int8Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of a `Int8Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create an Int8Array
```
// From a length
const int8 = new Int8Array(2);
int8[0] = 42;
console.log(int8[0]); // 42
console.log(int8.length); // 2
console.log(int8.BYTES\_PER\_ELEMENT); // 1
// From an array
const x = new Int8Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int8Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Int8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const int8FromIterable = new Int8Array(iterable);
console.log(int8FromIterable);
// Int8Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Int8Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Int8Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Int8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript unescape() unescape()
==========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`decodeURIComponent()`](decodeuricomponent) or [`decodeURI()`](decodeuri) if possible.
The `unescape()` function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like [`escape()`](escape).
Syntax
------
```
unescape(str)
```
### Parameters
`str` A string to be decoded.
### Return value
A new string in which certain characters have been unescaped.
Description
-----------
`unescape()` is a function property of the global object.
The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is.
**Note:** This function was used mostly for URL encoding and is partly based on the escape format in [RFC 1738](https://datatracker.ietf.org/doc/html/rfc1738). The `unescape()` function does *not* evaluate [escape sequences](string#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`.
Examples
--------
### Using unescape()
```
unescape("abc123"); // "abc123"
unescape("%E4%F6%FC"); // "äöü"
unescape("%u0107"); // "ć"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-unescape-string](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-unescape-string) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `unescape` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `unescape` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`decodeURI`](decodeuri)
* [`decodeURIComponent`](decodeuricomponent)
* [`escape`](escape)
javascript Int16Array Int16Array
==========
The `Int16Array` typed array represents an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Int16Array()`](int16array/int16array) Creates a new `Int16Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Int16Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `2` in the case of `Int16Array`.
[`Int16Array.name`](typedarray/name) Returns the string value of the constructor name. `"Int16Array"` in the case of `Int16Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Int16Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `2` in the case of a `Int16Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create an Int16Array
```
// From a length
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42
console.log(int16.length); // 2
console.log(int16.BYTES\_PER\_ELEMENT); // 2
// From an array
const x = new Int16Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int16Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Int16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const int16FromIterable = new Int16Array(iterable);
console.log(int16FromIterable);
// Int16Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Int16Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Int16Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Int16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript Object Object
======
The `Object` type represents one of [JavaScript's data types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures). It is used to store various keyed collections and more complex entities. Objects can be created using the [`Object()`](object/object) constructor or the [object initializer / literal syntax](../operators/object_initializer).
Description
-----------
Nearly all [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects) in JavaScript are instances of [`Object`](object); a typical object inherits properties (including methods) from `Object.prototype`, although these properties may be shadowed (a.k.a. overridden). The only objects that don't inherit from `Object.prototype` are those with [`null` prototype](#null-prototype_objects), or descended from other `null` prototype objects.
Changes to the `Object.prototype` object are seen by **all** objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. To make it more secure, `Object.prototype` is the only object in the core JavaScript language that has [immutable prototype](object/setprototypeof#description) — the prototype of `Object.prototype` is always `null` and not changeable.
### Object prototype properties
You should avoid calling any `Object.prototype` method, especially those that are not intended to be polymorphic (i.e. only its initial behavior makes sense and no descending object could override it in a meaningful way). All objects descending from `Object.prototype` may define a custom own property that has the same name, but with entirely different semantics from what you expect. Furthermore, these properties are not inherited by [`null`-prototype objects](#null-prototype_objects). All modern JavaScript utilities for working with objects are [static](#static_methods). More specifically:
* [`valueOf()`](object/valueof), [`toString()`](object/tostring), and [`toLocaleString()`](object/tolocalestring) exist to be polymorphic and you should expect the object to define its own implementation with sensible behaviors, so you can call them as instance methods. However, `valueOf()` and `toString()` are usually implicitly called through [type conversion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#type_coercion) and you don't need to call them yourself in your code.
* [`__defineGetter__()`](object/__definegetter__), [`__defineSetter__()`](object/__definesetter__), [`__lookupGetter__()`](object/__lookupgetter__), and [`__lookupSetter__()`](object/__lookupsetter__) are deprecated and should not be used. Use the static alternatives [`Object.defineProperty()`](object/defineproperty) and [`Object.getOwnPropertyDescriptor()`](object/getownpropertydescriptor) instead.
* The [`__proto__`](object/proto) property is deprecated and should not be used. The [`Object.getPrototypeOf()`](object/getprototypeof) and [`Object.setPrototypeOf()`](object/setprototypeof) alternatives are static methods.
* The [`propertyIsEnumerable()`](object/propertyisenumerable) and [`hasOwnProperty()`](object/hasownproperty) methods can be replaced with the [`Object.getOwnPropertyDescriptor()`](object/getownpropertydescriptor) and [`Object.hasOwn()`](object/hasown) static methods, respectively.
* The [`isPrototypeOf()`](object/isprototypeof) method can usually be replaced with [`instanceof`](../operators/instanceof), if you are checking the `prototype` property of a constructor.
In case where a semantically equivalent static method doesn't exist, or if you really want to use the `Object.prototype` method, you should directly [`call()`](function/call) the `Object.prototype` method on your target object instead, to prevent the object from having an overriding property that produces unexpected results.
```
const obj = {
foo: 1,
// You should not define such a method on your own object,
// but you may not be able to prevent it from happening if
// you are receiving the object from external input
propertyIsEnumerable() {
return false;
}
}
obj.propertyIsEnumerable("foo"); // false; unexpected result
Object.prototype.propertyIsEnumerable.call(obj, "foo"); // true; expected result
```
### Deleting a property from an object
There isn't any method in an Object itself to delete its own properties (such as [`Map.prototype.delete()`](map/delete)). To do so, one must use the [delete operator](../operators/delete).
### null-prototype objects
Almost all objects in JavaScript ultimately inherit from `Object.prototype` (see [inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)). However, you may create `null`-prototype objects using [`Object.create(null)`](object/create) or the [object initializer syntax](../operators/object_initializer) with `__proto__: null` (note: the `__proto__` key in object literals is different from the deprecated [`Object.prototype.__proto__`](object/proto) property). You can also change the prototype of an existing object to `null` by calling [`Object.setPrototypeOf(obj, null)`](object/setprototypeof).
```
const obj = Object.create(null);
const obj2 = { \_\_proto\_\_: null };
```
An object with a `null` prototype can behave in unexpected ways, because it doesn't inherit any object methods from `Object.prototype`. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or lose information (especially if using silent error-traps that ignore errors).
For example, the lack of [`Object.prototype.toString()`](object/tostring) often makes debugging intractable:
```
const normalObj = {}; // create a normal object
const nullProtoObj = Object.create(null); // create an object with "null" prototype
console.log(`normalObj is: ${normalObj}`); // shows "normalObj is: [object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // throws error: Cannot convert object to primitive value
alert(normalObj); // shows [object Object]
alert(nullProtoObj); // throws error: Cannot convert object to primitive value
```
Other methods will fail as well.
```
normalObj.valueOf(); // shows {}
nullProtoObj.valueOf(); // throws error: nullProtoObj.valueOf is not a function
normalObj.hasOwnProperty("p"); // shows "true"
nullProtoObj.hasOwnProperty("p"); // throws error: nullProtoObj.hasOwnProperty is not a function
normalObj.constructor; // shows "Object() { [native code] }"
nullProtoObj.constructor; // shows "undefined"
```
We can add the `toString` method back to the null-prototype object by assigning it one:
```
nullProtoObj.toString = Object.prototype.toString; // since new object lacks toString, add the original generic one back
console.log(nullProtoObj.toString()); // shows "[object Object]"
console.log(`nullProtoObj is: ${nullProtoObj}`); // shows "nullProtoObj is: [object Object]"
```
Unlike normal objects, in which `toString()` is on the object's prototype, the `toString()` method here is an own property of `nullProtoObj`. This is because `nullProtoObj` has no (`null`) prototype.
In practice, objects with `null` prototype are usually used as a cheap substitute for [maps](map). The presence of `Object.prototype` properties will cause some bugs:
```
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return name in ages;
}
function getAge(name) {
return ages[name];
}
hasPerson("hasOwnProperty"); // true
getAge("toString"); // [Function: toString]
```
Using a null-prototype object removes this hazard without introducing too much complexity to the `hasPerson` and `getAge` functions:
```
const ages = Object.create(null, {
alice: { value: 18, enumerable: true },
bob: { value: 27, enumerable: true },
});
hasPerson("hasOwnProperty"); // false
getAge("toString"); // undefined
```
In such case, the addition of any method should be done cautiously, as they can be confused with the other key-value pairs stored as data.
Making your object not inherit from `Object.prototype` also prevents prototype pollution attacks. If a malicious script adds a property to `Object.prototype`, it will be accessible on every object in your program, except objects that have null prototype.
```
const user = {};
// A malicious script:
Object.prototype.authenticated = true;
// Unexpectedly allowing unauthenticated user to pass through
if (user.authenticated) {
// access confidential data
}
```
JavaScript also has built-in APIs that produce `null`-prototype objects, especially those that use objects as ad hoc key-value collections. For example:
* The return value of [`Array.prototype.group()`](array/group)
* The `groups` and `indices.groups` properties of the result of [`RegExp.prototype.exec()`](regexp/exec)
* [`Array.prototype[@@unscopables]`](array/@@unscopables) (all `@@unscopables` objects should have `null`-prototype)
* [`import.meta`](../operators/import.meta)
* Module namespace objects, obtained through [`import * as ns from "module";`](../statements/import#namespace_import) or [`import()`](../operators/import)
### Object coercion
Many built-in operations that expect objects first coerce their arguments to objects. [The operation](https://tc39.es/ecma262/#sec-toobject) can be summarized as follows:
* Objects are returned as-is.
* [`undefined`](undefined) and [`null`](../operators/null) throw a [`TypeError`](typeerror).
* [`Number`](number), [`String`](string), [`Boolean`](boolean), [`Symbol`](symbol), [`BigInt`](bigint) primitives are wrapped into their corresponding object wrappers.
The best way to achieve the same effect in JavaScript is through the [`Object()`](object/object) constructor. `Object(x)` converts `x` to an object, and for `undefined` or `null`, it returns a plain object instead of throwing a [`TypeError`](typeerror).
Places that use object coercion include:
* The `object` parameter of [`for...in`](../statements/for...in) loops.
* The `this` value of [`Array`](array) methods.
* Parameters of `Object` methods such as [`Object.keys()`](object/keys).
* Auto-boxing when a property is accessed on a primitive value, since primitives do not have properties.
* The [`this`](../operators/this) value when calling a non-strict function. Primitives are boxed while `null` and `undefined` are replaced with the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object).
Unlike [conversion to primitives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion), the object coercion process itself is not observable in any way, since it doesn't invoke custom code like `toString` or `valueOf` methods.
Constructor
-----------
[`Object()`](object/object) Turns the input into an object.
Static methods
--------------
[`Object.assign()`](object/assign) Copies the values of all enumerable own properties from one or more source objects to a target object.
[`Object.create()`](object/create) Creates a new object with the specified prototype object and properties.
[`Object.defineProperty()`](object/defineproperty) Adds the named property described by a given descriptor to an object.
[`Object.defineProperties()`](object/defineproperties) Adds the named properties described by the given descriptors to an object.
[`Object.entries()`](object/entries) Returns an array containing all of the `[key, value]` pairs of a given object's **own** enumerable string properties.
[`Object.freeze()`](object/freeze) Freezes an object. Other code cannot delete or change its properties.
[`Object.fromEntries()`](object/fromentries) Returns a new object from an iterable of `[key, value]` pairs. (This is the reverse of [`Object.entries`](object/entries)).
[`Object.getOwnPropertyDescriptor()`](object/getownpropertydescriptor) Returns a property descriptor for a named property on an object.
[`Object.getOwnPropertyDescriptors()`](object/getownpropertydescriptors) Returns an object containing all own property descriptors for an object.
[`Object.getOwnPropertyNames()`](object/getownpropertynames) Returns an array containing the names of all of the given object's **own** enumerable and non-enumerable properties.
[`Object.getOwnPropertySymbols()`](object/getownpropertysymbols) Returns an array of all symbol properties found directly upon a given object.
[`Object.getPrototypeOf()`](object/getprototypeof) Returns the prototype (internal `[[Prototype]]` property) of the specified object.
[`Object.is()`](object/is) Compares if two values are the same value. Equates all `NaN` values (which differs from both `IsLooselyEqual` used by [`==`](../operators/equality) and `IsStrictlyEqual` used by [`===`](../operators/strict_equality)).
[`Object.isExtensible()`](object/isextensible) Determines if extending of an object is allowed.
[`Object.isFrozen()`](object/isfrozen) Determines if an object was frozen.
[`Object.isSealed()`](object/issealed) Determines if an object is sealed.
[`Object.keys()`](object/keys) Returns an array containing the names of all of the given object's **own** enumerable string properties.
[`Object.preventExtensions()`](object/preventextensions) Prevents any extensions of an object.
[`Object.seal()`](object/seal) Prevents other code from deleting properties of an object.
[`Object.setPrototypeOf()`](object/setprototypeof) Sets the object's prototype (its internal `[[Prototype]]` property).
[`Object.values()`](object/values) Returns an array containing the values that correspond to all of a given object's **own** enumerable string properties.
Instance properties
-------------------
[`Object.prototype.constructor`](object/constructor) Specifies the function that creates an object's prototype.
[`Object.prototype.__proto__`](object/proto) Deprecated
Points to the object which was used as prototype when the object was instantiated.
Instance methods
----------------
[`Object.prototype.__defineGetter__()`](object/__definegetter__) Associates a function with a property that, when accessed, executes that function and returns its return value.
[`Object.prototype.__defineSetter__()`](object/__definesetter__) Associates a function with a property that, when set, executes that function which modifies the property.
[`Object.prototype.__lookupGetter__()`](object/__lookupgetter__) Returns the function bound as a getter to the specified property.
[`Object.prototype.__lookupSetter__()`](object/__lookupsetter__) Returns the function bound as a setter to the specified property.
[`Object.prototype.hasOwnProperty()`](object/hasownproperty) Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
[`Object.prototype.isPrototypeOf()`](object/isprototypeof) Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
[`Object.prototype.propertyIsEnumerable()`](object/propertyisenumerable) Returns a boolean indicating whether the specified property is the object's [enumerable own](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) property.
[`Object.prototype.toLocaleString()`](object/tolocalestring) Calls [`toString()`](object/tostring).
[`Object.prototype.toString()`](object/tostring) Returns a string representation of the object.
[`Object.prototype.valueOf()`](object/valueof) Returns the primitive value of the specified object.
Examples
--------
### Constructing empty objects
The following examples store an empty `Object` object in `o`:
```
const o1 = new Object();
const o2 = new Object(undefined);
const o3 = new Object(null);
```
### Using Object to create Boolean objects
The following examples store [`Boolean`](boolean) objects in `o`:
```
// equivalent to const o = new Boolean(true)
const o = new Object(true);
```
```
// equivalent to const o = new Boolean(false)
const o = new Object(Boolean());
```
### Object prototypes
When altering the behavior of existing `Object.prototype` methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.
When modifying prototypes with hooks, pass `this` and the arguments (the call state) to the current behavior by calling `apply()` on the function. This pattern can be used for any prototype, such as `Node.prototype`, `Function.prototype`, etc.
```
const current = Object.prototype.valueOf;
// Since my property "-prop-value" is cross-cutting and isn't always
// on the same prototype chain, I want to modify Object.prototype:
Object.prototype.valueOf = function (...args) {
if (Object.hasOwn(this, '-prop-value')) {
return this['-prop-value'];
} else {
// It doesn't look like one of my objects, so let's fall back on
// the default behavior by reproducing the current behavior as best we can.
// The apply behaves like "super" in some other languages.
// Even though valueOf() doesn't take arguments, some other hook may.
return current.apply(this, args);
}
}
```
**Warning:** Modifying the `prototype` property of any built-in constructor is considered a bad practice and risks forward compatibility.
You can read more about prototypes in [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-object-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Object` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Object` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `assign` | 45 | 12 | 34 | No | 32 | 9 | 45 | 45 | 34 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
| `constructor` | 1 | 12 | 1 | 8 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `create` | 5 | 12 | 4 | 9 | 11.6 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `defineGetter` | 1 | 12 | 1
Starting with Firefox 48, this method can no longer be called at the global scope without any object. A `TypeError` will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case. | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `defineProperties` | 5 | 12 | 4 | 9 | 11.6 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `defineProperty` | 5 | 12 | 4 | 9
8
In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9. | 11.6 | 5.1
Also supported in Safari 5, but not on DOM objects. | 4.4 | 18 | 4 | 12 | 6
Also supported in Safari for iOS 4.2, but not on DOM objects. | 1.0 | 1.0 | 0.10.0 |
| `defineSetter` | 1 | 12 | 1
Starting with Firefox 48, this method can no longer be called at the global scope without any object. A `TypeError` will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case. | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `entries` | 54 | 14 | 47 | No | 41 | 10.1 | 54 | 54 | 47 | 41 | 10.3 | 6.0 | 1.0 | 7.0.0
6.5.0 |
| `freeze` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `fromEntries` | 73 | 79 | 63 | No | 60 | 12.1 | 73 | 73 | 63 | 52 | 12.2 | 11.0 | 1.0 | 12.0.0 |
| `getOwnPropertyDescriptor` | 5 | 12 | 4 | 9
8
In Internet Explorer 8, this was only supported on DOM objects and with some non-standard behaviors. This was later fixed in Internet Explorer 9. | 12 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getOwnPropertyDescriptors` | 54 | 15 | 50 | No | 41 | 10 | 54 | 54 | 50 | 41 | 10 | 6.0 | 1.0 | 7.0.0
6.5.0 |
| `getOwnPropertyNames` | 5 | 12 | 4 | 9 | 12 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getOwnPropertySymbols` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `getPrototypeOf` | 5 | 12 | 3.5 | 9 | 12.1 | 5 | 4.4 | 18 | 4 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `hasOwn` | 93 | 93 | 92 | No | 79 | 15.4 | 93 | 93 | 92 | 66 | 15.4 | 17.0 | 1.13 | 16.9.0 |
| `hasOwnProperty` | 1 | 12 | 1 | 5.5 | 5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `is` | 19 | 12 | 22 | No | 15 | 9 | 4.4 | 25 | 22 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
| `isExtensible` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `isFrozen` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `isPrototypeOf` | 1 | 12 | 1 | 9 | 4 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `isSealed` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `keys` | 5 | 12 | 4 | 9 | 12 | 5 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `lookupGetter` | 1 | 12 | 1 | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lookupSetter` | 1 | 12 | 1 | 11 | 9.5 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `preventExtensions` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `propertyIsEnumerable` | 1 | 12 | 1 | 5.5 | 4 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `proto` | 1 | 12 | 1 | 11 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | No | 0.10.0 |
| `seal` | 6 | 12 | 4 | 9 | 12 | 5.1 | 4.4 | 18 | 4 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setPrototypeOf` | 34 | 12 | 31 | 11 | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `toLocaleString` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `valueOf` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `values` | 54 | 14 | 47 | No | 41 | 10.1 | 54 | 54 | 47 | 41 | 10.3 | 6.0 | 1.0 | 7.0.0
6.5.0 |
See also
--------
* [Object initializer](../operators/object_initializer)
| programming_docs |
javascript TypedArray TypedArray
==========
A ***TypedArray*** object describes an array-like view of an underlying [binary data buffer](arraybuffer). There is no global property named `TypedArray`, nor is there a directly visible `TypedArray` constructor. Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.
Try it
------
Description
-----------
The `TypedArray` constructor (often referred to as `%TypedArray%` to indicate its "intrinsicness", since it does not correspond to any global exposed to a JavaScript program) serves as the common superclass of all `TypedArray` subclasses. Think about `%TypedArray%` as an "abstract class" providing a common interface of utility methods for all typed array subclasses. This constructor is not directly exposed: there is no global `TypedArray` property. It is only accessible through `Object.getPrototypeOf(Int8Array)` and similar.
When creating an instance of a `TypedArray` subclass (e.g. `Int8Array`), an array buffer is created internally in memory or, if an `ArrayBuffer` object is given as constructor argument, that `ArrayBuffer` is used instead. The buffer address is saved as an internal property of the instance and all the methods of `%TypedArray%.prototype` will set and get values based on that array buffer address.
### TypedArray objects
| Type | Value Range | Size in bytes | Description | Web IDL type | Equivalent C type |
| --- | --- | --- | --- | --- | --- |
| [`Int8Array`](int8array) | -128 to 127 | 1 | 8-bit two's complement signed integer | `byte` | `int8_t` |
| [`Uint8Array`](uint8array) | 0 to 255 | 1 | 8-bit unsigned integer | `octet` | `uint8_t` |
| [`Uint8ClampedArray`](uint8clampedarray) | 0 to 255 | 1 | 8-bit unsigned integer (clamped) | `octet` | `uint8_t` |
| [`Int16Array`](int16array) | -32768 to 32767 | 2 | 16-bit two's complement signed integer | `short` | `int16_t` |
| [`Uint16Array`](uint16array) | 0 to 65535 | 2 | 16-bit unsigned integer | `unsigned short` | `uint16_t` |
| [`Int32Array`](int32array) | -2147483648 to 2147483647 | 4 | 32-bit two's complement signed integer | `long` | `int32_t` |
| [`Uint32Array`](uint32array) | 0 to 4294967295 | 4 | 32-bit unsigned integer | `unsigned long` | `uint32_t` |
| [`Float32Array`](float32array) | `-3.4E38` to `3.4E38` and `1.2E-38` is the min positive number | 4 | 32-bit IEEE floating point number (7 significant digits e.g., `1.234567`) | `unrestricted float` | `float` |
| [`Float64Array`](float64array) | `-1.8E308` to `1.8E308` and `5E-324` is the min positive number | 8 | 64-bit IEEE floating point number (16 significant digits e.g., `1.23456789012345`) | `unrestricted double` | `double` |
| [`BigInt64Array`](bigint64array) | -263 to 263 - 1 | 8 | 64-bit two's complement signed integer | `bigint` | `int64_t (signed long long)` |
| [`BigUint64Array`](biguint64array) | 0 to 264 - 1 | 8 | 64-bit unsigned integer | `bigint` | `uint64_t (unsigned long long)` |
Constructor
-----------
This object cannot be instantiated directly — attempting to construct it with `new` throws a [`TypeError`](typeerror).
```
new (Object.getPrototypeOf(Int8Array))();
// TypeError: Abstract class TypedArray not directly constructable
```
Instead, you create an instance of a typed array of a particular type, such as an [`Int8Array`](int8array) or a [`BigInt64Array`](bigint64array). These objects all have a common syntax for their constructors:
```
new TypedArray()
new TypedArray(length)
new TypedArray(typedArray)
new TypedArray(object)
new TypedArray(buffer)
new TypedArray(buffer, byteOffset)
new TypedArray(buffer, byteOffset, length)
```
Where `TypedArray` is a constructor for one of the concrete types.
**Note:** All `TypedArray` subclasses' constructors can only be constructed with [`new`](../operators/new). Attempting to call one without `new` throws a [`TypeError`](typeerror).
### Parameters
`typedArray` When called with an instance of a `TypedArray` subclass, the `typedArray` gets copied into a new typed array. For a non-<bigint> `TypedArray` constructor, the `typedArray` parameter can only be of one of the non-<bigint> types (such as [`Int32Array`](int32array)). Similarly, for a <bigint> `TypedArray` constructor ([`BigInt64Array`](bigint64array) or [`BigUint64Array`](biguint64array)), the `typedArray` parameter can only be of one of the <bigint> types. Each value in `typedArray` is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the `typedArray` argument.
`object` When called with an object that's not a `TypedArray` instance, a new typed array is created in the same way as the [`TypedArray.from()`](typedarray/from) method.
`length` Optional
When called with a non-object, the parameter will be treated as a number specifying the length of the typed array. An internal array buffer is created in memory, of size `length` multiplied by [`BYTES_PER_ELEMENT`](typedarray/bytes_per_element) bytes, filled with zeros. Omitting all parameters is equivalent to using `0` as `length`.
`buffer`, `byteOffset` Optional, `length` Optional
When called with an [`ArrayBuffer`](arraybuffer) or [`SharedArrayBuffer`](sharedarraybuffer) instance, and optionally a `byteOffset` and a `length` argument, a new typed array view is created that views the specified buffer. The `byteOffset` and `length` parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of `buffer` is viewed; if only `length` is omitted, the remainder of `buffer` starting from `byteOffset` is viewed.
### Exceptions
All `TypeArray` subclass constructors operate in the same way. They would all throw the following exceptions:
[`TypeError`](typeerror) Thrown in one of the following cases:
* A `typedArray` is passed but it is a <bigint> type while the current constructor is not, or vice versa.
* A `typedArray` is passed but the buffer it's viewing is detached, or a detached `buffer` is directly passed.
[`RangeError`](rangeerror) Thrown in one of the following cases:
* The new typed array's length is too large.
* The length of `buffer` (if the `length` parameter is not specified) or `byteOffset` is not an integral multiple of the new typed array's element size.
* `byteOffset` is not a valid array index (an integer between 0 and 253 - 1).
* When creating a view from a buffer, the bounds are outside the buffer. In other words, `byteOffset + length * TypedArray.BYTES_PER_ELEMENT > buffer.byteLength`.
Static properties
-----------------
These properties are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors.
[`get TypedArray[@@species]`](typedarray/@@species) The constructor function used to create derived objects.
All `TypedArray` subclasses also have the following static properties:
[`TypedArray.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size for the different `TypedArray` objects.
[`TypedArray.name`](typedarray/name) Returns the string value of the constructor [name](function/name) (e.g., `"Int8Array"`).
Static methods
--------------
These methods are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors.
[`TypedArray.from()`](typedarray/from) Creates a new `TypedArray` from an array-like or iterable object. See also [`Array.from()`](array/from).
[`TypedArray.of()`](typedarray/of) Creates a new `TypedArray` with a variable number of arguments. See also [`Array.of()`](array/of).
Instance properties
-------------------
These properties are all [getters](../functions/get) defined on the `TypedArray` prototype object and are thus read-only and shared by all `TypedArray` subclass instances.
`TypedArray.prototype[@@toStringTag]` The initial value of a typed array's [`@@toStringTag`](symbol/tostringtag) property is the same string as its [name](typedarray/name). This property is used in [`Object.prototype.toString()`](object/tostring). However, because `TypedArray` also has its own [`toString()`](typedarray/tostring) method, this property is not used unless you call [`Object.prototype.toString.call()`](function/call) with a typed array as `thisArg`.
[`TypedArray.prototype.buffer`](typedarray/buffer) Returns the [`ArrayBuffer`](arraybuffer) referenced by the typed array.
[`TypedArray.prototype.byteLength`](typedarray/bytelength) Returns the length (in bytes) of the typed array.
[`TypedArray.prototype.byteOffset`](typedarray/byteoffset) Returns the offset (in bytes) of the typed array from the start of its [`ArrayBuffer`](arraybuffer).
[`TypedArray.prototype.length`](typedarray/length) Returns the number of elements held in the typed array.
All `TypedArray` subclasses also have the following instance properties:
[`TypedArray.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size for the different `TypedArray` objects.
Instance methods
----------------
These methods are defined on the `TypedArray` prototype object and are thus shared by all `TypedArray` subclass instances.
[`TypedArray.prototype.at()`](typedarray/at) Takes an integer value and returns the item at that index. This method allows for negative integers, which count back from the last item.
[`TypedArray.prototype.copyWithin()`](typedarray/copywithin) Copies a sequence of array elements within the array. See also [`Array.prototype.copyWithin()`](array/copywithin).
[`TypedArray.prototype.entries()`](typedarray/entries) Returns a new *array iterator* object that contains the key/value pairs for each index in the array. See also [`Array.prototype.entries()`](array/entries).
[`TypedArray.prototype.every()`](typedarray/every) Tests whether all elements in the array pass the test provided by a function. See also [`Array.prototype.every()`](array/every).
[`TypedArray.prototype.fill()`](typedarray/fill) Fills all the elements of an array from a start index to an end index with a static value. See also [`Array.prototype.fill()`](array/fill).
[`TypedArray.prototype.filter()`](typedarray/filter) Creates a new array with all of the elements of this array for which the provided filtering function returns `true`. See also [`Array.prototype.filter()`](array/filter).
[`TypedArray.prototype.find()`](typedarray/find) Returns the first `element` in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also [`Array.prototype.find()`](array/find).
[`TypedArray.prototype.findIndex()`](typedarray/findindex) Returns the first index value of in the array that has an element that satisfies a provided testing function, or `-1` if no appropriate element was found. See also [`Array.prototype.findIndex()`](array/findindex).
[`TypedArray.prototype.findLast()`](typedarray/findlast) Returns the value of the last element in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also [`Array.prototype.findLast()`](array/findlast).
[`TypedArray.prototype.findLastIndex()`](typedarray/findlastindex) Returns the index of the last element in the array that satisfies a provided testing function, or `-1` if no appropriate element was found. See also [`Array.prototype.findLastIndex()`](array/findlastindex).
[`TypedArray.prototype.forEach()`](typedarray/foreach) Calls a function for each element in the array. See also [`Array.prototype.forEach()`](array/foreach).
[`TypedArray.prototype.includes()`](typedarray/includes) Determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. See also [`Array.prototype.includes()`](array/includes).
[`TypedArray.prototype.indexOf()`](typedarray/indexof) Returns the first (least) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.indexOf()`](array/indexof).
[`TypedArray.prototype.join()`](typedarray/join) Joins all elements of an array into a string. See also [`Array.prototype.join()`](array/join).
[`TypedArray.prototype.keys()`](typedarray/keys) Returns a new array iterator that contains the keys for each index in the array. See also [`Array.prototype.keys()`](array/keys).
[`TypedArray.prototype.lastIndexOf()`](typedarray/lastindexof) Returns the last (greatest) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.lastIndexOf()`](array/lastindexof).
[`TypedArray.prototype.map()`](typedarray/map) Creates a new array with the results of calling a provided function on every element in this array. See also [`Array.prototype.map()`](array/map).
[`TypedArray.prototype.reduce()`](typedarray/reduce) Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also [`Array.prototype.reduce()`](array/reduce).
[`TypedArray.prototype.reduceRight()`](typedarray/reduceright) Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also [`Array.prototype.reduceRight()`](array/reduceright).
[`TypedArray.prototype.reverse()`](typedarray/reverse) Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also [`Array.prototype.reverse()`](array/reverse).
[`TypedArray.prototype.set()`](typedarray/set) Stores multiple values in the typed array, reading input values from a specified array.
[`TypedArray.prototype.slice()`](typedarray/slice) Extracts a section of an array and returns a new array. See also [`Array.prototype.slice()`](array/slice).
[`TypedArray.prototype.some()`](typedarray/some) Returns `true` if at least one element in this array satisfies the provided testing function. See also [`Array.prototype.some()`](array/some).
[`TypedArray.prototype.sort()`](typedarray/sort) Sorts the elements of an array in place and returns the array. See also [`Array.prototype.sort()`](array/sort).
[`TypedArray.prototype.subarray()`](typedarray/subarray) Returns a new `TypedArray` from the given start and end element index.
[`TypedArray.prototype.values()`](typedarray/values) Returns a new *array iterator* object that contains the values for each index in the array. See also [`Array.prototype.values()`](array/values).
[`TypedArray.prototype.toLocaleString()`](typedarray/tolocalestring) Returns a localized string representing the array and its elements. See also [`Array.prototype.toLocaleString()`](array/tolocalestring).
[`TypedArray.prototype.toString()`](typedarray/tostring) Returns a string representing the array and its elements. See also [`Array.prototype.toString()`](array/tostring).
[`TypedArray.prototype[@@iterator]()`](typedarray/@@iterator) Returns a new *array iterator* object that contains the values for each index in the array.
Examples
--------
### Property access
You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the [`ArrayBuffer`](arraybuffer) and will never look at object properties. You can still use named properties, just like with all objects.
```
// Setting and getting using standard array syntax
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42
// Indexed properties on prototypes are not consulted (Fx 25)
Int8Array.prototype[20] = "foo";
new Int8Array(32)[20]; // 0
// even when out of bound
Int8Array.prototype[20] = "foo";
new Int8Array(8)[20]; // undefined
// or with negative integers
Int8Array.prototype[-1] = "foo";
new Int8Array(8)[-1]; // undefined
// Named properties are allowed, though (Fx 30)
Int8Array.prototype.foo = "bar";
new Int8Array(32).foo; // "bar"
```
### Cannot be frozen
`TypedArray`s that aren't empty cannot be frozen, as their underlying `ArrayBuffer` could be mutated through another `TypedArray` view of the buffer. This would mean that the object would never genuinely be frozen.
```
const i8 = Int8Array.of(1, 2, 3);
Object.freeze(i8);
// TypeError: Cannot freeze array buffer views with elements
```
### ByteOffset must be aligned
When constructing a `TypedArray` as a view onto an `ArrayBuffer`, the `byteOffset` argument must be aligned to its element size; in other words, the offset must be a multiple of `BYTES_PER_ELEMENT`.
```
const i32 = new Int32Array(new ArrayBuffer(4), 1);
// RangeError: start offset of Int32Array should be a multiple of 4
```
```
const i32 = new Int32Array(new ArrayBuffer(4), 0);
```
### ByteLength must be aligned
Like the `byteOffset` parameter, the `byteLength` property of an `ArrayBuffer` passed to a `TypedArray`'s constructor must be a multiple of the constructor's `BYTES_PER_ELEMENT`.
```
const i32 = new Int32Array(new ArrayBuffer(3));
// RangeError: byte length of Int32Array should be a multiple of 4
```
```
const i32 = new Int32Array(new ArrayBuffer(4));
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray-objects](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 10 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
| `@@species` | 51 | 13 | 48 | No | 38 | 10 | 51 | 51 | 48 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `BYTES_PER_ELEMENT` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `TypedArray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `at` | 92 | 92 | 90 | No | 78 | 15.4 | 92 | 92 | 90 | 65 | 15.4 | 16.0 | No | 16.6.0 |
| `buffer` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `byteLength` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `byteOffset` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `constructor_without_parameters` | 7 | 12 | 55 | 10 | 11.6 | 5.1 | ≤37 | 18 | 55 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `copyWithin` | 45 | 12 | 34 | No | 32 | 9.1 | 45 | 45 | 34 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `entries` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 0.12.0 |
| `every` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `fill` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `filter` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `find` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `findIndex` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `findLast` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | No |
| `findLastIndex` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | No |
| `forEach` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `from` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `includes` | 47 | 14 | 43 | No | 34 | 10 | 47 | 47 | 43 | 34 | 10 | 5.0 | 1.0 | 6.0.0
5.0.0 |
| `indexOf` | 45 | 12 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).indexOf(0, -0)` will now always return `+0`. | No | 32 | 9.1 | 45 | 45 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).indexOf(0, -0)` will now always return `+0`. | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `index_properties_not_consulting_prototype` | 7
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 12
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 25 | 10
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 11.6
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 5.1
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | ≤37
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 18
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 25 | 12
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 5
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 1.0
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 1.0
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. | 0.10.0
Negative integers are not considered as indexed properties and therefore return the value of the prototype property. |
| `iterable_in_constructor` | 39 | 14 | 52 | No | 26 | 10 | 39 | 39 | 52 | 26 | 10 | 4.0 | 1.0 | 4.0.0 |
| `join` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `keys` | 38 | 12 | 37 | No | 25 | 10 | 38 | 38 | 37 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
| `lastIndexOf` | 45 | 12 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).lastIndexOf(0, -0)` will now always return `+0`. | No | 32 | 10 | 45 | 45 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).lastIndexOf(0, -0)` will now always return `+0`. | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `length` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `map` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `name` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `named_properties` | 7 | 12 | 30 | 10 | 11.6 | 5.1 | ≤37 | 18 | 30 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `new_required` | 7 | 14 | 44 | No | 15 | 5.1 | ≤37 | 18 | 44 | 14 | 5 | 1.0 | 1.0 | 0.12.0 |
| `of` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
| `reduce` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `reduceRight` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `reverse` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `set` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `slice` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `some` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `sort` | 45 | 12 | 46 | No | 32 | 10 | 45 | 45 | 46 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
| `subarray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.12.0 |
| `toLocaleString` | 7 | 12 | 51 | 10 | 11.6 | 5.1 | ≤37 | 18 | 51 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 7 | 12 | 51 | 10 | 11.6 | 5.1 | ≤37 | 18 | 51 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `values` | 38 | 12 | 37 | No | 25 | 10 | 38 | 38 | 37 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of typed arrays in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
* [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) — Helper that decode strings from numerical data
| programming_docs |
javascript String String
======
The `String` object is used to represent and manipulate a sequence of characters.
Description
-----------
Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their [`length`](string/length), to build and concatenate them using the [+ and += string operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#string_operators), checking for the existence or location of substrings with the [`indexOf()`](string/indexof) method, or extracting substrings with the [`substring()`](string/substring) method.
### Creating strings
Strings can be created as primitives, from string literals, or as objects, using the [`String()`](string/string) constructor:
```
const string1 = "A string primitive";
const string2 = "Also a string primitive";
const string3 = `Yet another string primitive`;
```
```
const string4 = new String("A String object");
```
String primitives and string objects share many behaviors, but have other important differences and caveats. See "[String primitives and String objects](#string_primitives_and_string_objects)" below.
String literals can be specified using single or double quotes, which are treated identically, or using the backtick character ```. This last form specifies a [template literal](../template_literals): with this form you can interpolate expressions.
### Character access
There are two ways to access an individual character in a string. The first is the [`charAt()`](string/charat) method:
```
"cat".charAt(1); // gives value "a"
```
The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:
```
"cat"[1]; // gives value "a"
```
When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See [`Object.defineProperty()`](object/defineproperty) for more information.)
### Comparing strings
In C, the `strcmp()` function is used for comparing strings. In JavaScript, you just use the [less-than and greater-than operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators):
```
const a = "a";
const b = "b";
if (a < b) {
// true
console.log(`${a} is less than ${b}`);
} else if (a > b) {
console.log(`${a} is greater than ${b}`);
} else {
console.log(`${a} and ${b} are equal.`);
}
```
Note that all comparison operators, including [`===`](../operators/strict_equality) and [`==`](../operators/equality), compare strings case-sensitively. A common way to compare strings case-insensitively is to convert both to the same case (upper or lower) before comparing them.
```
function areEqualCaseInsensitive(str1, str2) {
return str1.toUpperCase() === str2.toUpperCase();
}
```
The choice of whether to transform by [`toUpperCase()`](string/touppercase) or [`toLowerCase()`](string/tolowercase) is mostly arbitrary, and neither one is fully robust when extending beyond the Latin alphabet. For example, the German lowercase letter `ß` and `ss` are both transformed to `SS` by `toUpperCase()`, while the Turkish letter `ı` would be falsely reported as unequal to `I` by `toLowerCase()` unless specifically using [`toLocaleLowerCase("tr")`](string/tolocalelowercase).
```
const areEqualInUpperCase = (str1, str2) =>
str1.toUpperCase() === str2.toUpperCase();
const areEqualInLowerCase = (str1, str2) =>
str1.toLowerCase() === str2.toLowerCase();
areEqualInUpperCase("ß", "ss"); // true; should be false
areEqualInLowerCase("ı", "I"); // false; should be true
```
A locale-aware and robust solution for testing case-insensitive equality is to use the [`Intl.Collator`](intl/collator) API or the string's [`localeCompare()`](string/localecompare) method — they share the same interface — with the [`sensitivity`](intl/collator/collator#sensitivity) option set to `"accent"` or `"base"`.
```
const areEqual = (str1, str2, locale = "en-US") =>
str1.localeCompare(str2, locale, { sensitivity: "accent" }) === 0;
areEqual("ß", "ss", "de"); // false
areEqual("ı", "I", "tr"); // true
```
The `localeCompare()` method enables string comparison in a similar fashion as `strcmp()` — it allows sorting strings in a locale-aware manner.
### String primitives and String objects
Note that JavaScript distinguishes between `String` objects and [primitive string](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) values. (The same is true of [`Boolean`](boolean) and [`Numbers`](number).)
String literals (denoted by double or single quotes) and strings returned from `String` calls in a non-constructor context (that is, called without using the [`new`](../operators/new) keyword) are primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup on the wrapper object instead.
```
const strPrim = "foo"; // A literal is a string primitive
const strPrim2 = String(1); // Coerced into the string primitive "1"
const strPrim3 = String(true); // Coerced into the string primitive "true"
const strObj = new String(strPrim); // String with new returns a string wrapper object.
console.log(typeof strPrim); // "string"
console.log(typeof strPrim2); // "string"
console.log(typeof strPrim3); // "string"
console.log(typeof strObj); // "object"
```
**Warning:** You should rarely find yourself using `String` as a constructor.
String primitives and `String` objects also give different results when using [`eval()`](eval). Primitives passed to `eval` are treated as source code; `String` objects are treated as all other objects are, by returning the object. For example:
```
const s1 = "2 + 2"; // creates a string primitive
const s2 = new String("2 + 2"); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
```
For these reasons, the code may break when it encounters `String` objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.
A `String` object can always be converted to its primitive counterpart with the [`valueOf()`](string/valueof) method.
```
console.log(eval(s2.valueOf())); // returns the number 4
```
### String coercion
Many built-in operations that expect strings first coerce their arguments to strings (which is largely why `String` objects behave similarly to string primitives). [The operation](https://tc39.es/ecma262/#sec-tostring) can be summarized as follows:
* Strings are returned as-is.
* [`undefined`](undefined) turns into `"undefined"`.
* [`null`](../operators/null) turns into `"null"`.
* `true` turns into `"true"`; `false` turns into `"false"`.
* Numbers are converted with the same algorithm as [`toString(10)`](number/tostring).
* [BigInts](bigint) are converted with the same algorithm as [`toString(10)`](bigint/tostring).
* [Symbols](symbol) throw a [`TypeError`](typeerror).
* Objects are first [converted to a primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](symbol/toprimitive) (with `"string"` as hint), `toString()`, and `valueOf()` methods, in that order. The resulting primitive is then converted to a string.
There are several ways to achieve nearly the same effect in JavaScript.
* [Template literal](../template_literals): ``${x}`` does exactly the string coercion steps explained above for the embedded expression.
* The [`String()`](string/string) function: `String(x)` uses the same algorithm to convert `x`, except that [Symbols](symbol) don't throw a [`TypeError`](typeerror), but return `"Symbol(description)"`, where `description` is the [description](symbol/description) of the Symbol.
* Using the [`+` operator](../operators/addition): `"" + x` coerces its operand to a *primitive* instead of a *string*, and, for some objects, has entirely different behaviors from normal string coercion. See its [reference page](../operators/addition) for more details.
Depending on your use case, you may want to use ``${x}`` (to mimic built-in behavior) or `String(x)` (to handle symbol values without throwing an error), but you should not use `"" + x`.
### Escape sequences
Special characters can be encoded using escape sequences:
| Escape sequence | Unicode code point |
| --- | --- |
| `\0` | null character (U+0000 NULL) |
| `\'` | single quote (U+0027 APOSTROPHE) |
| `\"` | double quote (U+0022 QUOTATION MARK) |
| `\\` | backslash (U+005C REVERSE SOLIDUS) |
| `\n` | newline (U+000A LINE FEED; LF) |
| `\r` | carriage return (U+000D CARRIAGE RETURN; CR) |
| `\v` | vertical tab (U+000B LINE TABULATION) |
| `\t` | tab (U+0009 CHARACTER TABULATION) |
| `\b` | backspace (U+0008 BACKSPACE) |
| `\f` | form feed (U+000C FORM FEED) |
| `\uXXXX` …where `XXXX` is exactly 4 hex digits in the range `0000`–`FFFF`; e.g., `\u000A` is the same as `\n` (LINE FEED); `\u0021` is `!` | Unicode code point between `U+0000` and `U+FFFF` (the Unicode Basic Multilingual Plane) |
| `\u{X}`…`\u{XXXXXX}` …where `X`…`XXXXXX` is 1–6 hex digits in the range `0`–`10FFFF`; e.g., `\u{A}` is the same as `\n` (LINE FEED); `\u{21}` is `!` | Unicode code point between `U+0000` and `U+10FFFF` (the entirety of Unicode) |
| `\xXX` …where `XX` is exactly 2 hex digits in the range `00`–`FF`; e.g., `\x0A` is the same as `\n` (LINE FEED); `\x21` is `!` | Unicode code point between `U+0000` and `U+00FF` (the Basic Latin and Latin-1 Supplement blocks; equivalent to ISO-8859-1) |
### Long literal strings
Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents.
You can use the [`+`](../operators/addition) operator to append multiple strings together, like this:
```
const longString =
"This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
```
Or you can use the backslash character (`\`) at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work.
```
const longString =
"This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
```
Both of the above methods result in identical strings.
### UTF-16 characters, Unicode codepoints, and grapheme clusters
Strings are represented fundamentally as sequences of [UTF-16 code units](https://en.wikipedia.org/wiki/UTF-16). In UTF-16 encoding, every code unit is exact 16 bits long. This means there are a maximum of 216, or 65536 possible characters representable as single UTF-16 code units. This character set is called the [basic multilingual plane (BMP)](https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane), and includes the most common characters like the Latin, Greek, Cyrillic alphabets, as well as many East Asian characters. Each code unit can be written in a string with `\u` followed by exactly four hex digits.
However, the entire Unicode character set is much, much bigger than 65536. The extra characters are stored in UTF-16 as *surrogate pairs*, which are pairs of 16-bit code units that represent a single character. To avoid ambiguity, the two parts of the pair must be between `0xD800` and `0xDFFF`, and these code units are not used to encode single-code-unit characters. Therefore, "lone surrogates" are often not valid values for string manipulation — for example, [`encodeURI()`](encodeuri) will throw a [`URIError`](urierror) for lone surrogates. Each Unicode character, comprised of one or two UTF-16 code units, is also called a *Unicode codepoint*. Each Unicode codepoint can be written in a string with `\u{xxxxxx}` where `xxxxxx` represents 1–6 hex digits.
On top of Unicode characters, there are certain sequences of Unicode characters that should be treated as one visual unit, known as a *grapheme cluster*. The most common case is emojis: many emojis that have a range of variations are actually formed by multiple emojis, usually joined by the <ZWJ> (`U+200D`) character.
You must be careful which level of characters you are iterating on. For example, [`split("")`](string/split) will split by UTF-16 code units and will separate surrogate pairs. String indexes also refer to the index of each UTF-16 code unit. On the other hand, [`@@iterator()`](string/@@iterator) iterates by Unicode codepoints. Iterating through grapheme clusters will require some custom code.
```
"😄".split(""); // ['\ud83d', '\ude04']; splits into two lone surrogates
// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji
// "Family: Man, Boy"
[..."👨👦"]; // [ '👨', '', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ
// The United Nations flag
[..."🇺🇳"]; // [ '🇺', '🇳' ]
// splits into two "region indicator" letters "U" and "N".
// All flag emojis are formed by joining two region indicator letters
```
Constructor
-----------
[`String()`](string/string) Creates a new `String` object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.
Static methods
--------------
[`String.fromCharCode()`](string/fromcharcode) Returns a string created by using the specified sequence of Unicode values.
[`String.fromCodePoint()`](string/fromcodepoint) Returns a string created by using the specified sequence of code points.
[`String.raw()`](string/raw) Returns a string created from a raw template string.
Instance properties
-------------------
[`String.prototype.length`](string/length) Reflects the `length` of the string. Read-only.
Instance methods
----------------
[`String.prototype.at()`](string/at) Returns the character (exactly one UTF-16 code unit) at the specified `index`. Accepts negative integers, which count back from the last string character.
[`String.prototype.charAt()`](string/charat) Returns the character (exactly one UTF-16 code unit) at the specified `index`.
[`String.prototype.charCodeAt()`](string/charcodeat) Returns a number that is the UTF-16 code unit value at the given `index`.
[`String.prototype.codePointAt()`](string/codepointat) Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified `pos`.
[`String.prototype.concat()`](string/concat) Combines the text of two (or more) strings and returns a new string.
[`String.prototype.includes()`](string/includes) Determines whether the calling string contains `searchString`.
[`String.prototype.endsWith()`](string/endswith) Determines whether a string ends with the characters of the string `searchString`.
[`String.prototype.indexOf()`](string/indexof) Returns the index within the calling [`String`](string) object of the first occurrence of `searchValue`, or `-1` if not found.
[`String.prototype.lastIndexOf()`](string/lastindexof) Returns the index within the calling [`String`](string) object of the last occurrence of `searchValue`, or `-1` if not found.
[`String.prototype.localeCompare()`](string/localecompare) Returns a number indicating whether the reference string `compareString` comes before, after, or is equivalent to the given string in sort order.
[`String.prototype.match()`](string/match) Used to match regular expression `regexp` against a string.
[`String.prototype.matchAll()`](string/matchall) Returns an iterator of all `regexp`'s matches.
[`String.prototype.normalize()`](string/normalize) Returns the Unicode Normalization Form of the calling string value.
[`String.prototype.padEnd()`](string/padend) Pads the current string from the end with a given string and returns a new string of the length `targetLength`.
[`String.prototype.padStart()`](string/padstart) Pads the current string from the start with a given string and returns a new string of the length `targetLength`.
[`String.prototype.repeat()`](string/repeat) Returns a string consisting of the elements of the object repeated `count` times.
[`String.prototype.replace()`](string/replace) Used to replace occurrences of `searchFor` using `replaceWith`. `searchFor` may be a string or Regular Expression, and `replaceWith` may be a string or function.
[`String.prototype.replaceAll()`](string/replaceall) Used to replace all occurrences of `searchFor` using `replaceWith`. `searchFor` may be a string or Regular Expression, and `replaceWith` may be a string or function.
[`String.prototype.search()`](string/search) Search for a match between a regular expression `regexp` and the calling string.
[`String.prototype.slice()`](string/slice) Extracts a section of a string and returns a new string.
[`String.prototype.split()`](string/split) Returns an array of strings populated by splitting the calling string at occurrences of the substring `sep`.
[`String.prototype.startsWith()`](string/startswith) Determines whether the calling string begins with the characters of string `searchString`.
[`String.prototype.substring()`](string/substring) Returns a new string containing characters of the calling string from (or between) the specified index (or indices).
[`String.prototype.toLocaleLowerCase()`](string/tolocalelowercase) The characters within a string are converted to lowercase while respecting the current locale.
For most languages, this will return the same as [`toLowerCase()`](string/tolowercase).
[`String.prototype.toLocaleUpperCase( [locale, ...locales])`](string/tolocaleuppercase) The characters within a string are converted to uppercase while respecting the current locale.
For most languages, this will return the same as [`toUpperCase()`](string/touppercase).
[`String.prototype.toLowerCase()`](string/tolowercase) Returns the calling string value converted to lowercase.
[`String.prototype.toString()`](string/tostring) Returns a string representing the specified object. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`String.prototype.toUpperCase()`](string/touppercase) Returns the calling string value converted to uppercase.
[`String.prototype.trim()`](string/trim) Trims whitespace from the beginning and end of the string.
[`String.prototype.trimStart()`](string/trimstart) Trims whitespace from the beginning of the string.
[`String.prototype.trimEnd()`](string/trimend) Trims whitespace from the end of the string.
[`String.prototype.valueOf()`](string/valueof) Returns the primitive value of the specified object. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
[`String.prototype[@@iterator]()`](string/@@iterator) Returns a new iterator object that iterates over the code points of a String value, returning each code point as a String value.
HTML wrapper methods
--------------------
**Warning:** Deprecated. Avoid these methods.
They are of limited use, as they are based on a very old HTML standard and provide only a subset of the currently available HTML tags and attributes. Many of them create deprecated or non-standard markup today. In addition, they do simple string concatenation without any validation or sanitation, which makes them a potential security threat when directly inserted using [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML). Use [DOM APIs](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) instead.
[`String.prototype.anchor()`](string/anchor) Deprecated
[`<a name="name">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-name) (hypertext target)
[`String.prototype.big()`](string/big) Deprecated
[`<big>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/big)
[`String.prototype.blink()`](string/blink) Deprecated
[`<blink>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blink)
[`String.prototype.bold()`](string/bold) Deprecated
[`<b>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b)
[`String.prototype.fixed()`](string/fixed) Deprecated
[`<tt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tt)
[`String.prototype.fontcolor()`](string/fontcolor) Deprecated
[`<font color="color">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font#attr-color)
[`String.prototype.fontsize()`](string/fontsize) Deprecated
[`<font size="size">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font#attr-size)
[`String.prototype.italics()`](string/italics) Deprecated
[`<i>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i)
[`String.prototype.link()`](string/link) Deprecated
[`<a href="url">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-href) (link to URL)
[`String.prototype.small()`](string/small) Deprecated
[`<small>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small)
[`String.prototype.strike()`](string/strike) Deprecated
[`<strike>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strike)
[`String.prototype.sub()`](string/sub) Deprecated
[`<sub>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub)
[`String.prototype.sup()`](string/sup) Deprecated
[`<sup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup) Note that these methods do not check if the string itself contains HTML tags, so it's possible to create invalid HTML:
```
"</b>".bold(); // <b></b></b>
```
The only escaping they do is to replace `"` in the attribute value (for [`anchor()`](string/anchor), [`fontcolor()`](string/fontcolor), [`fontsize()`](string/fontsize), and [`link()`](string/link)) with `"`.
```
"foo".anchor('"Hello"'); // <a name=""Hello"">foo</a>
```
Examples
--------
### String conversion
It's possible to use `String` as a more reliable [`toString()`](string/tostring) alternative, as it works when used on [`null`](../operators/null) and [`undefined`](undefined). For example:
```
const nullVar = null;
nullVar.toString(); // TypeError: nullVar is null
String(nullVar); // "null"
const undefinedVar = undefined;
undefinedVar.toString(); // TypeError: undefinedVar is undefined
String(undefinedVar); // "undefined"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-string-objects](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 9 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `String` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `String` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `anchor` | 1 | 12 | 1
Starting with version 17, the quotation mark (") is replaced by its HTML reference character (`"`) in strings supplied for the `name` parameter. | No | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `at` | 92 | 92 | 90 | No | 78 | 15.4 | 92 | 92 | 90 | 65 | 15.4 | 16.0 | 1.12 | 16.6.0 |
| `big` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `blink` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `bold` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `charAt` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `charCodeAt` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `codePointAt` | 41 | 12 | 29 | No | 28 | 9 | 41 | 41 | 29 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `concat` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `endsWith` | 41 | 12 | 17 | No | 28 | 9 | 37 | 36 | 17 | 24 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
| `fixed` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fontcolor` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fontsize` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fromCharCode` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fromCodePoint` | 41 | 12 | 29 | No | 28 | 9 | 41 | 41 | 29 | 28 | 9 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `includes` | 41 | 12 | 40
18-48 | No | 28 | 9 | 41 | 41 | 40
18-48 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
| `indexOf` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `italics` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lastIndexOf` | 1 | 12 | 1 | 6 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `length` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `link` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `localeCompare` | 1 | 12 | 1 | 5.5 | 7 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `match` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `matchAll` | 73 | 79 | 67 | No | 60 | 13 | 73 | 73 | 67 | 52 | 13 | 11.0 | 1.0 | 12.0.0 |
| `normalize` | 34 | 12 | 31 | No | 21 | 10 | 37 | 34 | 31 | 21 | 10 | 2.0 | 1.0 | 0.12.0 |
| `padEnd` | 57 | 15 | 48 | No | 44 | 10 | 57 | 57 | 48 | 43 | 10 | 7.0 | 1.0 | 8.0.0
7.0.0 |
| `padStart` | 57 | 15 | 48 | No | 44 | 10 | 57 | 57 | 48 | 43 | 10 | 7.0 | 1.0 | 8.0.0
7.0.0 |
| `raw` | 41 | 12 | 34 | No | 28 | 9 | 41 | 41 | 34 | 28 | 9 | 4.0 | 1.0 | 4.0.0 |
| `repeat` | 41 | 12 | 24 | No | 28 | 9 | 41 | 36 | 24 | 28 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
| `replace` | 1 | 12 | 1 | 5.5
4-5.5
A replacement function as second argument is not supported. | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `replaceAll` | 85 | 85 | 77 | No | 71 | 13.1 | 85 | 85 | 79 | 60 | 13.4 | 14.0 | 1.2 | 15.0.0 |
| `search` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `slice` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `small` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `split` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `startsWith` | 41 | 12 | 17 | No | 28 | 9 | 37 | 36 | 17 | 24 | 9 | 3.0 | 1.0 | 4.0.0
0.12.0 |
| `strike` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sub` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `substr` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `substring` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sup` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleLowerCase` | 1 | 12 | 1 | 5.5 | 4 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleUpperCase` | 1 | 12 | 1 | 5.5 | 4 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLowerCase` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toUpperCase` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `trim` | 4 | 12 | 3.5 | 10 | 10.5 | 5 | ≤37 | 18 | 4 | 11 | 5 | 1.0 | 1.0 | 0.10.0 |
| `trimEnd` | 66
4 | 79
12 | 61
3.5 | No | 53
15 | 12 | 66
≤37 | 66
18 | 61
4 | 47
14 | 12 | 9.0
1.0 | 1.0
1.0 | 10.0.0
0.12.0 |
| `trimStart` | 66
4 | 79
12 | 61
3.5 | No | 53
15 | 12 | 66
≤37 | 66
18 | 61
4 | 47
14 | 12 | 9.0
1.0 | 1.0
1.0 | 10.0.0
0.12.0 |
| `unicode_code_point_escapes` | 1 | 12 | 40 | 4 | 4 | 1 | 4.4 | 18 | 40 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `valueOf` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Text formatting in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting)
* [`RegExp`](regexp)
| programming_docs |
javascript InternalError InternalError
=============
**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The `InternalError` indicates an error that occurred internally in the JavaScript engine.
Example cases are mostly when something is too large, e.g.:
* "too many switch cases",
* "too many parentheses in regular expression",
* "array initializer too large",
* "too much recursion".
Constructor
-----------
[`InternalError()`](internalerror/internalerror) Non-standard
Creates a new `InternalError` object.
Instance properties
-------------------
[`InternalError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`InternalError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`InternalError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`InternalError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`InternalError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`InternalError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`InternalError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Too much recursion
This recursive function runs 10 times, as per the exit condition.
```
function loop(x) {
// "x >= 10" is the exit condition
if (x >= 10) return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
```
Setting this condition to an extremely high value, may not work:
```
function loop(x) {
if (x >= 1000000000000) return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
```
For more information, see [InternalError: too much recursion.](../errors/too_much_recursion)
Specifications
--------------
Not part of any standard.
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `InternalError` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `InternalError` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
See also
--------
* [`Error`](error)
* [InternalError: too much recursion](../errors/too_much_recursion)
javascript Number Number
======
`Number` values represent floating-point numbers like `37` or `-9.25`.
The `Number` constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the `Number()` function.
Description
-----------
Numbers are most commonly expressed in literal forms like `0b101`, `0o13`, `0x0A`. The [lexical grammar](../lexical_grammar#numeric_literals) contains a more detailed reference.
```
123; // one-hundred twenty-three
123.0; // same
123 === 123.0; // true
```
A number literal like `37` in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript also has a [`BigInt`](bigint) type, but it's not designed to replace Number for everyday uses. `37` is still a number, not a BigInt.)
When used as a function, `Number(value)` converts a string or other value to the Number type. If the value can't be converted, it returns [`NaN`](nan).
```
Number("123"); // returns the number 123
Number("123") === 123; // true
Number("unicorn"); // NaN
Number(undefined); // NaN
```
### Number encoding
The JavaScript `Number` type is a [double-precision 64-bit binary format IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) value, like `double` in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision. Very briefly, an IEEE 754 double-precision number uses 64 bits to represent 3 parts:
* 1 bit for the *sign* (positive or negative)
* 11 bits for the *exponent* (-1022 to 1023)
* 52 bits for the *mantissa* (representing a number between 0 and 1)
The mantissa (also called *significand*) is the part of the number representing the actual value (significant digits). The exponent is the power of 2 that the mantissa should be multiplied by. Thinking about it as scientific notation:
Number = ( − 1 ) sign ⋅ ( 1 + mantissa ) ⋅ 2 exponent \text{Number} = ({-1})^{\text{sign}} \cdot (1 + \text{mantissa}) \cdot 2^{\text{exponent}}
The mantissa is stored with 52 bits, interpreted as digits after `1.…` in a binary fractional number. Therefore, the mantissa's precision is 2-52 (obtainable via [`Number.EPSILON`](number/epsilon)), or about 15 to 17 decimal places; arithmetic above that level of precision is subject to [rounding](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Representable_numbers,_conversion_and_rounding).
The largest value a number can hold is 21024 - 1 (with the exponent being 1023 and the mantissa being 0.1111… in base 2), which is obtainable via [`Number.MAX_VALUE`](number/max_value). Values higher than that are replaced with the special number constant [`Infinity`](infinity).
Integers can only be represented without loss of precision in the range -253 + 1 to 253 - 1, inclusive (obtainable via [`Number.MIN_SAFE_INTEGER`](number/min_safe_integer) and [`Number.MAX_SAFE_INTEGER`](number/max_safe_integer)), because the mantissa can only hold 53 bits (including the leading 1).
More details on this are described in the [ECMAScript standard](https://tc39.es/ecma262/#sec-ecmascript-language-types-number-type).
### Number coercion
Many built-in operations that expect numbers first coerce their arguments to numbers (which is largely why `Number` objects behave similarly to number primitives). [The operation](https://tc39.es/ecma262/#sec-tonumber) can be summarized as follows:
* Numbers are returned as-is.
* [`undefined`](undefined) turns into [`NaN`](nan).
* [`null`](../operators/null) turns into `0`.
* `true` turns into `1`; `false` turns into `0`.
* Strings are converted by parsing them as if they contain a [number literal](../lexical_grammar#numeric_literals). Parsing failure results in `NaN`. There are some minor differences compared to an actual number literal:
+ Leading and trailing whitespace/line terminators are ignored.
+ A leading `0` digit does not cause the number to become an octal literal (or get rejected in strict mode).
+ `+` and `-` are allowed at the start of the string to indicate its sign. (In actual code, they "look like" part of the literal, but are actually separate unary operators.) However, the sign can only appear once, and must not be followed by whitespace.
+ `Infinity` and `-Infinity` are recognized as literals. In actual code, they are global variables.
+ Empty or whitespace-only strings are converted to `0`.
+ [Numeric separators](../lexical_grammar#numeric_separators) are not allowed.
* [BigInts](bigint) throw a [`TypeError`](typeerror) to prevent unintended implicit coercion causing loss of precision.
* [Symbols](symbol) throw a [`TypeError`](typeerror).
* Objects are first [converted to a primitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling their [`[@@toPrimitive]()`](symbol/toprimitive) (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. The resulting primitive is then converted to a number.
There are two ways to achieve nearly the same effect in JavaScript.
* [Unary plus](../operators/unary_plus): `+x` does exactly the number coercion steps explained above to convert `x`.
* The [`Number()`](number/number) function: `Number(x)` uses the same algorithm to convert `x`, except that [BigInts](bigint) don't throw a [`TypeError`](typeerror), but return their number value, with possible loss of precision.
[`Number.parseFloat()`](number/parsefloat) and [`Number.parseInt()`](number/parseint) are similar to `Number()` but only convert strings, and have slightly different parsing rules. For example, `parseInt()` doesn't recognize the decimal point, and `parseFloat()` doesn't recognize the `0x` prefix.
#### Integer conversion
Some operations expect integers, most notably those that work with array/string indices, date/time components, and number radixes. After performing the number coercion steps above, the result is [truncated](math/trunc) to an integer (by discarding the fractional part). If the number is ±Infinity, it's returned as-is. If the number is `NaN` or `-0`, it's returned as `0`. The result is therefore always an integer (which is not `-0`) or ±Infinity.
Notably, when converted to integers, both `undefined` and `null` become `0`, because `undefined` is converted to `NaN`, which also becomes `0`.
#### Fixed-width number conversion
JavaScript has some lower-level functions that deal with the binary encoding of integer numbers, most notably [bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators) and [`TypedArray`](typedarray) objects. Bitwise operators always convert the operands to 32-bit integers. In these cases, after converting the value to a number, the number is then normalized to the given width by first [truncating](math/trunc) the fractional part and then taking the lowest bits in the integer's two's complement encoding.
```
new Int32Array([1.1, 1.9, -1.1, -1.9]); // Int32Array(4) [ 1, 1, -1, -1 ]
new Int8Array([257, -257]); // Int8Array(1) [ 1, -1 ]
// 257 = 0001 0000 0001 = 0000 0001 (mod 2^8) = 1
// -257 = 1110 1111 1111 = 1111 1111 (mod 2^8) = -1 (as signed integer)
new Uint8Array([257, -257]); // Uint8Array(1) [ 1, 255 ]
// -257 = 1110 1111 1111 = 1111 1111 (mod 2^8) = 255 (as unsigned integer)
```
Constructor
-----------
[`Number()`](number/number) Creates a new `Number` value.
When `Number` is called as a constructor (with `new`), it creates a [`Number`](number) object, which is **not** a primitive. For example, `typeof new Number(42) === "object"`, and `new Number(42) !== 42` (although `new Number(42) == 42`).
**Warning:** You should rarely find yourself using `Number` as a constructor.
Static properties
-----------------
[`Number.EPSILON`](number/epsilon) The smallest interval between two representable numbers.
[`Number.MAX_SAFE_INTEGER`](number/max_safe_integer) The maximum safe integer in JavaScript (253 - 1).
[`Number.MAX_VALUE`](number/max_value) The largest positive representable number.
[`Number.MIN_SAFE_INTEGER`](number/min_safe_integer) The minimum safe integer in JavaScript (-(253 - 1)).
[`Number.MIN_VALUE`](number/min_value) The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).
[`Number.NaN`](number/nan) Special "**N**ot **a** **N**umber" value.
[`Number.NEGATIVE_INFINITY`](number/negative_infinity) Special value representing negative infinity. Returned on overflow.
[`Number.POSITIVE_INFINITY`](number/positive_infinity) Special value representing infinity. Returned on overflow.
[`Number.prototype`](number) Allows the addition of properties to the `Number` object.
Static methods
--------------
[`Number.isNaN()`](number/isnan) Determine whether the passed value is `NaN`.
[`Number.isFinite()`](number/isfinite) Determine whether the passed value is a finite number.
[`Number.isInteger()`](number/isinteger) Determine whether the passed value is an integer.
[`Number.isSafeInteger()`](number/issafeinteger) Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).
[`Number.parseFloat()`](number/parsefloat) This is the same as the global [`parseFloat()`](parsefloat) function.
[`Number.parseInt()`](number/parseint) This is the same as the global [`parseInt()`](parseint) function.
Instance methods
----------------
[`Number.prototype.toExponential()`](number/toexponential) Returns a string representing the number in exponential notation.
[`Number.prototype.toFixed()`](number/tofixed) Returns a string representing the number in fixed-point notation.
[`Number.prototype.toLocaleString()`](number/tolocalestring) Returns a string with a language sensitive representation of this number. Overrides the [`Object.prototype.toLocaleString()`](object/tolocalestring) method.
[`Number.prototype.toPrecision()`](number/toprecision) Returns a string representing the number to a specified precision in fixed-point or exponential notation.
[`Number.prototype.toString()`](number/tostring) Returns a string representing the specified object in the specified *radix* ("base"). Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`Number.prototype.valueOf()`](number/valueof) Returns the primitive value of the specified object. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
Examples
--------
### Using the Number object to assign values to numeric variables
The following example uses the `Number` object's properties to assign values to several numeric variables:
```
const biggestNum = Number.MAX\_VALUE;
const smallestNum = Number.MIN\_VALUE;
const infiniteNum = Number.POSITIVE\_INFINITY;
const negInfiniteNum = Number.NEGATIVE\_INFINITY;
const notANum = Number.NaN;
```
### Integer range for Number
The following example shows the minimum and maximum integer values that can be represented as `Number` object.
```
const biggestInt = Number.MAX\_SAFE\_INTEGER; // (2\*\*53 - 1) => 9007199254740991
const smallestInt = Number.MIN\_SAFE\_INTEGER; // -(2\*\*53 - 1) => -9007199254740991
```
When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to `Number` type.
A possible workaround is to use [`String`](string) instead.
Larger numbers can be represented using the [`BigInt`](bigint) type.
### Using Number() to convert a Date object
The following example converts the [`Date`](date) object to a numerical value using `Number` as a function:
```
const d = new Date("December 17, 1995 03:24:00");
console.log(Number(d));
```
This logs `819199440000`.
### Convert numeric strings and null to numbers
```
Number("123"); // 123
Number("123") === 123; // true
Number("12.3"); // 12.3
Number("12.00"); // 12
Number("123e-1"); // 12.3
Number(""); // 0
Number(null); // 0
Number("0x11"); // 17
Number("0b11"); // 3
Number("0o11"); // 9
Number("foo"); // NaN
Number("100a"); // NaN
Number("-Infinity"); // -Infinity
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-number-objects](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `EPSILON` | 34 | 12 | 25 | No | 21 | 9 | 37 | 34 | 25 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `MAX_SAFE_INTEGER` | 34 | 12 | 31 | No | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `MAX_VALUE` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `MIN_SAFE_INTEGER` | 34 | 12 | 31 | No | 21 | 9 | 37 | 34 | 31 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `MIN_VALUE` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `NEGATIVE_INFINITY` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `NaN` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Number` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `POSITIVE_INFINITY` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Number` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `isFinite` | 19 | 12 | 16 | No | 15 | 9 | 4.4 | 25 | 16 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
| `isInteger` | 34 | 12 | 16 | No | 21 | 9 | 37 | 34 | 16 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `isNaN` | 25 | 12 | 15 | No | 15 | 9 | 4.4 | 25 | 15 | 14 | 9 | 1.5 | 1.0 | 0.10.0 |
| `isSafeInteger` | 34 | 12 | 32 | No | 21 | 9 | 37 | 34 | 32 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `parseFloat` | 34 | 12 | 25 | No | 21 | 9 | 37 | 34 | 25 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `parseInt` | 34 | 12 | 25 | No | 21 | 9 | 37 | 34 | 25 | 21 | 9 | 2.0 | 1.0 | 0.12.0 |
| `toExponential` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toFixed` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleString` | 1 | 12
Before Edge 18, numbers are rounded to 15 decimal digits. For example, `(1000000000000005).toLocaleString('en-US')` returns `"1,000,000,000,000,010"`. | 1 | 5
In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, `(1000000000000005).toLocaleString('en-US')` returns `"1,000,000,000,000,010"`. | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toPrecision` | 1 | 12 | 1 | 5.5 | 7 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `valueOf` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of modern `Number` behavior (with support binary and octal literals) in `core-js`](https://github.com/zloirock/core-js#ecmascript-number)
* [`NaN`](nan)
* [Arithmetic operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#arithmetic_operators)
* The [`Math`](math) global object
* Integers with arbitrary precision: [`BigInt`](bigint)
javascript FinalizationRegistry FinalizationRegistry
====================
A `FinalizationRegistry` object lets you request a callback when an object is garbage-collected.
Description
-----------
`FinalizationRegistry` provides a way to request that a *cleanup callback* get called at some point when an object registered with the registry has been *reclaimed* (garbage-collected). (Cleanup callbacks are sometimes called *finalizers*.)
**Note:** Cleanup callbacks should not be used for essential program logic. See [Notes on cleanup callbacks](#notes_on_cleanup_callbacks) for details.
You create the registry passing in the callback:
```
const registry = new FinalizationRegistry((heldValue) => {
// …
});
```
Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it:
```
registry.register(theObject, "some value");
```
The registry does not keep a strong reference to the object, as that would defeat the purpose (if the registry held it strongly, the object would never be reclaimed).
If `theObject` is reclaimed, your cleanup callback may be called at some point with the *held value* you provided for it (`"some value"` in the above). The held value can be any value you like: a primitive or an object, even `undefined`. If the held value is an object, the registry keeps a *strong* reference to it (so it can pass it to your cleanup callback later).
If you might want to unregister an object later, you pass a third value, which is the *unregistration token* you'll use later when calling the registry's `unregister` function to unregister the object. The registry only keeps a weak reference to the unregister token.
It's common to use the object itself as the unregister token, which is just fine:
```
registry.register(theObject, "some value", theObject);
// …
// some time later, if you don't care about `theObject` anymore unregister it
registry.unregister(theObject);
```
It doesn't have to be the same object, though; it can be a different one:
```
registry.register(theObject, "some value", tokenObject);
// …
// some time later
registry.unregister(tokenObject);
```
### Avoid where possible
Correct use of `FinalizationRegistry` takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.
Here are some specific points that the authors of the WeakRef proposal that FinalizationRegistry is part of included in its [explainer document](https://github.com/tc39/proposal-weakrefs/blob/master/reference.md):
> [Garbage collectors](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) are complicated. If an application or library depends on GC cleaning up a FinalizationRegistry or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:
>
> * One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
> * Garbage collection work can be split up over time using incremental and concurrent techniques.
> * Various runtime heuristics can be used to balance memory usage, responsiveness.
> * The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
> * Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
> * Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
>
>
### Notes on cleanup callbacks
* Developers shouldn't rely on cleanup callbacks for essential program logic. Cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful otherwise.
* A conforming JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks. When and whether it does so is entirely down to the implementation of the JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all.
* It's likely that major implementations will call cleanup callbacks at some point during execution, but those calls may be substantially after the related object was reclaimed.
* There are also situations where even implementations that normally call cleanup callbacks are unlikely to call them:
+ When the JavaScript program shuts down entirely (for instance, closing a tab in a browser).
+ When the `FinalizationRegistry` instance itself is no longer reachable by JavaScript code.
Constructor
-----------
[`FinalizationRegistry()`](finalizationregistry/finalizationregistry) Creates a new `FinalizationRegistry` object.
Instance properties
-------------------
`FinalizationRegistry.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"FinalizationRegistry"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`FinalizationRegistry.prototype.register()`](finalizationregistry/register) Registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected.
[`FinalizationRegistry.prototype.unregister()`](finalizationregistry/unregister) Unregisters an object from the registry.
Examples
--------
### Creating a new registry
You create the registry passing in the callback:
```
const registry = new FinalizationRegistry((heldValue) => {
// …
});
```
### Registering objects for cleanup
Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it:
```
registry.register(theObject, "some value");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-finalization-registry-objects](https://tc39.es/ecma262/multipage/managing-memory.html#sec-finalization-registry-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `FinalizationRegistry` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
| `FinalizationRegistry` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
| `register` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
| `unregister` | 84 | 84 | 79 | No | 70 | 14.1 | 84 | 84 | 79 | 60 | 14.5 | 14.0 | 1.0 | 14.6.0
13.0.0 |
See also
--------
* [`WeakRef`](weakref)
* [`WeakSet`](weakset)
* [`WeakMap`](weakmap)
| programming_docs |
javascript encodeURI() encodeURI()
===========
The `encodeURI()` function encodes a [URI](https://developer.mozilla.org/en-US/docs/Glossary/URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the [UTF-8](https://developer.mozilla.org/en-US/docs/Glossary/UTF-8) encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to [`encodeURIComponent()`](encodeuricomponent), this function encodes fewer characters, preserving those that are part of the URI syntax.
Try it
------
Syntax
------
```
encodeURI(uri)
```
### Parameters
`uri` A string to be encoded as a URI.
### Return value
A new string representing the provided string encoded as a URI.
### Exceptions
[`URIError`](urierror) Thrown if `uri` contains a [lone surrogate](string#utf-16_characters_unicode_codepoints_and_grapheme_clusters).
Description
-----------
`encodeURI()` is a function property of the global object.
The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a [`URIError`](urierror).
`encodeURI()` escapes all characters **except**:
```
A–Z a–z 0–9 - _ . ! ~ * ' ( )
; / ? : @ & = + $ , #
```
The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt))
The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning:
```
http://username:[email protected]:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
```
Examples
--------
### encodeURI() vs. encodeURIComponent()
`encodeURI()` differs from [`encodeURIComponent()`](encodeuricomponent) as follows:
```
const set1 = ";/?:@&=+$,#"; // Reserved Characters
const set2 = "-.!~\*'()"; // Unreserved Marks
const set3 = "ABC abc 123"; // Alphanumeric Characters + Space
console.log(encodeURI(set1)); // ;/?:@&=+$,#
console.log(encodeURI(set2)); // -.!~\*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
console.log(encodeURIComponent(set2)); // -.!~\*'()
console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
```
Note that `encodeURI()` by itself *cannot* form proper HTTP [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) and [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) requests, such as for [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), because `&`, `+`, and `=` are not encoded, which are treated as special characters in `GET` and `POST` requests. `encodeURIComponent()`, however, does encode these characters.
### Encoding a lone high surrogate throws
An [`URIError`](urierror) will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:
```
// High-low pair OK
encodeURI("\uD800\uDFFF"); // "%F0%90%8F%BF"
// Lone high surrogate throws "URIError: malformed URI sequence"
encodeURI("\uD800");
// Lone low surrogate throws "URIError: malformed URI sequence"
encodeURI("\uDFFF");
```
### Encoding for RFC3986
The more recent [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986) makes square brackets reserved (for [IPv6](https://developer.mozilla.org/en-US/docs/Glossary/IPv6)) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format.
```
function encodeRFC3986URI(str) {
return encodeURI(str)
.replace(/%5B/g, "[")
.replace(/%5D/g, "]")
.replace(
/[!'()\*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
);
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-encodeuri-uri](https://tc39.es/ecma262/multipage/global-object.html#sec-encodeuri-uri) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `encodeURI` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`decodeURI()`](decodeuri)
* [`encodeURIComponent()`](encodeuricomponent)
* [`decodeURIComponent()`](decodeuricomponent)
javascript Int32Array Int32Array
==========
The `Int32Array` typed array represents an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Int32Array()`](int32array/int32array) Creates a new `Int32Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Int32Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of `Int32Array`.
[`Int32Array.name`](typedarray/name) Returns the string value of the constructor name. `"Int32Array"` in the case of `Int32Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Int32Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of a `Int32Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create an Int32Array
```
// From a length
const int32 = new Int32Array(2);
int32[0] = 42;
console.log(int32[0]); // 42
console.log(int32.length); // 2
console.log(int32.BYTES\_PER\_ELEMENT); // 4
// From an array
const x = new Int32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Int32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const int32FromIterable = new Int32Array(iterable);
console.log(int32FromIterable);
// Int32Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Int32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Int32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Int32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript isNaN() isNaN()
=======
The `isNaN()` function determines whether a value is [`NaN`](nan) when converted to a number. Because coercion inside the `isNaN()` function can be [surprising](#description), you may alternatively want to use [`Number.isNaN()`](number/isnan).
Try it
------
Syntax
------
```
isNaN(value)
```
### Parameters
`value` The value to be tested.
### Return value
`true` if the given value is [`NaN`](nan) after being [converted to a number](number#number_coercion); otherwise, `false`.
Description
-----------
`isNaN()` is a function property of the global object.
For number values, `isNaN()` tests if the number is the value [`NaN`](nan). When the argument to the `isNaN()` function is not of type [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against [`NaN`](nan).
This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point [`NaN`](nan) value" nor the question "is the input not a number".
[`Number.isNaN()`](number/isnan) is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](../operators/typeof).
The `isNaN()` function answers the question "is the input functionally equivalent to [`NaN`](nan) when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context.
Examples
--------
Note how `isNaN()` returns `true` for values that are not the value `NaN` but are not numbers either:
```
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// Strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN("37,5"); // true
isNaN("123ABC"); // true: Number("123ABC") is NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
// Dates
isNaN(new Date()); // false; Date objects can be converted to a number (timestamp)
isNaN(new Date().toString()); // true; the string representation of a Date object cannot be parsed as a number
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-isnan-number](https://tc39.es/ecma262/multipage/global-object.html#sec-isnan-number) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isNaN` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`NaN`](nan)
* [`Number.isNaN()`](number/isnan)
javascript BigInt64Array BigInt64Array
=============
The `BigInt64Array` typed array represents an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`BigInt64Array()`](bigint64array/bigint64array) Creates a new `BigInt64Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`BigInt64Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of `BigInt64Array`.
[`BigInt64Array.name`](typedarray/name) Returns the string value of the constructor name. `"BigInt64Array"` in the case of `BigInt64Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`BigInt64Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of a `BigInt64Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a `BigInt64Array`
```
// From a length
const bigint64 = new BigInt64Array(2);
bigint64[0] = 42n;
console.log(bigint64[0]); // 42n
console.log(bigint64.length); // 2
console.log(bigint64.BYTES\_PER\_ELEMENT); // 8
// From an array
const x = new BigInt64Array([21n, 31n]);
console.log(x[1]); // 31n
// From another TypedArray
const y = new BigInt64Array(x);
console.log(y[0]); // 21n
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigInt64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = function\*() { yield\* [1n, 2n, 3n]; }();
const bigint64FromIterable = new BigInt64Array(iterable);
console.log(bigint64FromIterable);
// BigInt64Array [1n, 2n, 3n]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray-objects](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `BigInt64Array` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `BigInt64Array` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`BigUint64Array`](biguint64array)
* [`DataView`](dataview)
javascript parseInt() parseInt()
==========
The `parseInt()` function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems).
Try it
------
Syntax
------
```
parseInt(string)
parseInt(string, radix)
```
### Parameters
`string` A string starting with an integer. Leading [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) in this argument is ignored.
`radix` Optional
An integer between `2` and `36` that represents the *radix* (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](number#fixed-width_number_conversion); if it's outside the range of [2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does NOT always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided.
### Return value
An integer parsed from the given `string`, or [`NaN`](nan) when
* the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or
* the first non-whitespace character cannot be converted to a number.
**Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](parsefloat) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a [`Number`](number) 42.
Description
-----------
The `parseInt` function [converts its first argument to a string](string#string_coercion), parses that string, then returns an integer or `NaN`.
If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.)
The `radix` argument is [converted to a number](number#number_coercion). If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following:
1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number.
2. If the input `string` begins with any other value, the radix is `10` (decimal).
**Note:** Other prefixes like `0b`, which are valid in [number literals](../lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does *not* treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing.
If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`).
If the radix value (coerced if necessary) is not in range [2, 36] (inclusive) `parseInt` returns `NaN`.
For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive.
`parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string.
If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](parsefloat)), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer.
If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed.
For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](number/isnan) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`.
Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 1023), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should *not* be used as a substitute for [`Math.trunc()`](math/trunc).
To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](number/tostring).
Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](number/issafeinteger). The [`BigInt()`](bigint/bigint) function supports parsing integers of arbitrary length accurately, by returning a [`BigInt`](bigint).
Examples
--------
### Using parseInt()
The following examples all return `15`:
```
parseInt("0xF", 16);
parseInt("F", 16);
parseInt("17", 8);
parseInt("015", 10); // but `parseInt('015', 8)` will return 13
parseInt("15,123", 10);
parseInt("FXX123", 16);
parseInt("1111", 2);
parseInt("15 \* 3", 10);
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);
```
The following examples all return `NaN`:
```
parseInt("Hello", 8); // Not a number at all
parseInt("546", 2); // Digits other than 0 or 1 are invalid for binary radix
```
The following examples all return `-15`:
```
parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
parseInt("-17", 8);
parseInt("-15", 10);
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);
```
The following example returns `224`:
```
parseInt("0e0", 16);
```
`parseInt()` does not handle [`BigInt`](bigint) values. It stops at the `n` character, and treats the preceding string as a normal integer, with possible loss of precision.
```
parseInt("900719925474099267n");
// 900719925474099300
```
You should pass the string to the [`BigInt()`](bigint/bigint) function instead, without the trailing `n` character.
```
BigInt("900719925474099267");
// 900719925474099267n
```
`parseInt` doesn't work with [numeric separators](../lexical_grammar#numeric_separators):
```
parseInt("123\_456"); // 123
```
### Using parseInt() on non-strings
`parseInt()` can have interesting results when working on non-strings combined with a high radix; for example, `36` (which makes all alphanumeric characters valid numeric digits).
```
parseInt(null, 36); // 1112745: The string "null" is 1112745 in base 36
parseInt(undefined, 36); // 86464843759093: The string "undefined" is 86464843759093 in base 36
```
In general, it's a bad idea to use `parseInt()` on non-strings, especially to use it as a substitution for [`Math.trunc()`](math/trunc). It may work on small numbers:
```
parseInt(15.99, 10); // 15
parseInt(-15.1, 10); // -15
```
However, it only happens to work because the string representation of these numbers uses basic fractional notation (`"15.99"`, `"-15.1"`), where `parseInt()` stops at the decimal point. Numbers greater than or equal to 1e+21 or less than or equal to 1e-7 use exponential notation (`"1.5e+22"`, `"1.51e-8"`) in their string representation, and `parseInt()` will stop at the `e` character or decimal point, which always comes after the first digit. This means for large and small numbers, `parseInt()` will return a one-digit integer:
```
parseInt(4.7 \* 1e22, 10); // Very large number becomes 4
parseInt(0.00000000000434, 10); // Very small number becomes 4
parseInt(0.0000001, 10); // 1
parseInt(0.000000123, 10); // 1
parseInt(1e-7, 10); // 1
parseInt(1000000000000000000000, 10); // 1
parseInt(123000000000000000000000, 10); // 1
parseInt(1e21, 10); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-parseint-string-radix](https://tc39.es/ecma262/multipage/global-object.html#sec-parseint-string-radix) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `parseInt` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `leading_zero_strings_as_decimal` | 23 | 12 | 21 | 9 | 15 | 6 | 4.4 | 25 | 21 | 14 | 6 | 1.5 | 1.0 | 0.10.0 |
See also
--------
* [`parseFloat()`](parsefloat)
* [`Number()`](number/number)
* [`Number.parseFloat()`](number/parsefloat)
* [`Number.parseInt()`](number/parseint)
* [`isNaN()`](isnan)
* [`Number.prototype.toString()`](number/tostring)
* [`Object.prototype.valueOf()`](object/valueof)
* [`BigInt()`](bigint/bigint)
| programming_docs |
javascript Symbol Symbol
======
`Symbol` is a built-in object whose constructor returns a `symbol` [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) — also called a **Symbol value** or just a **Symbol** — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak [encapsulation](https://developer.mozilla.org/en-US/docs/Glossary/Encapsulation), or a weak form of [information hiding](https://en.wikipedia.org/wiki/Information_hiding).
Every `Symbol()` call is guaranteed to return a unique Symbol. Every `Symbol.for("key")` call will always return the same Symbol for a given value of `"key"`. When `Symbol.for("key")` is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.
Description
-----------
To create a new primitive Symbol, you write `Symbol()` with an optional string as its description:
```
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
```
The above code creates three new Symbols. Note that `Symbol("foo")` does not coerce the string `"foo"` into a Symbol. It creates a new Symbol each time:
```
Symbol("foo") === Symbol("foo"); // false
```
The following syntax with the [`new`](../operators/new) operator will throw a [`TypeError`](typeerror):
```
const sym = new Symbol(); // TypeError
```
This prevents authors from creating an explicit `Symbol` wrapper object instead of a new Symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, `new Boolean`, `new String` and `new Number`).
If you really want to create a `Symbol` wrapper object, you can use the `Object()` function:
```
const sym = Symbol("foo");
typeof sym; // "symbol"
const symObj = Object(sym);
typeof symObj; // "object"
```
### Shared Symbols in the global Symbol registry
The above syntax using the `Symbol()` function will create a Symbol whose value remains unique throughout the lifetime of the program. To create Symbols available across files and even across realms (each of which has its own global scope), use the methods [`Symbol.for()`](symbol/for) and [`Symbol.keyFor()`](symbol/keyfor) to set and retrieve Symbols from the global Symbol registry.
Note that the "global Symbol registry" is only a fictitious concept and may not correspond to any internal data structure in the JavaScript engine — and even if such a registry exists, its content is not available to the JavaScript code, except through the `for()` and `keyFor()` methods.
The method `Symbol.for(tokenString)` takes a string key and returns a symbol value from the registry, while `Symbol.keyFor(symbolValue)` takes a symbol value and returns the string key corresponding to it. Each is the other's inverse, so the following is `true`:
```
Symbol.keyFor(Symbol.for("tokenString")) === "tokenString"; // true
```
### Well-known Symbols
All static properties of the `Symbol` constructor are Symbols themselves, whose values are constant across realms. They are known as *well-known Symbols*, and their purpose is to serve as "protocols" for certain built-in JavaScript operations, allowing users to customize the language's behavior. For example, if a constructor function has a method with [`Symbol.hasInstance`](symbol/hasinstance) as its name, this method will encode its behavior with the [`instanceof`](../operators/instanceof) operator.
Prior to well-known Symbols, JavaScript used normal properties to implement certain built-in operations. For example, the [`JSON.stringify`](json/stringify) function will attempt to call each object's `toJSON()` method, and the [`String`](string/string) function will call the object's `toString()` and `valueOf()` methods. However, as more operations are added to the language, designating each operation a "magic property" can break backward compatibility and make the language's behavior harder to reason with. Well-known Symbols allow the customizations to be "invisible" from normal code, which typically only read string properties.
### Finding Symbol properties on objects
The method [`Object.getOwnPropertySymbols()`](object/getownpropertysymbols) returns an array of Symbols and lets you find Symbol properties on a given object. Note that every object is initialized with no own Symbol properties, so that this array will be empty unless you've set Symbol properties on the object.
Constructor
-----------
[`Symbol()`](symbol/symbol) Creates a new `Symbol` object. It is not a constructor in the traditional sense, because it can only be called as a function, instead of being constructed with `new Symbol()`.
Static properties
-----------------
The static properties are all well-known Symbols. In these Symbols' descriptions, we will use language like "`Symbol.hasInstance` is a method determining…", but bear in mind that this is referring to the semantic of an object's method having this Symbol as the method name (because well-known Symbols act as "protocols"), not describing the value of the Symbol itself.
[`Symbol.asyncIterator`](symbol/asynciterator) A method that returns the default AsyncIterator for an object. Used by [`for await...of`](../statements/for-await...of).
[`Symbol.hasInstance`](symbol/hasinstance) A method determining if a constructor object recognizes an object as its instance. Used by [`instanceof`](../operators/instanceof).
[`Symbol.isConcatSpreadable`](symbol/isconcatspreadable) A Boolean value indicating if an object should be flattened to its array elements. Used by [`Array.prototype.concat()`](array/concat).
[`Symbol.iterator`](symbol/iterator) A method returning the default iterator for an object. Used by [`for...of`](../statements/for...of).
[`Symbol.match`](symbol/match) A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by [`String.prototype.match()`](string/match).
[`Symbol.matchAll`](symbol/matchall) A method that returns an iterator, that yields matches of the regular expression against a string. Used by [`String.prototype.matchAll()`](string/matchall).
[`Symbol.replace`](symbol/replace) A method that replaces matched substrings of a string. Used by [`String.prototype.replace()`](string/replace).
[`Symbol.search`](symbol/search) A method that returns the index within a string that matches the regular expression. Used by [`String.prototype.search()`](string/search).
[`Symbol.split`](symbol/split) A method that splits a string at the indices that match a regular expression. Used by [`String.prototype.split()`](string/split).
[`Symbol.species`](symbol/species) A constructor function that is used to create derived objects.
[`Symbol.toPrimitive`](symbol/toprimitive) A method converting an object to a primitive value.
[`Symbol.toStringTag`](symbol/tostringtag) A string value used for the default description of an object. Used by [`Object.prototype.toString()`](object/tostring).
[`Symbol.unscopables`](symbol/unscopables) An object value of whose own and inherited property names are excluded from the [`with`](../statements/with) environment bindings of the associated object.
Static methods
--------------
[`Symbol.for(key)`](symbol/for) Searches for existing Symbols with the given `key` and returns it if found. Otherwise a new Symbol gets created in the global Symbol registry with `key`.
[`Symbol.keyFor(sym)`](symbol/keyfor) Retrieves a shared Symbol key from the global Symbol registry for the given Symbol.
Instance properties
-------------------
`Symbol.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Symbol"`. This property is used in [`Object.prototype.toString()`](object/tostring). However, because `Symbol` also has its own [`toString()`](symbol/tostring) method, this property is not used unless you call [`Object.prototype.toString.call()`](function/call) with a symbol as `thisArg`.
[`Symbol.prototype.description`](symbol/description) A read-only string containing the description of the Symbol.
Instance methods
----------------
[`Symbol.prototype.toString()`](symbol/tostring) Returns a string containing the description of the Symbol. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`Symbol.prototype.valueOf()`](symbol/valueof) Returns the Symbol. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
[`Symbol.prototype[@@toPrimitive]()`](symbol/@@toprimitive) Returns the Symbol.
Examples
--------
### Using the typeof operator with Symbols
The [`typeof`](../operators/typeof) operator can help you to identify Symbols.
```
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
```
### Symbol type conversions
Some things to note when working with type conversion of Symbols.
* When trying to convert a Symbol to a number, a [`TypeError`](typeerror) will be thrown (e.g. `+sym` or `sym | 0`).
* When using loose equality, `Object(sym) == sym` returns `true`.
* `Symbol("foo") + "bar"` throws a [`TypeError`](typeerror) (can't convert Symbol to string). This prevents you from silently creating a new string property name from a Symbol, for example.
* The ["safer" `String(sym)` conversion](string#string_conversion) works like a call to [`Symbol.prototype.toString()`](symbol/tostring) with Symbols, but note that `new String(sym)` will throw.
### Symbols and for...in iteration
Symbols are not enumerable in [`for...in`](../statements/for...in) iterations. In addition, [`Object.getOwnPropertyNames()`](object/getownpropertynames) will not return Symbol object properties, however, you can use [`Object.getOwnPropertySymbols()`](object/getownpropertysymbols) to get these.
```
const obj = {};
obj[Symbol("a")] = "a";
obj[Symbol.for("b")] = "b";
obj["c"] = "c";
obj.d = "d";
for (const i in obj) {
console.log(i);
}
// "c" "d"
```
### Symbols and JSON.stringify()
Symbol-keyed properties will be completely ignored when using `JSON.stringify()`:
```
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
```
For more details, see [`JSON.stringify()`](json/stringify).
### Symbol wrapper objects as property keys
When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped Symbol:
```
const sym = Symbol("foo");
const obj = { [sym]: 1 };
obj[sym]; // 1
obj[Object(sym)]; // still 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-symbol-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@toPrimitive` | 47 | 15 | 44 | No | 34 | 10 | 47 | 47 | 44 | 34 | 10 | 5.0 | 1.0 | 6.0.0 |
| `Symbol` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `Symbol` | 38 | 12
Edge 12 included Symbol properties in `JSON.stringify()` output. | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `asyncIterator` | 63 | 79 | 57 | No | 50 | 11.1 | 63 | 63 | 57 | 46 | 11.3 | 8.0 | 1.0 | 10.0.0 |
| `description` | 70 | 79 | 63 | No | 57 | 12.1
12
No support for an undefined description. | 70 | 70 | 63 | 49 | 12.2
12
No support for an undefined description. | 10.0 | 1.0 | 11.0.0 |
| `for` | 40 | 12 | 36 | No | 27 | 9 | 40 | 40 | 36 | 27 | 9 | 4.0 | 1.0 | 0.12.0 |
| `hasInstance` | 50 | 15 | 50 | No | 37 | 10 | 50 | 50 | 50 | 37 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `isConcatSpreadable` | 48 | 15 | 48 | No | 35 | 10 | 48 | 48 | 48 | 35 | 10 | 5.0 | 1.0 | 6.0.0 |
| `iterator` | 43 | 12 | 36 | No | 30 | 10 | 43 | 43 | 36 | 30 | 10 | 4.0 | 1.0 | 0.12.0 |
| `keyFor` | 40 | 12 | 36 | No | 27 | 9 | 40 | 40 | 36 | 27 | 9 | 4.0 | 1.0 | 0.12.0 |
| `match` | 50 | 79 | 40 | No | 37 | 10 | 50 | 50 | 40 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `matchAll` | 73 | 79 | 67 | No | 60 | 13 | 73 | 73 | 67 | 52 | 13 | 11.0 | 1.0 | 12.0.0 |
| `replace` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `search` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `species` | 51 | 13 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `split` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `toPrimitive` | 47 | 15 | 44 | No | 34 | 10 | 47 | 47 | 44 | 34 | 10 | 5.0 | 1.0 | 6.0.0 |
| `toString` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `toStringTag` | 49 | 15 | 51 | No | 36 | 10 | 49 | 49 | 51 | 36 | 10 | 5.0 | 1.0 | 6.0.0
4.0.0 |
| `unscopables` | 38 | 12 | 48 | No | 25 | 9 | 38 | 38 | 48 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `valueOf` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Symbol` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
* [`typeof`](../operators/typeof)
* [Data types and data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
* ["ES6 In Depth: Symbols" on hacks.mozilla.org](https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/)
javascript BigUint64Array BigUint64Array
==============
The `BigUint64Array` typed array represents an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`BigUint64Array()`](biguint64array/biguint64array) Creates a new `BigUint64Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`BigUint64Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of `BigUint64Array`.
[`BigUint64Array.name`](typedarray/name) Returns the string value of the constructor name. `"BigUint64Array"` in the case of `BigUint64Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`BigUint64Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of a `BigUint64Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a `BigUint64Array`
```
// From a length
const biguint64 = new BigUint64Array(2);
biguint64[0] = 42n;
console.log(biguint64[0]); // 42n
console.log(biguint64.length); // 2
console.log(biguint64.BYTES\_PER\_ELEMENT); // 8
// From an array
const x = new BigUint64Array([21n, 31n]);
console.log(x[1]); // 31n
// From another TypedArray
const y = new BigUint64Array(x);
console.log(y[0]); // 21n
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigUint64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = function\*() { yield\* [1n, 2n, 3n]; }();
const biguint64FromIterable = new BigUint64Array(iterable);
console.log(biguint64FromIterable);
// BigUint64Array [1n, 2n, 3n]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray-objects](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `BigUint64Array` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `BigUint64Array` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`BigInt64Array`](bigint64array)
* [`DataView`](dataview)
javascript ReferenceError ReferenceError
==============
The `ReferenceError` object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.
`ReferenceError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`ReferenceError()`](referenceerror/referenceerror) Creates a new `ReferenceError` object.
Instance properties
-------------------
[`ReferenceError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`ReferenceError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`ReferenceError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`ReferenceError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`ReferenceError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`ReferenceError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`ReferenceError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Catching a ReferenceError
```
try {
let a = undefinedVariable
} catch (e) {
console.log(e instanceof ReferenceError) // true
console.log(e.message) // "undefinedVariable is not defined"
console.log(e.name) // "ReferenceError"
console.log(e.fileName) // "Scratchpad/1"
console.log(e.lineNumber) // 2
console.log(e.columnNumber) // 6
console.log(e.stack) // "@Scratchpad/2:2:7\n"
}
```
### Creating a ReferenceError
```
try {
throw new ReferenceError('Hello', 'someFile.js', 10)
} catch (e) {
console.log(e instanceof ReferenceError) // true
console.log(e.message) // "Hello"
console.log(e.name) // "ReferenceError"
console.log(e.fileName) // "someFile.js"
console.log(e.lineNumber) // 10
console.log(e.columnNumber) // 0
console.log(e.stack) // "@Scratchpad/2:2:9\n"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-referenceerror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-referenceerror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ReferenceError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `ReferenceError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
| programming_docs |
javascript TypeError TypeError
=========
The `TypeError` object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
A `TypeError` may be thrown when:
* an operand or argument passed to a function is incompatible with the type expected by that operator or function; or
* when attempting to modify a value that cannot be changed; or
* when attempting to use a value in an inappropriate way.
`TypeError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`TypeError()`](typeerror/typeerror) Creates a new `TypeError` object.
Instance properties
-------------------
[`TypeError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`TypeError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`TypeError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`TypeError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`TypeError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`TypeError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`TypeError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Catching a TypeError
```
try {
null.f()
} catch (e) {
console.log(e instanceof TypeError) // true
console.log(e.message) // "null has no properties"
console.log(e.name) // "TypeError"
console.log(e.fileName) // "Scratchpad/1"
console.log(e.lineNumber) // 2
console.log(e.columnNumber) // 2
console.log(e.stack) // "@Scratchpad/2:2:3\n"
}
```
### Creating a TypeError
```
try {
throw new TypeError('Hello', "someFile.js", 10)
} catch (e) {
console.log(e instanceof TypeError) // true
console.log(e.message) // "Hello"
console.log(e.name) // "TypeError"
console.log(e.fileName) // "someFile.js"
console.log(e.lineNumber) // 10
console.log(e.columnNumber) // 0
console.log(e.stack) // "@Scratchpad/2:2:9\n"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-typeerror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-typeerror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `TypeError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `TypeError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
javascript Array Array
=====
The `Array` object, as with arrays in other programming languages, enables [storing a collection of multiple items under a single variable name](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays), and has members for [performing common array operations](#examples).
Description
-----------
In JavaScript, arrays aren't [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) but are instead `Array` objects with the following core characteristics:
* **JavaScript arrays are resizable** and **can contain a mix of different [data types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)**. (When those characteristics are undesirable, use [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) instead.)
* **JavaScript arrays are not associative arrays** and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
* **JavaScript arrays are [zero-indexed](https://en.wikipedia.org/wiki/Zero-based_numbering)**: the first element of an array is at index `0`, the second is at index `1`, and so on — and the last element is at the value of the array's [`length`](array/length) property minus `1`.
* **JavaScript [array-copy operations](#copy_an_array) create [shallow copies](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy)**. (All standard built-in copy operations with *any* JavaScript objects create shallow copies, rather than [deep copies](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy)).
### Array indices
`Array` objects cannot use arbitrary strings as element indexes (as in an [associative array](https://en.wikipedia.org/wiki/Associative_array)) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's [object property collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties). The array's object properties and list of array elements are separate, and the array's [traversal and mutation operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#array_methods) cannot be applied to these named properties.
Array elements are object properties in the same way that `toString` is a property (to be specific, however, `toString()` is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:
```
console.log(arr.0); // a syntax error
```
JavaScript syntax requires properties beginning with a digit to be accessed using [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#objects_and_properties) instead of [dot notation](../operators/property_accessors). It's also possible to quote the array indices (e.g., `years['2']` instead of `years[2]`), although usually not necessary.
The `2` in `years[2]` is coerced into a string by the JavaScript engine through an implicit `toString` conversion. As a result, `'2'` and `'02'` would refer to two different slots on the `years` object, and the following example could be `true`:
```
console.log(years["2"] !== years["02"]);
```
Only `years['2']` is an actual array index. `years['02']` is an arbitrary string property that will not be visited in array iteration.
### Relationship between length and numerical properties
A JavaScript array's [`length`](array/length) property and numerical properties are connected.
Several of the built-in array methods (e.g., [`join()`](array/join), [`slice()`](array/slice), [`indexOf()`](array/indexof), etc.) take into account the value of an array's [`length`](array/length) property when they're called.
Other methods (e.g., [`push()`](array/push), [`splice()`](array/splice), etc.) also result in updates to an array's [`length`](array/length) property.
```
const fruits = [];
fruits.push("banana", "apple", "peach");
console.log(fruits.length); // 3
```
When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's [`length`](array/length) property accordingly:
```
fruits[5] = "mango";
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 6
```
Increasing the [`length`](array/length).
```
fruits.length = 10;
console.log(fruits); // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4]
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10
console.log(fruits[8]); // undefined
```
Decreasing the [`length`](array/length) property does, however, delete elements.
```
fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2
```
This is explained further on the [`Array/length`](array/length) page.
### Array methods and empty slots
Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave inconsistently between array methods. Generally, the older methods will skip empty slots, while newer ones treat them as `undefined`.
Among methods that iterate through multiple elements, the following do an [`in`](../operators/in) check before accessing the index and do not conflate empty slots with `undefined`:
* [`concat()`](array/concat)
* [`copyWithin()`](array/copywithin)
* [`every()`](array/every)
* [`filter()`](array/filter)
* [`flat()`](array/flat)
* [`flatMap()`](array/flatmap)
* [`forEach()`](array/foreach)
* [`indexOf()`](array/indexof)
* [`lastIndexOf()`](array/lastindexof)
* [`map()`](array/map)
* [`reduce()`](array/reduce)
* [`reduceRight()`](array/reduceright)
* [`reverse()`](array/reverse)
* [`slice()`](array/slice)
* [`some()`](array/some)
* [`sort()`](array/sort)
* [`splice()`](array/splice)
For exactly how they treat empty slots, see the page for each method.
These methods treat empty slots as if they are `undefined`:
* [`entries()`](array/entries)
* [`fill()`](array/fill)
* [`find()`](array/find)
* [`findIndex()`](array/findindex)
* [`findLast()`](array/findlast)
* [`findLastIndex()`](array/findlastindex)
* [`group()`](array/group) Experimental
* [`groupToMap()`](array/grouptomap) Experimental
* [`includes()`](array/includes)
* [`join()`](array/join)
* [`keys()`](array/keys)
* [`toLocaleString()`](array/tolocalestring)
* [`values()`](array/values)
### Copying methods and mutating methods
Some methods do not mutate the existing array that the method was called on, but instead return a new array. They do so by first accessing [`this.constructor[Symbol.species]`](array/@@species) to determine the constructor to use for the new array. The newly constructed array is then populated with elements. The copy always happens [*shallowly*](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) — the method never copies anything beyond the initially created array. Elements of the original array(s) are copied into the new array as follows:
* Objects: the object reference is copied into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
* Primitive types such as strings, numbers and booleans (not [`String`](string), [`Number`](number), and [`Boolean`](boolean) objects): their values are copied into the new array.
Other methods mutate the array that the method was called on, in which case their return value differs depending on the method: sometimes a reference to the same array, sometimes the length of the new array.
The following methods create new arrays with `@@species`:
* [`concat()`](array/concat)
* [`filter()`](array/filter)
* [`flat()`](array/flat)
* [`flatMap()`](array/flatmap)
* [`map()`](array/map)
* [`slice()`](array/slice)
* [`splice()`](array/splice) (to construct the array of removed elements that's returned)
Note that [`group()`](array/group) and [`groupToMap()`](array/grouptomap) do not use `@@species` to create new arrays for each group entry, but always use the plain `Array` constructor. Conceptually, they are not copying methods either.
The following methods mutate the original array:
* [`copyWithin()`](array/copywithin)
* [`fill()`](array/fill)
* [`pop()`](array/pop)
* [`push()`](array/push)
* [`reverse()`](array/reverse)
* [`shift()`](array/shift)
* [`sort()`](array/sort)
* [`splice()`](array/splice)
* [`unshift()`](array/unshift)
### Iterative methods
Many array methods take a callback function as an argument. The callback function is called sequentially and at most once for each element in the array, and the return value of the callback function is used to determine the return value of the method. They all share the same signature:
```
method(callbackFn, thisArg)
```
Where `callbackFn` takes three arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array that the method was called upon.
What `callbackFn` is expected to return depends on the array method that was called.
The `thisArg` argument (defaults to `undefined`) will be used as the `this` value when calling `callbackFn`. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules](../operators/this): if `callbackFn` is [non-strict](../strict_mode#no_this_substitution), primitive `this` values are wrapped into objects, and `undefined`/`null` is substituted with [`globalThis`](globalthis). The `thisArg` argument is irrelevant for any `callbackFn` defined with an [arrow function](../functions/arrow_functions), as arrow functions don't have their own `this` binding.
All iterative methods are [copying](#copying_methods_and_mutating_methods) and [generic](#generic_array_methods), although they behave differently with [empty slots](#array_methods_and_empty_slots).
The following methods are iterative:
* [`every()`](array/every)
* [`filter()`](array/filter)
* [`find()`](array/find)
* [`findIndex()`](array/findindex)
* [`findLast()`](array/findlast)
* [`findLastIndex()`](array/findlastindex)
* [`flatMap()`](array/flatmap)
* [`forEach()`](array/foreach)
* [`group()`](array/group)
* [`groupToMap()`](array/grouptomap)
* [`map()`](array/map)
* [`some()`](array/some)
In particular, [`every()`](array/every), [`find()`](array/find), [`findIndex()`](array/findindex), [`findLast()`](array/findlast), [`findLastIndex()`](array/findlastindex), and [`some()`](array/some) do not always invoke `callbackFn` on every element — they stop iteration as soon as the return value is determined.
There are two other methods that take a callback function and run it at most once for each element in the array, but they have slightly different signatures from typical iterative methods (for example, they don't accept `thisArg`):
* [`reduce()`](array/reduce)
* [`reduceRight()`](array/reduceright)
The [`sort()`](array/sort) method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't accept `thisArg`, and may invoke the callback multiple times on an index.
### Generic array methods
Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the `length` property and the indexed elements. This means that they can be called on array-like objects as well.
```
const arrayLike = {
0: "a",
1: "b",
length: 2,
};
console.log(Array.prototype.join.call(arrayLike, "+")); // 'a+b'
```
#### Normalization of the length property
The `length` property is [converted to an integer](number#integer_conversion) and then clamped to the range between 0 and 253 - 1. `NaN` becomes `0`, so even when `length` is not present or is `undefined`, it behaves as if it has value `0`.
```
Array.prototype.flat.call({}); // []
```
Some array methods set the `length` property of the array object. They always set the value after normalization, so `length` always ends as an integer.
```
const a = { length: 0.7 };
Array.prototype.push.call(a);
console.log(a.length); // 0
```
#### Array-like objects
The term [*array-like object*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) refers to any object that doesn't throw during the `length` conversion process described above. In practice, such object is expected to actually have a `length` property and to have indexed elements in the range `0` to `length - 1`. (If it doesn't have all indices, it will be functionally equivalent to a [sparse array](#array_methods_and_empty_slots).)
Many DOM objects are array-like — for example, [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) and [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection). The [`arguments`](../functions/arguments) object is also array-like. You can call array methods on them even if they don't have these methods themselves.
```
function f() {
console.log(Array.prototype.join.call(arguments, "+"));
}
f("a", "b"); // 'a+b'
```
Constructor
-----------
[`Array()`](array/array) Creates a new `Array` object.
Static properties
-----------------
[`get Array[@@species]`](array/@@species) Returns the `Array` constructor.
Static methods
--------------
[`Array.from()`](array/from) Creates a new `Array` instance from an array-like object or iterable object.
[`Array.isArray()`](array/isarray) Returns `true` if the argument is an array, or `false` otherwise.
[`Array.of()`](array/of) Creates a new `Array` instance with a variable number of arguments, regardless of number or type of the arguments.
Instance properties
-------------------
[`Array.prototype.length`](array/length) Reflects the number of elements in an array.
[`Array.prototype[@@unscopables]`](array/@@unscopables) Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](../statements/with) statement-binding purposes.
Instance methods
----------------
[`Array.prototype.at()`](array/at) Returns the array item at the given index. Accepts negative integers, which count back from the last item.
[`Array.prototype.concat()`](array/concat) Returns a new array that is the calling array joined with other array(s) and/or value(s).
[`Array.prototype.copyWithin()`](array/copywithin) Copies a sequence of array elements within an array.
[`Array.prototype.entries()`](array/entries) Returns a new [*array iterator*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the key/value pairs for each index in an array.
[`Array.prototype.every()`](array/every) Returns `true` if every element in the calling array satisfies the testing function.
[`Array.prototype.fill()`](array/fill) Fills all the elements of an array from a start index to an end index with a static value.
[`Array.prototype.filter()`](array/filter) Returns a new array containing all elements of the calling array for which the provided filtering function returns `true`.
[`Array.prototype.find()`](array/find) Returns the value of the first element in the array that satisfies the provided testing function, or `undefined` if no appropriate element is found.
[`Array.prototype.findIndex()`](array/findindex) Returns the index of the first element in the array that satisfies the provided testing function, or `-1` if no appropriate element was found.
[`Array.prototype.findLast()`](array/findlast) Returns the value of the last element in the array that satisfies the provided testing function, or `undefined` if no appropriate element is found.
[`Array.prototype.findLastIndex()`](array/findlastindex) Returns the index of the last element in the array that satisfies the provided testing function, or `-1` if no appropriate element was found.
[`Array.prototype.flat()`](array/flat) Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
[`Array.prototype.flatMap()`](array/flatmap) Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
[`Array.prototype.forEach()`](array/foreach) Calls a function for each element in the calling array.
[`Array.prototype.group()`](array/group) Experimental
Groups the elements of an array into an object according to the strings returned by a test function.
[`Array.prototype.groupToMap()`](array/grouptomap) Experimental
Groups the elements of an array into a [`Map`](map) according to values returned by a test function.
[`Array.prototype.includes()`](array/includes) Determines whether the calling array contains a value, returning `true` or `false` as appropriate.
[`Array.prototype.indexOf()`](array/indexof) Returns the first (least) index at which a given element can be found in the calling array.
[`Array.prototype.join()`](array/join) Joins all elements of an array into a string.
[`Array.prototype.keys()`](array/keys) Returns a new [*array iterator*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) that contains the keys for each index in the calling array.
[`Array.prototype.lastIndexOf()`](array/lastindexof) Returns the last (greatest) index at which a given element can be found in the calling array, or `-1` if none is found.
[`Array.prototype.map()`](array/map) Returns a new array containing the results of invoking a function on every element in the calling array.
[`Array.prototype.pop()`](array/pop) Removes the last element from an array and returns that element.
[`Array.prototype.push()`](array/push) Adds one or more elements to the end of an array, and returns the new `length` of the array.
[`Array.prototype.reduce()`](array/reduce) Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.
[`Array.prototype.reduceRight()`](array/reduceright) Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.
[`Array.prototype.reverse()`](array/reverse) Reverses the order of the elements of an array *in place*. (First becomes the last, last becomes first.)
[`Array.prototype.shift()`](array/shift) Removes the first element from an array and returns that element.
[`Array.prototype.slice()`](array/slice) Extracts a section of the calling array and returns a new array.
[`Array.prototype.some()`](array/some) Returns `true` if at least one element in the calling array satisfies the provided testing function.
[`Array.prototype.sort()`](array/sort) Sorts the elements of an array in place and returns the array.
[`Array.prototype.splice()`](array/splice) Adds and/or removes elements from an array.
[`Array.prototype.toLocaleString()`](array/tolocalestring) Returns a localized string representing the calling array and its elements. Overrides the [`Object.prototype.toLocaleString()`](object/tolocalestring) method.
[`Array.prototype.toString()`](array/tostring) Returns a string representing the calling array and its elements. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`Array.prototype.unshift()`](array/unshift) Adds one or more elements to the front of an array, and returns the new `length` of the array.
[`Array.prototype.values()`](array/values) Returns a new [*array iterator*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) object that contains the values for each index in the array.
[`Array.prototype[@@iterator]()`](array/@@iterator) An alias for the [`values()`](array/values) method by default.
Examples
--------
This section provides some examples of common array operations in JavaScript.
**Note:** If you're not yet familiar with array basics, consider first reading [JavaScript First Steps: Arrays](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays), which [explains what arrays are](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays#what_is_an_array), and includes other examples of common array operations.
### Create an array
This example shows three ways to create new array: first using [array literal notation](array/array#array_literal_notation), then using the [`Array()`](array/array) constructor, and finally using [`String.prototype.split()`](string/split) to build the array from a string.
```
// 'fruits' array created using array literal notation.
const fruits = ["Apple", "Banana"];
console.log(fruits.length);
// 2
// 'fruits2' array created using the Array() constructor.
const fruits2 = new Array("Apple", "Banana");
console.log(fruits2.length);
// 2
// 'fruits3' array created using String.prototype.split().
const fruits3 = "Apple, Banana".split(", ");
console.log(fruits3.length);
// 2
```
### Create a string from an array
This example uses the [`join()`](array/join) method to create a string from the `fruits` array.
```
const fruits = ["Apple", "Banana"];
const fruitsString = fruits.join(", ");
console.log(fruitsString);
// "Apple, Banana"
```
### Access an array item by its index
This example shows how to access items in the `fruits` array by specifying the index number of their position in the array.
```
const fruits = ["Apple", "Banana"];
// The index of an array's first element is always 0.
fruits[0]; // Apple
// The index of an array's second element is always 1.
fruits[1]; // Banana
// The index of an array's last element is always one
// less than the length of the array.
fruits[fruits.length - 1]; // Banana
// Using an index number larger than the array's length
// returns 'undefined'.
fruits[99]; // undefined
```
### Find the index of an item in an array
This example uses the [`indexOf()`](array/indexof) method to find the position (index) of the string `"Banana"` in the `fruits` array.
```
const fruits = ["Apple", "Banana"];
console.log(fruits.indexOf("Banana"));
// 1
```
### Check if an array contains a certain item
This example shows two ways to check if the `fruits` array contains `"Banana"` and `"Cherry"`: first with the [`includes()`](array/includes) method, and then with the [`indexOf()`](array/indexof) method to test for an index value that's not `-1`.
```
const fruits = ["Apple", "Banana"];
fruits.includes("Banana"); // true
fruits.includes("Cherry"); // false
// If indexOf() doesn't return -1, the array contains the given item.
fruits.indexOf("Banana") !== -1; // true
fruits.indexOf("Cherry") !== -1; // false
```
### Append an item to an array
This example uses the [`push()`](array/push) method to append a new string to the `fruits` array.
```
const fruits = ["Apple", "Banana"];
const newLength = fruits.push("Orange");
console.log(fruits);
// ["Apple", "Banana", "Orange"]
console.log(newLength);
// 3
```
### Remove the last item from an array
This example uses the [`pop()`](array/pop) method to remove the last item from the `fruits` array.
```
const fruits = ["Apple", "Banana", "Orange"];
const removedItem = fruits.pop();
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItem);
// Orange
```
**Note:** `pop()` can only be used to remove the last item from an array. To remove multiple items from the end of an array, see the next example.
### Remove multiple items from the end of an array
This example uses the [`splice()`](array/splice) method to remove the last 3 items from the `fruits` array.
```
const fruits = ["Apple", "Banana", "Strawberry", "Mango", "Cherry"];
const start = -3;
const removedItems = fruits.splice(start);
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItems);
// ["Strawberry", "Mango", "Cherry"]
```
### Truncate an array down to just its first N items
This example uses the [`splice()`](array/splice) method to truncate the `fruits` array down to just its first 2 items.
```
const fruits = ["Apple", "Banana", "Strawberry", "Mango", "Cherry"];
const start = 2;
const removedItems = fruits.splice(start);
console.log(fruits);
// ["Apple", "Banana"]
console.log(removedItems);
// ["Strawberry", "Mango", "Cherry"]
```
### Remove the first item from an array
This example uses the [`shift()`](array/shift) method to remove the first item from the `fruits` array.
```
const fruits = ["Apple", "Banana"];
const removedItem = fruits.shift();
console.log(fruits);
// ["Banana"]
console.log(removedItem);
// Apple
```
**Note:** `shift()` can only be used to remove the first item from an array. To remove multiple items from the beginning of an array, see the next example.
### Remove multiple items from the beginning of an array
This example uses the [`splice()`](array/splice) method to remove the first 3 items from the `fruits` array.
```
const fruits = ["Apple", "Strawberry", "Cherry", "Banana", "Mango"];
const start = 0;
const deleteCount = 3;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Banana", "Mango"]
console.log(removedItems);
// ["Apple", "Strawberry", "Cherry"]
```
### Add a new first item to an array
This example uses the [`unshift()`](array/unshift) method to add, at index `0`, a new item to the `fruits` array — making it the new first item in the array.
```
const fruits = ["Banana", "Mango"];
const newLength = fruits.unshift("Strawberry");
console.log(fruits);
// ["Strawberry", "Banana", "Mango"]
console.log(newLength);
// 3
```
### Remove a single item by index
This example uses the [`splice()`](array/splice) method to remove the string `"Banana"` from the `fruits` array — by specifying the index position of `"Banana"`.
```
const fruits = ["Strawberry", "Banana", "Mango"];
const start = fruits.indexOf("Banana");
const deleteCount = 1;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Strawberry", "Mango"]
console.log(removedItems);
// ["Banana"]
```
### Remove multiple items by index
This example uses the [`splice()`](array/splice) method to remove the strings `"Banana"` and `"Strawberry"` from the `fruits` array — by specifying the index position of `"Banana"`, along with a count of the number of total items to remove.
```
const fruits = ["Apple", "Banana", "Strawberry", "Mango"];
const start = 1;
const deleteCount = 2;
const removedItems = fruits.splice(start, deleteCount);
console.log(fruits);
// ["Apple", "Mango"]
console.log(removedItems);
// ["Banana", "Strawberry"]
```
### Replace multiple items in an array
This example uses the [`splice()`](array/splice) method to replace the last 2 items in the `fruits` array with new items.
```
const fruits = ["Apple", "Banana", "Strawberry"];
const start = -2;
const deleteCount = 2;
const removedItems = fruits.splice(start, deleteCount, "Mango", "Cherry");
console.log(fruits);
// ["Apple", "Mango", "Cherry"]
console.log(removedItems);
// ["Banana", "Strawberry"]
```
### Iterate over an array
This example uses a [`for...of`](../statements/for...of) loop to iterate over the `fruits` array, logging each item to the console.
```
const fruits = ["Apple", "Mango", "Cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// Apple
// Mango
// Cherry
```
But `for...of` is just one of many ways to iterate over any array; for more ways, see [Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration), and see the documentation for the [`every()`](array/every), [`filter()`](array/filter), [`flatMap()`](array/flatmap), [`map()`](array/map), [`reduce()`](array/reduce), and [`reduceRight()`](array/reduceright) methods — and see the next example, which uses the [`forEach()`](array/foreach) method.
### Call a function on each element in an array
This example uses the [`forEach()`](array/foreach) method to call a function on each element in the `fruits` array; the function causes each item to be logged to the console, along with the item's index number.
```
const fruits = ["Apple", "Mango", "Cherry"];
fruits.forEach((item, index, array) => {
console.log(item, index);
});
// Apple 0
// Mango 1
// Cherry 2
```
### Merge multiple arrays together
This example uses the [`concat()`](array/concat) method to merge the `fruits` array with a `moreFruits` array, to produce a new `combinedFruits` array. Notice that `fruits` and `moreFruits` remain unchanged.
```
const fruits = ["Apple", "Banana", "Strawberry"];
const moreFruits = ["Mango", "Cherry"];
const combinedFruits = fruits.concat(moreFruits);
console.log(combinedFruits);
// ["Apple", "Banana", "Strawberry", "Mango", "Cherry"]
// The 'fruits' array remains unchanged.
console.log(fruits);
// ["Apple", "Banana", "Strawberry"]
// The 'moreFruits' array also remains unchanged.
console.log(moreFruits);
// ["Mango", "Cherry"]
```
### Copy an array
This example shows three ways to create a new array from the existing `fruits` array: first by using [spread syntax](../operators/spread_syntax), then by using the [`from()`](array/from) method, and then by using the [`slice()`](array/slice) method.
```
const fruits = ["Strawberry", "Mango"];
// Create a copy using spread syntax.
const fruitsCopy = [...fruits];
// ["Strawberry", "Mango"]
// Create a copy using the from() method.
const fruitsCopy2 = Array.from(fruits);
// ["Strawberry", "Mango"]
// Create a copy using the slice() method.
const fruitsCopy3 = fruits.slice();
// ["Strawberry", "Mango"]
```
All built-in array-copy operations ([spread syntax](../operators/spread_syntax), [`Array.from()`](array/from), [`Array.prototype.slice()`](array/slice), and [`Array.prototype.concat()`](array/concat)) create [shallow copies](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy). If you instead want a [deep copy](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy) of an array, you can use [`JSON.stringify()`](json/stringify) to convert the array to a JSON string, and then [`JSON.parse()`](json/parse) to convert the string back into a new array that's completely independent from the original array.
```
const fruitsDeepCopy = JSON.parse(JSON.stringify(fruits));
```
You can also create deep copies using the [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) method, which has the advantage of allowing [transferable objects](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in the source to be *transferred* to the new copy, rather than just cloned.
Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, or alias, to the original array; that is, the original array's name and the new variable name are just two names for the exact same object (and so will always evaluate as [strictly equivalent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using)). Therefore, if you make any changes at all either to the value of the original array or to the value of the new variable, the other will change, too:
```
const fruits = ["Strawberry", "Mango"];
const fruitsAlias = fruits;
// 'fruits' and 'fruitsAlias' are the same object, strictly equivalent.
fruits === fruitsAlias; // true
// Any changes to the 'fruits' array change 'fruitsAlias' too.
fruits.unshift("Apple", "Banana");
console.log(fruits);
// ['Apple', 'Banana', 'Strawberry', 'Mango']
console.log(fruitsAlias);
// ['Apple', 'Banana', 'Strawberry', 'Mango']
```
### Grouping the elements of an array
The [`Array.prototype.group()`](array/group) methods 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`.
```
const inventory = [
{ name: "asparagus", type: "vegetables" },
{ name: "bananas", type: "fruit" },
{ name: "goat", type: "meat" },
{ name: "cherries", type: "fruit" },
{ name: "fish", type: "meat" },
];
```
To use `group()`, 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](../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.
```
const result = inventory.group(({ type }) => type);
console.log(result.vegetables);
// [{ name: "asparagus", type: "vegetables" }]
```
Note that the returned object references the *same* elements as the original array (not [deep copies](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy)). 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 [`Array.prototype.groupToMap()`](array/grouptomap). This is very similar to `group` except that it groups the elements of the array into a [`Map`](map) that can use an arbitrary value ([object](https://developer.mozilla.org/en-US/docs/Glossary/Object) or [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)) as a key.
### Creating a two-dimensional array
The following creates a chessboard as a two-dimensional array of strings. The first move is made by copying the `'p'` in `board[6][4]` to `board[4][4]`. The old position at `[6][4]` is made blank.
```
const board = [
["R", "N", "B", "Q", "K", "B", "N", "R"],
["P", "P", "P", "P", "P", "P", "P", "P"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
["p", "p", "p", "p", "p", "p", "p", "p"],
["r", "n", "b", "q", "k", "b", "n", "r"],
];
console.log(`${board.join("\n")}\n\n`);
// Move King's Pawn forward 2
board[4][4] = board[6][4];
board[6][4] = " ";
console.log(board.join("\n"));
```
Here is the output:
```
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , , , , ,
, , , , , , ,
p,p,p,p,p,p,p,p
r,n,b,q,k,b,n,r
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , ,p, , ,
, , , , , , ,
p,p,p,p, ,p,p,p
r,n,b,q,k,b,n,r
```
### Using an array to tabulate a set of values
```
const values = [];
for (let x = 0; x < 10; x++) {
values.push([2 \*\* x, 2 \* x \*\* 2]);
}
console.table(values);
```
Results in
```
// The first column is the index
0 1 0
1 2 2
2 4 8
3 8 18
4 16 32
5 32 50
6 64 72
7 128 98
8 256 128
9 512 162
```
### Creating an array using the result of a match
The result of a match between a [`RegExp`](regexp) and a string can create a JavaScript array that has properties and elements which provide information about the match. Such an array is returned by [`RegExp.prototype.exec()`](regexp/exec) and [`String.prototype.match()`](string/match).
For example:
```
// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case
const myRe = /d(b+)(d)/i;
const execResult = myRe.exec("cdbBdbsbz");
console.log(execResult.input); // 'cdbBdbsbz'
console.log(execResult.index); // 1
console.log(execResult); // [ "dbBd", "bB", "d" ]
```
For more information about the result of a match, see the [`RegExp.prototype.exec()`](regexp/exec) and [`String.prototype.match()`](string/match) pages.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array-objects](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 10 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
| `@@species` | 51 | 79 | 48 | No | 38 | 10 | 51 | 51 | 48 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `@@unscopables` | 38 | 12 | 48 | No | 25 | 10 | 38 | 38 | 48 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
| `Array` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Array` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `at` | 92 | 92 | 90 | No | 78 | 15.4 | 92 | 92 | 90 | 65 | 15.4 | 16.0 | 1.12 | 16.6.0 |
| `concat` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `copyWithin` | 45 | 12 | 32 | No | 32 | 9 | 45 | 45 | 32 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
| `entries` | 38 | 12 | 28 | No | 25 | 8 | 38 | 38 | 28 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `every` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fill` | 45 | 12 | 31 | No | 32 | 8 | 45 | 45 | 31 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
| `filter` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `find` | 45 | 12 | 25 | No | 32 | 8 | 45 | 45 | 4 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
| `findIndex` | 45 | 12 | 25 | No | 32 | 8 | 45 | 45 | 4 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
| `findLast` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | 18.0.0 |
| `findLastIndex` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | 18.0.0 |
| `flat` | 69 | 79 | 62 | No | 56 | 12 | 69 | 69 | 62 | 48 | 12 | 10.0 | 1.0 | 11.0.0 |
| `flatMap` | 69 | 79 | 62 | No | 56 | 12 | 69 | 69 | 62 | 48 | 12 | 10.0 | 1.0 | 11.0.0 |
| `forEach` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `from` | 45 | 12 | 32 | No | 32 | 9 | 45 | 45 | 32 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
| `group` | No | No | 98 | No | No | No | No | No | No | No | No | No | No | No |
| `groupToMap` | No | No | 98 | No | No | No | No | No | No | No | No | No | No | No |
| `includes` | 47 | 14 | 43 | No | 34 | 9 | 47 | 47 | 43 | 34 | 9 | 5.0 | 1.0 | 6.0.0
5.0.0 |
| `indexOf` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `isArray` | 4 | 12 | 4 | 9 | 10.5 | 5 | 4.4 | 18 | 4 | 14 | 5 | 1.0 | 1.0 | 0.10.0 |
| `join` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `keys` | 38 | 12 | 28 | No | 25 | 8 | 38 | 38 | 28 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `lastIndexOf` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `length` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `map` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `of` | 45 | 12 | 25 | No | 26 | 9 | 39 | 39 | 25 | 26 | 9 | 4.0 | 1.0 | 4.0.0 |
| `pop` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `push` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `reduce` | 3 | 12 | 3 | 9 | 10.5 | 4 | ≤37 | 18 | 4 | 14 | 3.2 | 1.0 | 1.0 | 0.10.0 |
| `reduceRight` | 3 | 12 | 3 | 9 | 10.5 | 4 | ≤37 | 18 | 4 | 14 | 3.2 | 1.0 | 1.0 | 0.10.0 |
| `reverse` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `shift` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `slice` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `some` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sort` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `splice` | 1 | 12 | 1 | 5.5
From Internet Explorer 5.5 through 8, all elements of the array will not be deleted if `deleteCount` is omitted. This behavior was fixed in Internet Explorer 9. | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleString` | 1 | 12 | 1 | 5.5 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `unshift` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `values` | 66 | 14 | 60 | No | 53 | 9 | 66 | 66 | 60 | 47 | 9 | 9.0 | 1.0 | 10.9.0
6.5.0
The `--harmony-array-prototype-values` flag is required; the `--harmony` flag is not sufficient in this case.
0.12.0-4.0.0 |
See also
--------
* From the JavaScript Guide:
+ [Accessing properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#accessing_properties)
+ [Indexed collections](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections)
* [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [RangeError: invalid array length](../errors/invalid_array_length)
| programming_docs |
javascript RegExp RegExp
======
The `RegExp` object is used for matching text with a pattern.
For an introduction to regular expressions, read the [Regular Expressions chapter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
Description
-----------
### Literal notation and constructor
There are two ways to create a `RegExp` object: a *literal notation* and a *constructor*.
* The *literal notation* takes a pattern between two slashes, followed by optional flags, after the second slash.
* The *constructor function* takes either a string or a `RegExp` object as its first parameter and a string of optional flags as its second parameter.
The following three expressions create the same regular expression object:
```
const re = /ab+c/i; // literal notation
// OR
const re = new RegExp('ab+c', 'i'); // constructor with string pattern as first argument
// OR
const re = new RegExp(/ab+c/, 'i'); // constructor with regular expression literal as first argument
```
Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. More about the process can be found in [dotnet docs](https://docs.microsoft.com/dotnet/standard/base-types/compilation-and-reuse-in-regular-expressions).
The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the `RegExp` object, `new RegExp('ab+c')`, results in runtime compilation of the regular expression.
Use a string as the first argument to the `RegExp()` constructor when you want to [build the regular expression from dynamic input](#building_a_regular_expression_from_dynamic_inputs).
### Flags in constructor
The expression `new RegExp(/ab+c/, flags)` will create a new `RegExp` using the source of the first parameter and the flags provided by the second.
When using the constructor function, the normal string escape rules (preceding special characters with `\` when included in a string) are necessary.
For example, the following are equivalent:
```
const re = /\w+/;
// OR
const re = new RegExp('\\w+');
```
### Special handling for regexes
**Note:** Whether something is a "regex" can be [duck-typed](https://en.wikipedia.org/wiki/Duck_typing). It doesn't have to be a `RegExp`!
Some built-in methods would treat regexes specially. They decide whether `x` is a regex through [multiple steps](https://tc39.es/ecma262/#sec-isregexp):
1. `x` must be an object (not a primitive).
2. If [`x[Symbol.match]`](symbol/match) is not `undefined`, check if it's [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
3. Otherwise, if `x[Symbol.match]` is `undefined`, check if `x` had been created with the `RegExp` constructor. (This step should rarely happen, since if `x` is a `RegExp` object that have not been tampered with, it should have a `Symbol.match` property.)
Note that in most cases, it would go through the `Symbol.match` check, which means:
* An actual `RegExp` object whose `Symbol.match` property's value is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) but not `undefined` (even with everything else intact, like [`exec`](regexp/exec) and [`@@replace`](regexp/@@replace)) can be used as if it's not a regex.
* A non-`RegExp` object with a `Symbol.match` property will be treated as if it's a regex.
This choice was made because `@@match` is the most indicative property that something is intended to be used for matching. (`exec` could also be used, but because it's not a symbol property, there would be too many false positives.) The places that treat regexes specially include:
* [`String.prototype.endsWith()`](string/endswith), [`startsWith()`](string/startswith), and [`includes()`](string/includes) throw a [`TypeError`](typeerror) if the first argument is a regex.
* [`String.prototype.matchAll()`](string/matchall) and [`replaceAll()`](string/replaceall) check whether the [global](regexp/global) flag is set if the first argument is a regex before invoking its [`@@matchAll`](symbol/matchall) or [`@@replace`](symbol/replace) method.
* The [`RegExp()`](regexp/regexp) constructor directly returns the `pattern` argument only if `pattern` is a regex (among a few other conditions). If `pattern` is a regex, it would also interrogate `pattern`'s `source` and `flags` properties instead of coercing `pattern` to a string.
For example, [`String.prototype.endsWith()`](string/endswith) would coerce all inputs to strings, but it would throw if the argument is a regex, because it's only designed to match strings, and using a regex is likely a developer mistake.
```
"foobar".endsWith({ toString: () => "bar" }); // true
"foobar".endsWith(/bar/); // TypeError: First argument to String.prototype.endsWith must not be a regular expression
```
You can get around the check by setting `@@match` to a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value that's not `undefined`. This would mean that the regex cannot be used for `String.prototype.match()` (since without `@@match`, `match()` would construct a new `RegExp` object with the two enclosing slashes added by [`re.toString()`](regexp/tostring)), but it can be used for virtually everything else.
```
const re = /bar/g;
re[Symbol.match] = false;
"/bar/g".endsWith(re); // true
re.exec("bar"); // [ 'bar', index: 0, input: 'bar', groups: undefined ]
"bar & bar".replace(re, "foo"); // 'foo & foo'
```
### Perl-like RegExp properties
Note that several of the [`RegExp`](regexp) properties have both long and short (Perl-like) names. Both names always refer to the same value. (Perl is the programming language from which JavaScript modeled its regular expressions.) See also [deprecated `RegExp` properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp).
Constructor
-----------
[`RegExp()`](regexp/regexp) Creates a new `RegExp` object.
Static properties
-----------------
[`get RegExp[@@species]`](regexp/@@species) The constructor function that is used to create derived objects.
[`RegExp.$1, …, RegExp.$9`](regexp/n) Deprecated
Static read-only properties that contain parenthesized substring matches.
[`RegExp.input ($_)`](regexp/input) Deprecated
A static property that contains the last string against which a regular expression was successfully matched.
[`RegExp.lastMatch ($&)`](regexp/lastmatch) Deprecated
A static read-only property that contains the last matched substring.
[`RegExp.lastParen ($+)`](regexp/lastparen) Deprecated
A static read-only property that contains the last parenthesized substring match.
[`RegExp.leftContext ($`)`](regexp/leftcontext) Deprecated
A static read-only property that contains the substring preceding the most recent match.
[`RegExp.rightContext ($')`](regexp/rightcontext) Deprecated
A static read-only property that contains the substring following the most recent match.
Instance properties
-------------------
[`RegExp.prototype.flags`](regexp/flags) A string that contains the flags of the `RegExp` object.
[`RegExp.prototype.dotAll`](regexp/dotall) Whether `.` matches newlines or not.
[`RegExp.prototype.global`](regexp/global) Whether to test the regular expression against all possible matches in a string, or only against the first.
[`RegExp.prototype.hasIndices`](regexp/hasindices) Whether the regular expression result exposes the start and end indices of captured substrings.
[`RegExp.prototype.ignoreCase`](regexp/ignorecase) Whether to ignore case while attempting a match in a string.
[`RegExp.prototype.multiline`](regexp/multiline) Whether or not to search in strings across multiple lines.
[`RegExp.prototype.source`](regexp/source) The text of the pattern.
[`RegExp.prototype.sticky`](regexp/sticky) Whether or not the search is sticky.
[`RegExp.prototype.unicode`](regexp/unicode) Whether or not Unicode features are enabled.
[`RegExp.prototype.lastIndex`](regexp/lastindex) The index at which to start the next match.
Instance methods
----------------
[`RegExp.prototype.compile()`](regexp/compile) Deprecated
(Re-)compiles a regular expression during execution of a script.
[`RegExp.prototype.exec()`](regexp/exec) Executes a search for a match in its string parameter.
[`RegExp.prototype.test()`](regexp/test) Tests for a match in its string parameter.
[`RegExp.prototype.toString()`](regexp/tostring) Returns a string representing the specified object. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`RegExp.prototype[@@match]()`](regexp/@@match) Performs match to given string and returns match result.
[`RegExp.prototype[@@matchAll]()`](regexp/@@matchall) Returns all matches of the regular expression against a string.
[`RegExp.prototype[@@replace]()`](regexp/@@replace) Replaces matches in given string with new substring.
[`RegExp.prototype[@@search]()`](regexp/@@search) Searches the match in given string and returns the index the pattern found in the string.
[`RegExp.prototype[@@split]()`](regexp/@@split) Splits given string into an array by separating the string into substrings.
Examples
--------
### Using a regular expression to change data format
The following script uses the [`replace()`](string/replace) method of the [`String`](string) instance to match a name in the format *first last* and output it in the format *last, first*.
In the replacement text, the script uses `$1` and `$2` to indicate the results of the corresponding matching parentheses in the regular expression pattern.
```
const re = /(\w+)\s(\w+)/;
const str = 'Maria Cruz';
const newstr = str.replace(re, '$2, $1');
console.log(newstr);
```
This displays `"Cruz, Maria"`.
### Using regular expression to split lines with different line endings/ends of line/line breaks
The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.
```
const text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
const lines = text.split(/\r\n|\r|\n/);
console.log(lines); // [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
```
Note that the order of the patterns in the regular expression matters.
### Using regular expression on multiple lines
```
const s = 'Please yes\nmake my day!';
s.match(/yes.\*day/);
// Returns null
s.match(/yes[^]\*day/);
// Returns ["yes\nmake my day"]
```
### Using a regular expression with the sticky flag
The [`sticky`](regexp/sticky) flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at [`RegExp.prototype.lastIndex`](regexp/lastindex).
```
const str = '#foo#';
const regex = /foo/y;
regex.lastIndex = 1;
regex.test(str) // true
regex.lastIndex = 5;
regex.test(str) // false (lastIndex is taken into account with sticky flag)
regex.lastIndex // 0 (reset after match failure)
```
### The difference between the sticky flag and the global flag
With the sticky flag `y`, the next match has to happen at the `lastIndex` position, while with the global flag `g`, the match can happen at the `lastIndex` position or later:
```
const re = /\d/y;
let r;
while ((r = re.exec("123 456"))) {
console.log(r, "AND re.lastIndex", re.lastIndex);
}
// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
// … and no more match.
```
With the global flag `g`, all 6 digits would be matched, not just 3.
### Regular expression and Unicode characters
`\w` and `\W` only matches ASCII based characters; for example, `a` to `z`, `A` to `Z`, `0` to `9`, and `_`.
To match characters from other languages such as Cyrillic or Hebrew, use `\uhhhh`, where `hhhh` is the character's Unicode value in hexadecimal.
This example demonstrates how one can separate out Unicode characters from a word.
```
const text = 'Образец text на русском языке';
const regex = /[\u0400-\u04FF]+/g;
const match = regex.exec(text);
console.log(match[0]); // 'Образец'
console.log(regex.lastIndex); // 7
const match2 = regex.exec(text);
console.log(match2[0]); // 'на' (did not log 'text')
console.log(regex.lastIndex); // 15
// and so on
```
The [Unicode property escapes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes) feature provides a simpler way to target particular Unicode ranges, by allowing for statements like `\p{scx=Cyrl}` (to match any Cyrillic letter), or `\p{L}/u` (to match a letter from any language).
### Extracting subdomain name from URL
```
const url = "http://xxx.domain.com";
console.log(/^https?:\/\/(.+?)\./.exec(url)[1]); // 'xxx'
```
**Note:** Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the [URL API](https://developer.mozilla.org/en-US/docs/Web/API/URL_API).
### Building a regular expression from dynamic inputs
```
const breakfasts = ['bacon', 'eggs', 'oatmeal', 'toast', 'cereal'];
const order = 'Let me get some bacon and eggs, please';
order.match(new RegExp(`\\b(${breakfasts.join('|')})\\b`, 'g'));
// Returns ['bacon', 'eggs']
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp-regular-expression-objects](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp-regular-expression-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@match` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `@@matchAll` | 73 | 79 | 67 | No | 60 | 13 | 73 | 73 | 67 | 52 | 13 | 5.0 | 1.0 | 12.0.0 |
| `@@replace` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `@@search` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `@@species` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `@@split` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `RegExp` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `RegExp` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `compile` | 1 | 12 | 1 | 4 | 6 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 | 1.0 | 0.10.0 |
| `dotAll` | 62 | 79 | 78 | No | 49 | 11.1 | 62 | 62 | 79 | 46 | 11.3 | 8.0 | 1.0 | 8.10.0
8.3.0 |
| `exec` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `flags` | 49 | 79 | 37 | No | 39 | 9 | 49 | 49 | 37 | 41 | 9 | 5.0 | 1.0 | 6.0.0 |
| `global` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `hasIndices` | 90 | 90 | 88 | No | 76 | 15 | 90 | 90 | 88 | 64 | 15 | 15.0 | 1.8 | 16.0.0 |
| `ignoreCase` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `input` | 1 | 12 | 1 | 5.5 | 15 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lastIndex` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lastMatch` | 1 | 12 | 1 | 5.5 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lastParen` | 1 | 12 | 1 | 5.5 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | 1.0 | 0.10.0 |
| `leftContext` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `lookbehind_assertion` | 62 | 79 | 78 | No | 49 | No | 62 | 62 | 79 | 46 | No | 8.0 | 1.0 | 8.10.0 |
| `multiline` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `n` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `named_capture_groups` | 64 | 79 | 78 | No | 51 | 11.1 | 64 | 64 | 79 | 47 | 11.3 | 9.0 | 1.0 | 10.0.0
8.3.0 |
| `property_escapes` | 64 | 79 | 78 | No | 51 | 11.1 | 64 | 64 | 79 | 47 | 11.3 | 9.0 | 1.0 | 10.0.0
8.3.0 |
| `rightContext` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `source` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sticky` | 49 | 13 | 3 | No | 36 | 10 | 49 | 49 | 4 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `test` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `unicode` | 50 | 12
Case folding is implemented in version 13 | 46 | No | 37 | 10 | 50 | 50 | 46 | 37 | 10 | 5.0 | 1.0 | 6.0.0
Case folding is implemented in version 8.6.0 |
### Firefox-specific notes
Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now `undefined` instead of an empty string:
```
// Firefox 33 or older
'x'.replace(/x(.)?/g, (m, group) => {
console.log(`group: ${JSON.stringify(group)}`);
});
// group: ""
// Firefox 34 or newer
'x'.replace(/x(.)?/g, (m, group) => {
console.log(`group: ${group}`);
});
// group: undefined
```
Note that due to web compatibility, `RegExp.$N` will still return an empty string instead of `undefined` ([bug 1053944](https://bugzilla.mozilla.org/show_bug.cgi?id=1053944)).
See also
--------
* [Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) chapter in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* [`String.prototype.match()`](string/match)
* [`String.prototype.replace()`](string/replace)
* [`String.prototype.split()`](string/split)
javascript EvalError EvalError
=========
The `EvalError` object indicates an error regarding the global [`eval()`](eval) function. This exception is not thrown by JavaScript anymore, however the `EvalError` object remains for compatibility.
`EvalError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`EvalError()`](evalerror/evalerror) Creates a new `EvalError` object.
Instance properties
-------------------
[`EvalError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`EvalError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`EvalError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`EvalError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`EvalError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`EvalError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`EvalError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
`EvalError` is not used in the current ECMAScript specification and will thus not be thrown by the runtime. However, the object itself remains for backwards compatibility with earlier versions of the specification.
### Creating an EvalError
```
try {
throw new EvalError("Hello", "someFile.js", 10);
} catch (e) {
console.log(e instanceof EvalError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "EvalError"
console.log(e.fileName); // "someFile.js"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // "@Scratchpad/2:2:9\n"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-evalerror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-evalerror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `EvalError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `EvalError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
* [`eval()`](eval)
| programming_docs |
javascript Proxy Proxy
=====
The `Proxy` object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
Description
-----------
The `Proxy` object allows you to create an object that can be used in place of the original object, but which may redefine fundamental `Object` operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
You create a `Proxy` with two parameters:
* `target`: the original object which you want to proxy
* `handler`: an object that defines which operations will be intercepted and how to redefine intercepted operations.
For example, this code creates a proxy for the `target` object.
```
const target = {
message1: "hello",
message2: "everyone",
};
const handler1 = {};
const proxy1 = new Proxy(target, handler1);
```
Because the handler is empty, this proxy behaves just like the original target:
```
console.log(proxy1.message1); // hello
console.log(proxy1.message2); // everyone
```
To customize the proxy, we define functions on the handler object:
```
const target = {
message1: "hello",
message2: "everyone",
};
const handler2 = {
get(target, prop, receiver) {
return "world";
},
};
const proxy2 = new Proxy(target, handler2);
```
Here we've provided an implementation of the [`get()`](proxy/proxy/get) handler, which intercepts attempts to access properties in the target.
Handler functions are sometimes called *traps*, presumably because they trap calls to the target object. The very simple trap in `handler2` above redefines all property accessors:
```
console.log(proxy2.message1); // world
console.log(proxy2.message2); // world
```
Proxies are often used with the [`Reflect`](reflect) object, which provides some methods with the same names as the `Proxy` traps. The `Reflect` methods provide the reflective semantics for invoking the corresponding [object internal methods](#object_internal_methods). For example, we can call `Reflect.get` if we don't wish to redefine the object's behavior:
```
const target = {
message1: "hello",
message2: "everyone",
};
const handler3 = {
get(target, prop, receiver) {
if (prop === "message2") {
return "world";
}
return Reflect.get(...arguments);
},
};
const proxy3 = new Proxy(target, handler3);
console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world
```
The `Reflect` method still interacts with the object through object internal methods — it doesn't "de-proxify" the proxy if it's invoked on a proxy. If you use `Reflect` methods within a proxy trap, and the `Reflect` method call gets intercepted by the trap again, there may be infinite recursion.
### Terminology
The following terms are used when talking about the functionality of proxies.
[handler](proxy/proxy#handler_functions) The object passed as the second argument to the `Proxy` constructor. It contains the traps which define the behavior of the proxy.
trap The function that define the behavior for the corresponding [object internal method](#object_internal_methods). (This is analogous to the concept of *traps* in operating systems.)
target Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
invariants Semantics that remain unchanged when implementing custom operations. If your trap implementation violates the invariants of a handler, a [`TypeError`](typeerror) will be thrown.
### Object internal methods
[Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects) are collections of properties. However, the language doesn't provide any machinery to *directly* manipulate data stored in the object — rather, the object defines some internal methods specifying how it can be interacted with. For example, when you read `obj.x`, you may expect the following to happen:
* The `x` property is searched up the [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) until it is found.
* If `x` is a data property, the property descriptor's `value` attribute is returned.
* If `x` is an accessor property, the getter is invoked, and the return value of the getter is returned.
There isn't anything special about this process in the language — it's just because ordinary objects, by default, have a `[[Get]]` internal method that is defined with this behavior. The `obj.x` property access syntax simply invokes the `[[Get]]` method on the object, and the object uses its own internal method implementation to determine what to return.
As another example, [arrays](array) differ from normal objects, because they have a magic [`length`](array/length) property that, when modified, automatically allocates empty slots or removes elements from the array. Similarly, adding array elements automatically changes the `length` property. This is because arrays have a `[[DefineOwnProperty]]` internal method that knows to update `length` when an integer index is written to, or update the array contents when `length` is written to. Such objects whose internal methods have different implementations from ordinary objects are called *exotic objects*. `Proxy` enable developers to define their own exotic objects with full capacity.
All objects have the following internal methods:
| Internal method | Corresponding trap |
| --- | --- |
| `[[GetPrototypeOf]]` | [`getPrototypeOf()`](proxy/proxy/getprototypeof) |
| `[[SetPrototypeOf]]` | [`setPrototypeOf()`](proxy/proxy/setprototypeof) |
| `[[IsExtensible]]` | [`isExtensible()`](proxy/proxy/isextensible) |
| `[[PreventExtensions]]` | [`preventExtensions()`](proxy/proxy/preventextensions) |
| `[[GetOwnProperty]]` | [`getOwnPropertyDescriptor()`](proxy/proxy/getownpropertydescriptor) |
| `[[DefineOwnProperty]]` | [`defineProperty()`](proxy/proxy/defineproperty) |
| `[[HasProperty]]` | [`has()`](proxy/proxy/has) |
| `[[Get]]` | [`get()`](proxy/proxy/get) |
| `[[Set]]` | [`set()`](proxy/proxy/set) |
| `[[Delete]]` | [`deleteProperty()`](proxy/proxy/deleteproperty) |
| `[[OwnPropertyKeys]]` | [`ownKeys()`](proxy/proxy/ownkeys) |
Function objects also have the following internal methods:
| Internal method | Corresponding trap |
| --- | --- |
| `[[Call]]` | [`apply()`](proxy/proxy/apply) |
| `[[Construct]]` | [`construct()`](proxy/proxy/construct) |
It's important to realize that all interactions with an object eventually boils down to the invocation of one of these internal methods, and that they are all customizable through proxies. This means almost no behavior (except certain critical invariants) is guaranteed in the language — everything is defined by the object itself. When you run [`delete obj.x`](../operators/delete), there's no guarantee that [`"x" in obj`](../operators/in) returns `false` afterwards — it depends on the object's implementations of `[[Delete]]` and `[[HasProperty]]`. A `delete obj.x` may log things to the console, modify some global state, or even define a new property instead of deleting the existing one, although these semantics should be avoided in your own code.
All internal methods are called by the language itself, and are not directly accessible in JavaScript code. The [`Reflect`](reflect) namespace offers methods that do little more than call the internal methods, besides some input normalization/validation. In each trap's page, we list several typical situations when the trap is invoked, but these internal methods are called in *a lot* of places. For example, array methods read and write to array through these internal methods, so methods like [`push()`](array/push) would also invoke `get()` and `set()` traps.
Most of the internal methods are straightforward in what they do. The only two that may be confusable are `[[Set]]` and `[[DefineOwnProperty]]`. For normal objects, the former invokes setters; the latter doesn't. (And `[[Set]]` calls `[[DefineOwnProperty]]` internally if there's no existing property or the property is a data property.) While you may know that the `obj.x = 1` syntax uses `[[Set]]`, and [`Object.defineProperty()`](object/defineproperty) uses `[[DefineOwnProperty]]`, it's not immediately apparent what semantics other built-in methods and syntaxes use. For example, [class fields](../classes/public_class_fields) use the `[[DefineOwnProperty]]` semantic, which is why setters defined in the superclass are not invoked when a field is declared on the derived class.
Constructor
-----------
[`Proxy()`](proxy/proxy) Creates a new `Proxy` object.
Static methods
--------------
[`Proxy.revocable()`](proxy/revocable) Creates a revocable `Proxy` object.
Examples
--------
### Basic example
In this simple example, the number `37` gets returned as the default value when the property name is not in the object. It is using the [`get()`](proxy/proxy/get) handler.
```
const handler = {
get(obj, prop) {
return prop in obj ? obj[prop] : 37;
},
};
const p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log("c" in p, p.c); // false, 37
```
### No-op forwarding proxy
In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.
```
const target = {};
const p = new Proxy(target, {});
p.a = 37; // Operation forwarded to the target
console.log(target.a); // 37 (The operation has been properly forwarded!)
```
Note that while this "no-op" works for plain JavaScript objects, it does not work for native objects, such as DOM elements, [`Map`](map) objects, or anything that has internal slots. See [no private property forwarding](#no_private_property_forwarding) for more information.
### No private property forwarding
A proxy is still another object with a different identity — it's a *proxy* that operates between the wrapped object and the outside. As such, the proxy does not have direct access to the original object's [private properties](../classes/private_class_fields).
```
class Secret {
#secret;
constructor(secret) {
this.#secret = secret;
}
get secret() {
return this.#secret.replace(/\d+/, "[REDACTED]");
}
}
const aSecret = new Secret("123456");
console.log(aSecret.secret); // [REDACTED]
// Looks like a no-op forwarding...
const proxy = new Proxy(aSecret, {});
console.log(proxy.secret); // TypeError: Cannot read private member #secret from an object whose class did not declare it
```
This is because when the proxy's `get` trap is invoked, the `this` value is the `proxy` instead of the original `secret`, so `#secret` is not accessible. To fix this, use the original `secret` as `this`:
```
const proxy = new Proxy(aSecret, {
get(target, prop, receiver) {
// By default, it looks like Reflect.get(target, prop, receiver)
// which has a different value of `this`
return target[prop];
},
});
console.log(proxy.secret);
```
For methods, this means you have to redirect the method's `this` value to the original object as well:
```
class Secret {
#x = 1;
x() {
return this.#x;
}
}
const aSecret = new Secret();
const proxy = new Proxy(aSecret, {
get(target, prop, receiver) {
const value = target[prop];
if (value instanceof Function) {
return function (...args) {
return value.apply(this === receiver ? target : this, args);
};
}
return value;
},
});
console.log(proxy.x());
```
Some native JavaScript objects have properties called *[internal slots](https://tc39.es/ecma262/#sec-object-internal-methods-and-internal-slots)*, which are not accessible from JavaScript code. For example, [`Map`](map) objects have an internal slot called `[[MapData]]`, which stores the key-value pairs of the map. As such, you cannot trivially create a forwarding proxy for a map:
```
const proxy = new Proxy(new Map(), {});
console.log(proxy.size); // TypeError: get size method called on incompatible Proxy
```
You have to use the "`this`-recovering" proxy illustrated above to work around this.
### Validation
With a `Proxy`, you can easily validate the passed value for an object. This example uses the [`set()`](proxy/proxy/set) handler.
```
const validator = {
set(obj, prop, value) {
if (prop === "age") {
if (!Number.isInteger(value)) {
throw new TypeError("The age is not an integer");
}
if (value > 200) {
throw new RangeError("The age seems invalid");
}
}
// The default behavior to store the value
obj[prop] = value;
// Indicate success
return true;
},
};
const person = new Proxy({}, validator);
person.age = 100;
console.log(person.age); // 100
person.age = "young"; // Throws an exception
person.age = 300; // Throws an exception
```
### Manipulating DOM nodes
In this example we use `Proxy` to toggle an attribute of two different elements: so when we set the attribute on one element, the attribute is unset on the other one.
We create a `view` object which is a proxy for an object with a `selected` property. The proxy handler defines the [`set()`](proxy/proxy/set) handler.
When we assign an HTML element to `view.selected`, the element's `'aria-selected'` attribute is set to `true`. If we then assign a different element to `view.selected`, this element's `'aria-selected'` attribute is set to `true` and the previous element's `'aria-selected'` attribute is automatically set to `false`.
```
const view = new Proxy(
{
selected: null,
},
{
set(obj, prop, newval) {
const oldval = obj[prop];
if (prop === "selected") {
if (oldval) {
oldval.setAttribute("aria-selected", "false");
}
if (newval) {
newval.setAttribute("aria-selected", "true");
}
}
// The default behavior to store the value
obj[prop] = newval;
// Indicate success
return true;
},
}
);
const item1 = document.getElementById("item-1");
const item2 = document.getElementById("item-2");
// select item1:
view.selected = item1;
console.log(`item1: ${item1.getAttribute("aria-selected")}`);
// item1: true
// selecting item2 de-selects item1:
view.selected = item2;
console.log(`item1: ${item1.getAttribute("aria-selected")}`);
// item1: false
console.log(`item2: ${item2.getAttribute("aria-selected")}`);
// item2: true
```
### Value correction and an extra property
The `products` proxy object evaluates the passed value and converts it to an array if needed. The object also supports an extra property called `latestBrowser` both as a getter and a setter.
```
const products = new Proxy(
{
browsers: ["Internet Explorer", "Netscape"],
},
{
get(obj, prop) {
// An extra property
if (prop === "latestBrowser") {
return obj.browsers[obj.browsers.length - 1];
}
// The default behavior to return the value
return obj[prop];
},
set(obj, prop, value) {
// An extra property
if (prop === "latestBrowser") {
obj.browsers.push(value);
return true;
}
// Convert the value if it is not an array
if (typeof value === "string") {
value = [value];
}
// The default behavior to store the value
obj[prop] = value;
// Indicate success
return true;
},
}
);
console.log(products.browsers);
// ['Internet Explorer', 'Netscape']
products.browsers = "Firefox";
// pass a string (by mistake)
console.log(products.browsers);
// ['Firefox'] <- no problem, the value is an array
products.latestBrowser = "Chrome";
console.log(products.browsers);
// ['Firefox', 'Chrome']
console.log(products.latestBrowser);
// 'Chrome'
```
### Finding an array item object by its property
This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using [`Object.defineProperties()`](object/defineproperties). This example can be adapted to find a table row by its cell. In that case, the target will be [`table.rows`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows).
```
const products = new Proxy(
[
{ name: "Firefox", type: "browser" },
{ name: "SeaMonkey", type: "browser" },
{ name: "Thunderbird", type: "mailer" },
],
{
get(obj, prop) {
// The default behavior to return the value; prop is usually an integer
if (prop in obj) {
return obj[prop];
}
// Get the number of products; an alias of products.length
if (prop === "number") {
return obj.length;
}
let result;
const types = {};
for (const product of obj) {
if (product.name === prop) {
result = product;
}
if (types[product.type]) {
types[product.type].push(product);
} else {
types[product.type] = [product];
}
}
// Get a product by name
if (result) {
return result;
}
// Get products by type
if (prop in types) {
return types[prop];
}
// Get product types
if (prop === "types") {
return Object.keys(types);
}
return undefined;
},
}
);
console.log(products[0]); // { name: 'Firefox', type: 'browser' }
console.log(products["Firefox"]); // { name: 'Firefox', type: 'browser' }
console.log(products["Chrome"]); // undefined
console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
console.log(products.types); // ['browser', 'mailer']
console.log(products.number); // 3
```
### A complete traps list example
Now in order to create a complete sample `traps` list, for didactic purposes, we will try to proxify a *non-native* object that is particularly suited to this type of operation: the `docCookies` global object created by [a simple cookie framework](https://reference.codeproject.com/dom/document/cookie/simple_document.cookie_framework).
```
/\*
const docCookies = ... get the "docCookies" object here:
https://reference.codeproject.com/dom/document/cookie/simple\_document.cookie\_framework
\*/
const docCookies = new Proxy(docCookies, {
get(target, key) {
return target[key] ?? target.getItem(key) ?? undefined;
},
set(target, key, value) {
if (key in target) {
return false;
}
return target.setItem(key, value);
},
deleteProperty(target, key) {
if (!(key in target)) {
return false;
}
return target.removeItem(key);
},
ownKeys(target) {
return target.keys();
},
has(target, key) {
return key in target || target.hasItem(key);
},
defineProperty(target, key, descriptor) {
if (descriptor && "value" in descriptor) {
target.setItem(key, descriptor.value);
}
return target;
},
getOwnPropertyDescriptor(target, key) {
const value = target.getItem(key);
return value
? {
value,
writable: true,
enumerable: true,
configurable: false,
}
: undefined;
},
});
/\* Cookies test \*/
console.log((docCookies.myCookie1 = "First value"));
console.log(docCookies.getItem("myCookie1"));
docCookies.setItem("myCookie1", "Changed value");
console.log(docCookies.myCookie1);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-objects](https://tc39.es/ecma262/multipage/reflection.html#sec-proxy-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Proxy` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `Proxy` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `revocable` | 63 | 12 | 34 | No | 50 | 10 | 63 | 63 | 34 | 46 | 10 | 8.0 | 1.0 | 6.0.0 |
See also
--------
* ["Proxies are awesome" Brendan Eich presentation at JSConf](https://www.youtube.com/watch?v=sClk6aB_CPk) ([slides](https://www.slideshare.net/BrendanEich/metaprog-5303821))
* [Tutorial on proxies](https://web.archive.org/web/20171007221059/https://soft.vub.ac.be/~tvcutsem/proxies/)
| programming_docs |
javascript NaN NaN
===
The global `NaN` property is a value representing Not-A-Number.
Try it
------
Value
-----
The same number value as [`Number.NaN`](number/nan).
| Property attributes of `NaN` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`NaN` is a property of the *global object*. In other words, it is a variable in global scope.
In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.
There are five different types of operations that return `NaN`:
* Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`)
* Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`)
* Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`)
* A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) — this means `NaN` is contagious
* Other cases where an invalid value is to be represented as a number (e.g. an invalid [Date](date) `new Date("blabla").getTime()`, `"".charCodeAt(1)`)
`NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include:
* If `NaN` is involved in a mathematical operation (but not [bitwise operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See [counter-example](#silently_escaping_nan) below.)
* When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`.
* `NaN` compares unequal (via [`==`](../operators/equality), [`!=`](../operators/inequality), [`===`](../operators/strict_equality), and [`!==`](../operators/strict_inequality)) to any other value — including to another `NaN` value.
`NaN` is also one of the [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values in JavaScript.
Examples
--------
### Testing against NaN
To tell if a value is `NaN`, use [`Number.isNaN()`](number/isnan) or [`isNaN()`](isnan) to most clearly determine whether a value is `NaN` — or, since `NaN` is the only value that compares unequal to itself, you can perform a self-comparison like `x !== x`.
```
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Number.isNaN(NaN); // true
function valueIsNaN(v) {
return v !== v;
}
valueIsNaN(1); // false
valueIsNaN(NaN); // true
valueIsNaN(Number.NaN); // true
```
However, do note the difference between `isNaN()` and `Number.isNaN()`: the former will return `true` if the value is currently `NaN`, or if it is going to be `NaN` after it is coerced to a number, while the latter will return `true` only if the value is currently `NaN`:
```
isNaN("hello world"); // true
Number.isNaN("hello world"); // false
```
For the same reason, using a BigInt value will throw an error with `isNaN()` and not with `Number.isNaN()`:
```
isNaN(1n); // TypeError: Conversion from 'BigInt' to 'number' is not allowed.
Number.isNaN(1n); // false
```
Additionally, some array methods cannot find `NaN`, while others can. Namely, the index-finding ones ([`indexOf()`](array/indexof), [`lastIndexOf()`](array/lastindexof)) cannot find `NaN`, while the value-finding ones ([`includes()`](array/includes)) can:
```
const arr = [2, 4, NaN, 12];
arr.indexOf(NaN); // -1
arr.includes(NaN); // true
// Methods accepting a properly defined predicate can always find NaN
arr.findIndex((n) => Number.isNaN(n)); // 2
```
For more information about `NaN` and its comparison, see [Equality comparison and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness).
### Observably distinct NaN values
There's a motivation for `NaN` being unequal to itself. It's possible to produce two floating point numbers with different binary representations but are both `NaN`, because in [IEEE 754 encoding](https://en.wikipedia.org/wiki/NaN#Floating_point), any floating point number with exponent `0x7ff` and a non-zero mantissa is `NaN`. In JavaScript, you can do bit-level manipulation using [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays).
```
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]
```
### Silently escaping NaN
`NaN` propagates through mathematical operations, so it's usually sufficient to test for `NaN` once at the end of calculation to detect error conditions. The only case where `NaN` gets silently escaped is when using [exponentiation](../operators/exponentiation) with an exponent of `0`, which immediately returns `1` without testing the base's value.
```
NaN \*\* 0 === 1; // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-value-properties-of-the-global-object-nan](https://tc39.es/ecma262/multipage/global-object.html#sec-value-properties-of-the-global-object-nan) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `NaN` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Number.NaN`](number/nan)
* [`Number.isNaN()`](number/isnan)
* [`isNaN()`](isnan)
javascript DataView DataView
========
The `DataView` view provides a low-level interface for reading and writing multiple number types in a binary [`ArrayBuffer`](arraybuffer), without having to care about the platform's [endianness](https://developer.mozilla.org/en-US/docs/Glossary/Endianness).
Description
-----------
### Endianness
Multi-byte number formats are represented in memory differently depending on machine architecture — see [Endianness](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) for an explanation. `DataView` accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness.
```
const littleEndian = (() => {
const buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /\* littleEndian \*/);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
console.log(littleEndian); // true or false
```
### 64-bit Integer Values
Some browsers don't have support for [`DataView.prototype.setBigInt64()`](dataview/setbigint64) and [`DataView.prototype.setBigUint64()`](dataview/setbiguint64). So to enable 64-bit operations in your code that will work across browsers, you could implement your own `getUint64()` function, to obtain values with precision up to [`Number.MAX_SAFE_INTEGER`](number/max_safe_integer) — which could suffice for certain cases.
```
function getUint64(dataview, byteOffset, littleEndian) {
// split 64-bit number into two 32-bit (4-byte) parts
const left = dataview.getUint32(byteOffset, littleEndian);
const right = dataview.getUint32(byteOffset+4, littleEndian);
// combine the two 32-bit values
const combined = littleEndian? left + 2\*\*32\*right : 2\*\*32\*left + right;
if (!Number.isSafeInteger(combined))
console.warn(combined, 'exceeds MAX\_SAFE\_INTEGER. Precision may be lost');
return combined;
}
```
Alternatively, if you need full 64-bit range, you can create a [`BigInt`](bigint). Further, although native BigInts are much faster than user-land library equivalents, BigInts will always be much slower than 32-bit integers in JavaScript due to the nature of their variable size.
```
const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0);
function getUint64BigInt(dataview, byteOffset, littleEndian) {
// split 64-bit number into two 32-bit (4-byte) parts
const left = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0);
const right = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>0);
// combine the two 32-bit values and return
return littleEndian ? (right<<bigThirtyTwo)|left : (left<<bigThirtyTwo)|right;
}
```
Constructor
-----------
[`DataView()`](dataview/dataview) Creates a new `DataView` object.
Instance properties
-------------------
`DataView.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"DataView"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`DataView.prototype.buffer`](dataview/buffer) The [`ArrayBuffer`](arraybuffer) referenced by this view. Fixed at construction time and thus **read only.**
[`DataView.prototype.byteLength`](dataview/bytelength) The length (in bytes) of this view. Fixed at construction time and thus **read only.**
[`DataView.prototype.byteOffset`](dataview/byteoffset) The offset (in bytes) of this view from the start of its [`ArrayBuffer`](arraybuffer). Fixed at construction time and thus **read only.**
Instance methods
----------------
[`DataView.prototype.getInt8()`](dataview/getint8) Gets a signed 8-bit integer (byte) at the specified byte offset from the start of the view.
[`DataView.prototype.getUint8()`](dataview/getuint8) Gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the view.
[`DataView.prototype.getInt16()`](dataview/getint16) Gets a signed 16-bit integer (short) at the specified byte offset from the start of the view.
[`DataView.prototype.getUint16()`](dataview/getuint16) Gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the view.
[`DataView.prototype.getInt32()`](dataview/getint32) Gets a signed 32-bit integer (long) at the specified byte offset from the start of the view.
[`DataView.prototype.getUint32()`](dataview/getuint32) Gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the view.
[`DataView.prototype.getFloat32()`](dataview/getfloat32) Gets a signed 32-bit float (float) at the specified byte offset from the start of the view.
[`DataView.prototype.getFloat64()`](dataview/getfloat64) Gets a signed 64-bit float (double) at the specified byte offset from the start of the view.
[`DataView.prototype.getBigInt64()`](dataview/getbigint64) Gets a signed 64-bit integer (long long) at the specified byte offset from the start of the view.
[`DataView.prototype.getBigUint64()`](dataview/getbiguint64) Gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the view.
[`DataView.prototype.setInt8()`](dataview/setint8) Stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the view.
[`DataView.prototype.setUint8()`](dataview/setuint8) Stores an unsigned 8-bit integer (unsigned byte) value at the specified byte offset from the start of the view.
[`DataView.prototype.setInt16()`](dataview/setint16) Stores a signed 16-bit integer (short) value at the specified byte offset from the start of the view.
[`DataView.prototype.setUint16()`](dataview/setuint16) Stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the view.
[`DataView.prototype.setInt32()`](dataview/setint32) Stores a signed 32-bit integer (long) value at the specified byte offset from the start of the view.
[`DataView.prototype.setUint32()`](dataview/setuint32) Stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the view.
[`DataView.prototype.setFloat32()`](dataview/setfloat32) Stores a signed 32-bit float (float) value at the specified byte offset from the start of the view.
[`DataView.prototype.setFloat64()`](dataview/setfloat64) Stores a signed 64-bit float (double) value at the specified byte offset from the start of the view.
[`DataView.prototype.setBigInt64()`](dataview/setbigint64) Stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the view.
[`DataView.prototype.setBigUint64()`](dataview/setbiguint64) Stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the view.
Examples
--------
### Using DataView
```
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer, 0);
view.setInt16(1, 42);
view.getInt16(1); // 42
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview-objects](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `DataView` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `DataView` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `buffer` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `byteLength` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `byteOffset` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getBigInt64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `getBigUint64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `getFloat32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getFloat64` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getInt16` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getInt32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getInt8` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getUint16` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getUint32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `getUint8` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setBigInt64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `setBigUint64` | 67 | 79 | 68 | No | 54 | 15 | 67 | 67 | 68 | 48 | 15 | 9.0 | 1.0 | 10.4.0 |
| `setFloat32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setFloat64` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setInt16` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setInt32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setInt8` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setUint16` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setUint32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
| `setUint8` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `DataView` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [jDataView](https://github.com/jDataView/jDataView): JavaScript library that polyfills and extends the `DataView` API to all browsers and Node.js.
* [`ArrayBuffer`](arraybuffer)
* [`SharedArrayBuffer`](sharedarraybuffer)
javascript WeakSet WeakSet
=======
The `WeakSet` object lets you store weakly held *objects* in a collection.
Description
-----------
`WeakSet` objects are collections of objects. Just as with [`Set`](set)s, each object in a `WeakSet` may occur only once; all objects in a `WeakSet`'s collection are unique.
The main differences to the [`Set`](set) object are:
* `WeakSet`s are collections of **objects only**. They cannot contain arbitrary values of any type, as [`Set`](set)s can.
* The `WeakSet` is *weak*, meaning references to objects in a `WeakSet` are held *weakly*. If no other references to an object stored in the `WeakSet` exist, those objects can be garbage collected. **Note:** This also means that there is no list of current objects stored in the collection. `WeakSets` are not enumerable.
### Use case: Detecting circular references
Functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed.
`WeakSet`s are ideal for this purpose:
```
// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = new WeakSet()) {
// Avoid infinite recursion
if (_refs.has(subject)) {
return;
}
fn(subject);
if (typeof subject === "object") {
_refs.add(subject);
for (const key in subject) {
execRecursively(fn, subject[key], _refs);
}
_refs.delete(subject);
}
}
const foo = {
foo: "Foo",
bar: {
bar: "Bar",
},
};
foo.bar.baz = foo; // Circular reference!
execRecursively((obj) => console.log(obj), foo);
```
Here, a `WeakSet` is created on the first run, and passed along with every subsequent function call (using the internal `_refs` parameter).
The number of objects or their traversal order is immaterial, so a `WeakSet` is more suitable (and performant) than a [`Set`](set) for tracking object references, especially if a very large number of objects is involved.
Constructor
-----------
[`WeakSet()`](weakset/weakset) Creates a new `WeakSet` object.
Instance properties
-------------------
`WeakSet.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"WeakSet"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`WeakSet.prototype.add()`](weakset/add) Appends `value` to the `WeakSet` object.
[`WeakSet.prototype.delete()`](weakset/delete) Removes `value` from the `WeakSet`. `WeakSet.prototype.has(value)` will return `false` afterwards.
[`WeakSet.prototype.has()`](weakset/has) Returns a boolean asserting whether `value` is present in the `WeakSet` object or not.
Examples
--------
### Using the WeakSet object
```
const ws = new WeakSet();
const foo = {};
const bar = {};
ws.add(foo);
ws.add(bar);
ws.has(foo); // true
ws.has(bar); // true
ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained
```
Note that `foo !== bar`. While they are similar objects, *they are not **the same object***. And so they are both added to the set.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakset-objects](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `WeakSet` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `WeakSet` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `add` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `delete` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `has` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `WeakSet` in `core-js`](https://github.com/zloirock/core-js#weakset)
* [`Map`](map)
* [`Set`](set)
* [`WeakMap`](weakmap)
| programming_docs |
javascript AggregateError AggregateError
==============
The `AggregateError` object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by [`Promise.any()`](promise/any), when all promises passed to it reject.
Constructor
-----------
[`AggregateError()`](aggregateerror/aggregateerror) Creates a new `AggregateError` object.
Instance properties
-------------------
[`AggregateError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`AggregateError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`AggregateError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
`AggregateError.prototype.errors` An array that essentially reflects the iterable with which the `AggregateError` was instantiated; for example, if the `AggregateError` was created using the [`AggregateError()`](aggregateerror/aggregateerror) constructor, an array produced from whatever iterable was passed to the constructor as its first argument.
Examples
--------
### Catching an AggregateError
```
Promise.any([
Promise.reject(new Error("some error")),
]).catch((e) => {
console.log(e instanceof AggregateError); // true
console.log(e.message); // "All Promises rejected"
console.log(e.name); // "AggregateError"
console.log(e.errors); // [ Error: "some error" ]
});
```
### Creating an AggregateError
```
try {
throw new AggregateError([
new Error("some error"),
], 'Hello');
} catch (e) {
console.log(e instanceof AggregateError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "AggregateError"
console.log(e.errors); // [ Error: "some error" ]
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-aggregate-error-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-aggregate-error-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `AggregateError` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
| `AggregateError` | 85 | 85 | 79 | No | 71 | 14 | 85 | 85 | 79 | 60 | 14 | 14.0 | 1.2 | 15.0.0 |
| `serializable_object` | No | No | 103
Serialized properties: `name`, `message`, `cause`, `errors`. | No | No | No | No | No | 103
Serialized properties: `name`, `message`, `cause`, `errors`. | No | No | No | No | No |
See also
--------
* [Polyfill of `AggregateError` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise)
* [`Error`](error)
* [`Promise.any`](promise/any)
javascript Boolean Boolean
=======
The `Boolean` object represents a truth value: `true` or `false`.
Description
-----------
### Boolean primitives and Boolean objects
Do not confuse the [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) `Boolean` values `true` and `false` with the `true` and `false` values of the `Boolean` object.
**Any** object, including a `Boolean` object whose value is `false`, evaluates to `true` when passed to a conditional statement. For example, the condition in the following [`if`](../statements/if...else) statement evaluates to `true`:
```
const x = new Boolean(false);
if (x) {
// this code is executed
}
```
This behavior does not apply to `Boolean` primitives. For example, the condition in the following [`if`](../statements/if...else) statement evaluates to `false`:
```
const x = false;
if (x) {
// this code is not executed
}
```
Do not use the `Boolean()` constructor with `new` to convert a non-boolean value to a boolean value — use `Boolean` as a function or a [double NOT](../operators/logical_not#double_not_!!) instead:
```
const good = Boolean(expression); // use this
const good2 = !!(expression); // or this
const bad = new Boolean(expression); // don't use this!
```
If you specify any object, including a `Boolean` object whose value is `false`, as the initial value of a `Boolean` object, the new `Boolean` object has a value of `true`.
```
const myFalse = new Boolean(false); // initial value of false
const g = Boolean(myFalse); // initial value of true
const myString = new String('Hello'); // string object
const s = Boolean(myString); // initial value of true
```
**Warning:** You should rarely find yourself using `Boolean` as a constructor.
### Boolean coercion
Many built-in operations that expect booleans first coerce their arguments to booleans. [The operation](https://tc39.es/ecma262/#sec-tostring) can be summarized as follows:
* Booleans are returned as-is.
* [`undefined`](undefined) turns into `false`.
* [`null`](../operators/null) turns into `false`.
* `0`, `-0`, and `NaN` turn into `false`; other numbers turn into `true`.
* `0n` turns into `false`; other [BigInts](bigint) turn into `true`.
* [Symbols](symbol) turn into `true`.
* All objects become `true`.
**Note:** A legacy behavior makes [`document.all`](https://developer.mozilla.org/en-US/docs/Web/API/Document/all) return `false` when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.
**Note:** Unlike other type conversions like [string coercion](string#string_coercion) or [number coercion](number#number_coercion), boolean coercion does not attempt to convert objects to primitives.
In other words, there are only a handful of values that get coerced to `false` — these are called [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values. All other values are called [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context.
There are two ways to achieve the same effect in JavaScript.
* [Double NOT](../operators/logical_not#double_not_!!): `!!x` negates `x` twice, which converts `x` to a boolean using the same algorithm as above.
* The [`Boolean()`](boolean/boolean) function: `Boolean(x)` uses the same algorithm as above to convert `x`.
Note that truthiness is not the same as being [loosely equal](../operators/equality) to `true` or `false`.
```
if ([]) {
console.log("[] is truthy");
}
if ([] == false) {
console.log("[] == false");
}
// [] is truthy
// [] == false
```
`[]` is truthy, but it's also loosely equal to `false`. It's truthy, because all objects are truthy. However, when comparing with `false`, which is a primitive, `[]` is also converted to a primitive, which is `""` via [`Array.prototype.toString()`](array/tostring). Comparing strings and booleans results in both being [converted to numbers](number#number_coercion), and they both become `0`, so `[] == false` is `true`. In general, falsiness and `== false` differ in the following cases:
* `NaN`, `undefined`, and `null` are falsy but not loosely equal to `false`.
* `"0"` (and other string literals that are not `""` but [get coerced to 0](number#number_coercion)) is truthy but loosely equal to `false`.
* Objects are always truthy, but their primitive representation may be loosely equal to `false`.
Truthy values are even more unlikely to be loosely equal to `true`. All values are either truthy or falsy, but most values are loosely equal to neither `true` nor `false`.
Constructor
-----------
[`Boolean()`](boolean/boolean) Creates a new `Boolean` object.
Instance methods
----------------
[`Boolean.prototype.toString()`](boolean/tostring) Returns a string of either `true` or `false` depending upon the value of the object. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`Boolean.prototype.valueOf()`](boolean/valueof) Returns the primitive value of the [`Boolean`](boolean) object. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
Examples
--------
### Creating Boolean objects with an initial value of false
```
const bNoParam = new Boolean();
const bZero = new Boolean(0);
const bNull = new Boolean(null);
const bEmptyString = new Boolean('');
const bfalse = new Boolean(false);
```
### Creating Boolean objects with an initial value of true
```
const btrue = new Boolean(true);
const btrueString = new Boolean('true');
const bfalseString = new Boolean('false');
const bSuLin = new Boolean('Su Lin');
const bArrayProto = new Boolean([]);
const bObjProto = new Boolean({});
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-boolean-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-boolean-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Boolean` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Boolean` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 3 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `valueOf` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
* [Boolean primitives](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type)
* [Boolean data type (Wikipedia)](https://en.wikipedia.org/wiki/Boolean_data_type)
javascript Math Math
====
`Math` is a built-in object that has properties and methods for mathematical constants and functions. It's not a function object.
`Math` works with the [`Number`](number) type. It doesn't work with [`BigInt`](bigint).
Description
-----------
Unlike many other global objects, `Math` is not a constructor. All properties and methods of `Math` are static. You refer to the constant pi as `Math.PI` and you call the sine function as `Math.sin(x)`, where `x` is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.
**Note:** Many `Math` functions have a precision that's *implementation-dependent.*
This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!
Static properties
-----------------
`Math[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Math"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`Math.E`](math/e) Euler's number and the base of natural logarithms; approximately `2.718`.
[`Math.LN2`](math/ln2) Natural logarithm of `2`; approximately `0.693`.
[`Math.LN10`](math/ln10) Natural logarithm of `10`; approximately `2.303`.
[`Math.LOG2E`](math/log2e) Base-2 logarithm of `E`; approximately `1.443`.
[`Math.LOG10E`](math/log10e) Base-10 logarithm of `E`; approximately `0.434`.
[`Math.PI`](math/pi) Ratio of a circle's circumference to its diameter; approximately `3.14159`.
[`Math.SQRT1_2`](math/sqrt1_2) Square root of ½; approximately `0.707`.
[`Math.SQRT2`](math/sqrt2) Square root of `2`; approximately `1.414`.
Static methods
--------------
[`Math.abs()`](math/abs) Returns the absolute value of `x`.
[`Math.acos()`](math/acos) Returns the arccosine of `x`.
[`Math.acosh()`](math/acosh) Returns the hyperbolic arccosine of `x`.
[`Math.asin()`](math/asin) Returns the arcsine of `x`.
[`Math.asinh()`](math/asinh) Returns the hyperbolic arcsine of a number.
[`Math.atan()`](math/atan) Returns the arctangent of `x`.
[`Math.atanh()`](math/atanh) Returns the hyperbolic arctangent of `x`.
[`Math.atan2()`](math/atan2) Returns the arctangent of the quotient of its arguments.
[`Math.cbrt()`](math/cbrt) Returns the cube root of `x`.
[`Math.ceil()`](math/ceil) Returns the smallest integer greater than or equal to `x`.
[`Math.clz32()`](math/clz32) Returns the number of leading zero bits of the 32-bit integer `x`.
[`Math.cos()`](math/cos) Returns the cosine of `x`.
[`Math.cosh()`](math/cosh) Returns the hyperbolic cosine of `x`.
[`Math.exp()`](math/exp) Returns ex, where x is the argument, and e is Euler's number (`2.718`…, the base of the natural logarithm).
[`Math.expm1()`](math/expm1) Returns subtracting `1` from `exp(x)`.
[`Math.floor()`](math/floor) Returns the largest integer less than or equal to `x`.
[`Math.fround()`](math/fround) Returns the nearest [single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`.
[`Math.hypot()`](math/hypot) Returns the square root of the sum of squares of its arguments.
[`Math.imul()`](math/imul) Returns the result of the 32-bit integer multiplication of `x` and `y`.
[`Math.log()`](math/log) Returns the natural logarithm (㏒e; also, ㏑) of `x`.
[`Math.log1p()`](math/log1p) Returns the natural logarithm (㏒e; also ㏑) of `1 + x` for the number `x`.
[`Math.log10()`](math/log10) Returns the base-10 logarithm of `x`.
[`Math.log2()`](math/log2) Returns the base-2 logarithm of `x`.
[`Math.max()`](math/max) Returns the largest of zero or more numbers.
[`Math.min()`](math/min) Returns the smallest of zero or more numbers.
[`Math.pow()`](math/pow) Returns base `x` to the exponent power `y` (that is, `x``y`).
[`Math.random()`](math/random) Returns a pseudo-random number between `0` and `1`.
[`Math.round()`](math/round) Returns the value of the number `x` rounded to the nearest integer.
[`Math.sign()`](math/sign) Returns the sign of the `x`, indicating whether `x` is positive, negative, or zero.
[`Math.sin()`](math/sin) Returns the sine of `x`.
[`Math.sinh()`](math/sinh) Returns the hyperbolic sine of `x`.
[`Math.sqrt()`](math/sqrt) Returns the positive square root of `x`.
[`Math.tan()`](math/tan) Returns the tangent of `x`.
[`Math.tanh()`](math/tanh) Returns the hyperbolic tangent of `x`.
[`Math.trunc()`](math/trunc) Returns the integer portion of `x`, removing any fractional digits.
Examples
--------
### Converting between degrees and radians
The trigonometric functions `sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, and `atan2()` expect (and return) angles in *radians*.
Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:
```
function degToRad(degrees) {
return degrees \* (Math.PI / 180);
}
function radToDeg(rad) {
return rad / (Math.PI / 180);
}
```
### Calculating the height of an equilateral triangle
If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae *length of the adjacent multiplied by the tangent of the angle is equal to the opposite.*
In JavaScript, we can do this with the following:
```
50 \* Math.tan(degToRad(60))
```
We use our `degToRad()` function to convert 60 degrees to radians, as [`Math.tan()`](math/tan) expects an input value in radians.
### Returning a random integer between two bounds
This can be achieved with a combination of [`Math.random()`](math/random) and [`Math.floor()`](math/floor):
```
function random(min, max) {
const num = Math.floor(Math.random() \* (max - min + 1)) + min;
return num;
}
random(1, 10);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-math-object](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math-object) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `E` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `LN10` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `LN2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `LOG10E` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `LOG2E` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `PI` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `SQRT1_2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `SQRT2` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Math` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `abs` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `acos` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `acosh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `asin` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `asinh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `atan` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `atan2` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `atanh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `cbrt` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `ceil` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `clz32` | 38 | 12 | 31 | No | 25 | 7 | 38 | 38 | 31 | 25 | 7 | 3.0 | 1.0 | 0.12.0 |
| `cos` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `cosh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `exp` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `expm1` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `floor` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `fround` | 38 | 12 | 26 | No | 25 | 8 | 38 | 38 | 26 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `hypot` | 38 | 12 | 27 | No | 25 | 8 | 38 | 38 | 27 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `imul` | 28 | 12 | 20 | No | 16 | 7 | 4.4 | 28 | 20 | 15 | 7 | 1.5 | 1.0 | 0.12.0 |
| `log` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `log10` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `log1p` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `log2` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `max` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `min` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `pow` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `random` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `round` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sign` | 38 | 12 | 25 | No | 25 | 9 | 38 | 38 | 25 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `sin` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `sinh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `sqrt` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `tan` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `tanh` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `trunc` | 38 | 12 | 25 | No | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Number`](number)
| programming_docs |
javascript GeneratorFunction GeneratorFunction
=================
In JavaScript, every generator function is actually a `GeneratorFunction` object. There is no global object with the name `GeneratorFunction`, but you can create a `GeneratorFunction()` constructor using the following code:
```
const GeneratorFunction = function\* () {}.constructor;
```
Try it
------
Constructor
-----------
[`GeneratorFunction()`](generatorfunction/generatorfunction) Creates a new `GeneratorFunction` object.
Instance properties
-------------------
*Also inherits instance properties from its parent [`Function`](function)*.
`GeneratorFunction.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"GeneratorFunction"`. This property is used in [`Object.prototype.toString()`](object/tostring).
`GeneratorFunction.prototype.prototype` All generator functions share the same [`prototype`](function/prototype) property, which is [`Generator.prototype`](generator). When the function is called, this object becomes the prototype of the returned generator object. A generator function instance can also create its own `prototype` property, which will be used instead of `GeneratorFunction.prototype.prototype`.
Instance methods
----------------
*Inherits instance methods from its parent [`Function`](function)*.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generatorfunction-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generatorfunction-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `GeneratorFunction` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `GeneratorFunction` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [`function*` declaration](../statements/function*)
* [`function*` expression](../operators/function*)
* [`Function`](function)
* [`AsyncFunction`](asyncfunction)
* [`AsyncGeneratorFunction`](asyncgeneratorfunction)
* [Functions](../functions)
javascript escape() escape()
========
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** `escape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use [`encodeURIComponent()`](encodeuricomponent) or [`encodeURI()`](encodeuri) if possible.
The `escape()` function computes a new string in which certain characters have been replaced by hexadecimal escape sequences.
Syntax
------
```
escape(str)
```
### Parameters
`str` A string to be encoded.
### Return value
A new string in which certain characters have been escaped.
Description
-----------
`escape()` is a function property of the global object.
The `escape()` function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, \_) and `@*_+-./`. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number in the format `%XX`, left-padded with 0 if necessary. Otherwise, it is represented by a four-digit hexadecimal number in the format `%uXXXX`, left-padded with 0 if necessary.
**Note:** This function was used mostly for URL encoding and is partly based on the escape format in [RFC 1738](https://datatracker.ietf.org/doc/html/rfc1738). The escape format is *not* an [escape sequence](string#escape_sequences) in string literals. You can replace `%XX` with `\xXX` and `%uXXXX` with `\uXXXX` to get a string containing actual string-literal escape sequences.
Examples
--------
### Using escape()
```
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"
// special characters
escape("@\*\_+-./"); // "@\*\_+-./"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-escape-string](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-escape-string) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `escape` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `escape` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`encodeURI`](encodeuri)
* [`encodeURIComponent`](encodeuricomponent)
* [`unescape`](unescape)
javascript Set Set
===
The `Set` object lets you store unique values of any type, whether [primitive values](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) or object references.
Description
-----------
`Set` objects are collections of values. A value in the `Set` **may only occur once**; it is unique in the `Set`'s collection. You can iterate through the elements of a set in insertion order. The *insertion order* corresponds to the order in which each element was inserted into the set by the [`add()`](set/add) method successfully (that is, there wasn't an identical element already in the set when `add()` was called).
The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).
### Value equality
Value equality is based on the [SameValueZero](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) algorithm. (It used to use [SameValue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is), which treated `0` and `-0` as different. Check [browser compatibility](#browser_compatibility).) This means [`NaN`](nan) is considered the same as `NaN` (even though `NaN !== NaN`) and all other values are considered equal according to the semantics of the `===` operator.
### Performance
The `Set` [`has`](set/has) method checks if a value is in a `Set` object, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the `Set` object. In particular, it is, on average, faster than the [`Array.prototype.includes`](array/includes) method when an `Array` object has a `length` equal to a `Set` object's `size`.
Constructor
-----------
[`Set()`](set/set) Creates a new `Set` object.
Static properties
-----------------
[`get Set[@@species]`](set/@@species) The constructor function that is used to create derived objects.
Instance properties
-------------------
`Set.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Set"`. This property is used in [`Object.prototype.toString()`](object/tostring).
[`Set.prototype.size`](set/size) Returns the number of values in the `Set` object.
Instance methods
----------------
[`Set.prototype.add()`](set/add) Inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`.
[`Set.prototype.clear()`](set/clear) Removes all elements from the `Set` object.
[`Set.prototype.delete()`](set/delete) Removes the element associated to the `value` and returns a boolean asserting whether an element was successfully removed or not. `Set.prototype.has(value)` will return `false` afterwards.
[`Set.prototype.has()`](set/has) Returns a boolean asserting whether an element is present with the given value in the `Set` object or not.
[`Set.prototype[@@iterator]()`](set/@@iterator) Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order.
[`Set.prototype.values()`](set/values) Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order.
[`Set.prototype.keys()`](set/keys) An alias for [`Set.prototype.values()`](set/values).
[`Set.prototype.entries()`](set/entries) Returns a new iterator object that contains `[value, value]` for each element in the `Set` object, in insertion order.
This is similar to the [`Map`](map) object, so that each entry's *key* is the same as its *value* for a `Set`.
[`Set.prototype.forEach()`](set/foreach) Calls `callbackFn` once for each value present in the `Set` object, in insertion order. If a `thisArg` parameter is provided, it will be used as the `this` value for each invocation of `callbackFn`.
Examples
--------
### Using the Set object
```
const mySet1 = new Set()
mySet1.add(1) // Set(1) { 1 }
mySet1.add(5) // Set(2) { 1, 5 }
mySet1.add(5) // Set(2) { 1, 5 }
mySet1.add('some text') // Set(3) { 1, 5, 'some text' }
const o = {a: 1, b: 2}
mySet1.add(o)
mySet1.add({a: 1, b: 2}) // o is referencing a different object, so this is okay
mySet1.has(1) // true
mySet1.has(3) // false, since 3 has not been added to the set
mySet1.has(5) // true
mySet1.has(Math.sqrt(25)) // true
mySet1.has('Some Text'.toLowerCase()) // true
mySet1.has(o) // true
mySet1.size // 5
mySet1.delete(5) // removes 5 from the set
mySet1.has(5) // false, 5 has been removed
mySet1.size // 4, since we just removed one value
mySet1.add(5) // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletion
console.log(mySet1) // Set(5) { 1, "some text", {…}, {…}, 5 }
```
### Iterating Sets
Iteration of sets visits elements in insertion order.
```
for (const item of mySet1) {
console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5
for (const item of mySet1.keys()) {
console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5
for (const item of mySet1.values()) {
console.log(item);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5
// key and value are the same here
for (const [key, value] of mySet1.entries()) {
console.log(key);
}
// 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5
// Convert Set object to an Array object, with Array.from
const myArr = Array.from(mySet1) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}, 5]
// the following will also work if run in an HTML document
mySet1.add(document.body)
mySet1.has(document.querySelector('body')) // true
// converting between Set and Array
const mySet2 = new Set([1, 2, 3, 4]);
console.log(mySet2.size); // 4
console.log([...mySet2]); // [1, 2, 3, 4]
// intersect can be simulated via
const intersection = new Set([...mySet1].filter((x) => mySet2.has(x)));
// difference can be simulated via
const difference = new Set([...mySet1].filter((x) => !mySet2.has(x)));
// Iterate set entries with forEach()
mySet2.forEach((value) => {
console.log(value);
});
// 1
// 2
// 3
// 4
```
### Implementing basic set operations
```
function isSuperset(set, subset) {
for (const elem of subset) {
if (!set.has(elem)) {
return false;
}
}
return true;
}
function union(setA, setB) {
const _union = new Set(setA);
for (const elem of setB) {
_union.add(elem);
}
return _union;
}
function intersection(setA, setB) {
const _intersection = new Set();
for (const elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem);
}
}
return _intersection;
}
function symmetricDifference(setA, setB) {
const _difference = new Set(setA);
for (const elem of setB) {
if (_difference.has(elem)) {
_difference.delete(elem);
} else {
_difference.add(elem);
}
}
return _difference;
}
function difference(setA, setB) {
const _difference = new Set(setA);
for (const elem of setB) {
_difference.delete(elem);
}
return _difference;
}
// Examples
const setA = new Set([1, 2, 3, 4])
const setB = new Set([2, 3])
const setC = new Set([3, 4, 5, 6])
isSuperset(setA, setB) // returns true
union(setA, setC) // returns Set {1, 2, 3, 4, 5, 6}
intersection(setA, setC) // returns Set {3, 4}
symmetricDifference(setA, setC) // returns Set {1, 2, 5, 6}
difference(setA, setC) // returns Set {1, 2}
```
### Relation with Array objects
```
const myArray = ['value1', 'value2', 'value3'];
// Use the regular Set constructor to transform an Array into a Set
const mySet = new Set(myArray);
mySet.has('value1') // returns true
// Use the spread syntax to transform a set into an Array.
console.log([...mySet]); // Will show you exactly the same Array as myArray
```
### Remove duplicate elements from the array
```
// Use to remove duplicate elements from the array
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)])
// [2, 3, 4, 5, 6, 7, 32]
```
### Relation with Strings
```
const text = 'India';
const mySet = new Set(text); // Set(5) {'I', 'n', 'd', 'i', 'a'}
mySet.size // 5
//case sensitive & duplicate omission
new Set("Firefox") // Set(7) { "F", "i", "r", "e", "f", "o", "x" }
new Set("firefox") // Set(6) { "f", "i", "r", "e", "o", "x" }
```
### Use Set to ensure the uniqueness of a list of values
```
const array = Array
.from(document.querySelectorAll('[id]'))
.map((e) => e.id);
const set = new Set(array);
console.assert(set.size === array.length);
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-set-objects](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 43 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 30 | 9 | 43 | 43 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 30 | 9 | 4.0 | 1.0 | 0.12.0 |
| `@@species` | 51 | 13 | 41 | No | 38 | 10 | 51 | 51 | 41 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
| `Set` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `Set` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `add` | 38 | 12 | 13 | 11
Returns 'undefined' instead of the 'Set' object. | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `clear` | 38 | 12 | 19 | 11 | 25 | 8 | 38 | 38 | 19 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `delete` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `entries` | 38 | 12 | 24 | No | 25 | 8 | 38 | 38 | 24 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `forEach` | 38 | 12 | 25 | 11 | 25 | 8 | 38 | 38 | 25 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `has` | 38 | 12 | 13 | 11 | 25 | 8 | 38 | 38 | 14 | 25 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `key_equality_for_zeros` | 38 | 12 | 29 | No | 25 | 9 | 38 | 38 | 29 | 25 | 9 | 3.0 | 1.0 | 4.0.0 |
| `size` | 38 | 12 | 19
From Firefox 13 to Firefox 18, the `size` property was implemented as a `Set.prototype.size()` method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification. | 11 | 25 | 8 | 38 | 38 | 19
From Firefox 13 to Firefox 18, the `size` property was implemented as a `Set.prototype.size()` method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification. | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
| `values` | 38
38 | 12
12 | 24
24 | No | 25
25 | 8
8 | 38
38 | 38
38 | 24
24 | 25
25 | 8
8 | 3.0
3.0 | 1.0
1.0 | 0.12.0
0.12.0 |
See also
--------
* [Polyfill of `Set` in `core-js`](https://github.com/zloirock/core-js#set)
* [`Map`](map)
* [`WeakMap`](weakmap)
* [`WeakSet`](weakset)
javascript Uint16Array Uint16Array
===========
The `Uint16Array` typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Uint16Array()`](uint16array/uint16array) Creates a new `Uint16Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Uint16Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `2` in the case of `Uint16Array`.
[`Uint16Array.name`](typedarray/name) Returns the string value of the constructor name. `"Uint16Array"` in the case of `Uint16Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Uint16Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `2` in the case of a `Uint16Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a Uint16Array
```
// From a length
const uint16 = new Uint16Array(2);
uint16[0] = 42;
console.log(uint16[0]); // 42
console.log(uint16.length); // 2
console.log(uint16.BYTES\_PER\_ELEMENT); // 2
// From an array
const x = new Uint16Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint16Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Uint16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uint16FromIterable = new Uint16Array(iterable);
console.log(uint16FromIterable);
// Uint16Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint16Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Uint16Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Uint16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
| programming_docs |
javascript Float32Array Float32Array
============
The `Float32Array` typed array represents an array of 32-bit floating point numbers (corresponding to the C `float` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Float32Array()`](float32array/float32array) Creates a new `Float32Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Float32Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of `Float32Array`.
[`Float32Array.name`](typedarray/name) Returns the string value of the constructor name. `"Float32Array"` in the case of `Float32Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Float32Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `4` in the case of a `Float32Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a `Float32Array`
```
// From a length
const float32 = new Float32Array(2);
float32[0] = 42;
console.log(float32[0]); // 42
console.log(float32.length); // 2
console.log(float32.BYTES\_PER\_ELEMENT); // 4
// From an array
const x = new Float32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Float32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Float32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const float32FromIterable = new Float32Array(iterable);
console.log(float32FromIterable);
// Float32Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Float32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Float32Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Float32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript Date Date
====
JavaScript `Date` objects represent a single moment in time in a platform-independent format. `Date` objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the *epoch*).
**Note:** TC39 is working on [Temporal](https://tc39.es/proposal-temporal/docs/index.html), a new Date/Time API. Read more about it on the [Igalia blog](https://blogs.igalia.com/compilers/2020/06/23/dates-and-times-in-javascript/). It is not yet ready for production use!
Description
-----------
### The ECMAScript epoch and timestamps
A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since the [ECMAScript epoch](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-time-values-and-time-range), which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the [UNIX epoch](https://en.wikipedia.org/wiki/Unix_time)).
**Note:** It's important to keep in mind that while the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.
It should be noted that the maximum `Date` is not of the same value as the maximum safe integer (`Number.MAX_SAFE_INTEGER` is 9,007,199,254,740,991). Instead, it is defined in ECMA-262 that a maximum of ±100,000,000 (one hundred million) days relative to January 1, 1970 UTC (that is, April 20, 271821 BCE ~ September 13, 275760 CE) can be represented by the standard `Date` object (equivalent to ±8,640,000,000,000,000 milliseconds).
### Date format and time zone conversions
There are several methods available to obtain a date in various formats, as well as to perform time zone conversions. Particularly useful are the functions that output the date and time in Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. (This time is historically known as *Greenwich Mean Time*, as UTC lies along the meridian that includes London—and nearby Greenwich—in the United Kingdom.) The user's device provides the local time.
In addition to methods to read and alter individual components of the local date and time (such as [`getDay()`](date/getday) and [`setHours()`](date/sethours)), there are also versions of the same methods that read and manipulate the date and time using UTC (such as [`getUTCDay()`](date/getutcday) and [`setUTCHours()`](date/setutchours)).
Constructor
-----------
[`Date()`](date/date) When called as a function, returns a string representation of the current date and time. All arguments are ignored. The result is the same as executing `new Date().toString()`.
[`new Date()`](date/date) When called as a constructor, returns a new `Date` object.
Static methods
--------------
[`Date.now()`](date/now) Returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
[`Date.parse()`](date/parse) Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.
**Note:** Parsing of strings with `Date.parse` is strongly discouraged due to browser differences and inconsistencies.
[`Date.UTC()`](date/utc) Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
Instance methods
----------------
[`Date.prototype.getDate()`](date/getdate) Returns the day of the month (`1` – `31`) for the specified date according to local time.
[`Date.prototype.getDay()`](date/getday) Returns the day of the week (`0` – `6`) for the specified date according to local time.
[`Date.prototype.getFullYear()`](date/getfullyear) Returns the year (4 digits for 4-digit years) of the specified date according to local time.
[`Date.prototype.getHours()`](date/gethours) Returns the hour (`0` – `23`) in the specified date according to local time.
[`Date.prototype.getMilliseconds()`](date/getmilliseconds) Returns the milliseconds (`0` – `999`) in the specified date according to local time.
[`Date.prototype.getMinutes()`](date/getminutes) Returns the minutes (`0` – `59`) in the specified date according to local time.
[`Date.prototype.getMonth()`](date/getmonth) Returns the month (`0` – `11`) in the specified date according to local time.
[`Date.prototype.getSeconds()`](date/getseconds) Returns the seconds (`0` – `59`) in the specified date according to local time.
[`Date.prototype.getTime()`](date/gettime) Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
[`Date.prototype.getTimezoneOffset()`](date/gettimezoneoffset) Returns the time-zone offset in minutes for the current locale.
[`Date.prototype.getUTCDate()`](date/getutcdate) Returns the day (date) of the month (`1` – `31`) in the specified date according to universal time.
[`Date.prototype.getUTCDay()`](date/getutcday) Returns the day of the week (`0` – `6`) in the specified date according to universal time.
[`Date.prototype.getUTCFullYear()`](date/getutcfullyear) Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
[`Date.prototype.getUTCHours()`](date/getutchours) Returns the hours (`0` – `23`) in the specified date according to universal time.
[`Date.prototype.getUTCMilliseconds()`](date/getutcmilliseconds) Returns the milliseconds (`0` – `999`) in the specified date according to universal time.
[`Date.prototype.getUTCMinutes()`](date/getutcminutes) Returns the minutes (`0` – `59`) in the specified date according to universal time.
[`Date.prototype.getUTCMonth()`](date/getutcmonth) Returns the month (`0` – `11`) in the specified date according to universal time.
[`Date.prototype.getUTCSeconds()`](date/getutcseconds) Returns the seconds (`0` – `59`) in the specified date according to universal time.
[`Date.prototype.getYear()`](date/getyear) Deprecated
Returns the year (usually 2–3 digits) in the specified date according to local time. Use [`getFullYear()`](date/getfullyear) instead.
[`Date.prototype.setDate()`](date/setdate) Sets the day of the month for a specified date according to local time.
[`Date.prototype.setFullYear()`](date/setfullyear) Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.
[`Date.prototype.setHours()`](date/sethours) Sets the hours for a specified date according to local time.
[`Date.prototype.setMilliseconds()`](date/setmilliseconds) Sets the milliseconds for a specified date according to local time.
[`Date.prototype.setMinutes()`](date/setminutes) Sets the minutes for a specified date according to local time.
[`Date.prototype.setMonth()`](date/setmonth) Sets the month for a specified date according to local time.
[`Date.prototype.setSeconds()`](date/setseconds) Sets the seconds for a specified date according to local time.
[`Date.prototype.setTime()`](date/settime) Sets the [`Date`](date) object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.
[`Date.prototype.setUTCDate()`](date/setutcdate) Sets the day of the month for a specified date according to universal time.
[`Date.prototype.setUTCFullYear()`](date/setutcfullyear) Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.
[`Date.prototype.setUTCHours()`](date/setutchours) Sets the hour for a specified date according to universal time.
[`Date.prototype.setUTCMilliseconds()`](date/setutcmilliseconds) Sets the milliseconds for a specified date according to universal time.
[`Date.prototype.setUTCMinutes()`](date/setutcminutes) Sets the minutes for a specified date according to universal time.
[`Date.prototype.setUTCMonth()`](date/setutcmonth) Sets the month for a specified date according to universal time.
[`Date.prototype.setUTCSeconds()`](date/setutcseconds) Sets the seconds for a specified date according to universal time.
[`Date.prototype.setYear()`](date/setyear) Deprecated
Sets the year (usually 2–3 digits) for a specified date according to local time. Use [`setFullYear()`](date/setfullyear) instead.
[`Date.prototype.toDateString()`](date/todatestring) Returns the "date" portion of the [`Date`](date) as a human-readable string like `'Thu Apr 12 2018'`.
[`Date.prototype.toISOString()`](date/toisostring) Converts a date to a string following the ISO 8601 Extended Format.
[`Date.prototype.toJSON()`](date/tojson) Returns a string representing the [`Date`](date) using [`toISOString()`](date/toisostring). Intended for use by [`JSON.stringify()`](json/stringify).
[`Date.prototype.toLocaleDateString()`](date/tolocaledatestring) Returns a string with a locality sensitive representation of the date portion of this date based on system settings.
[`Date.prototype.toLocaleString()`](date/tolocalestring) Returns a string with a locality-sensitive representation of this date. Overrides the [`Object.prototype.toLocaleString()`](object/tolocalestring) method.
[`Date.prototype.toLocaleTimeString()`](date/tolocaletimestring) Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.
[`Date.prototype.toString()`](date/tostring) Returns a string representing the specified [`Date`](date) object. Overrides the [`Object.prototype.toString()`](object/tostring) method.
[`Date.prototype.toTimeString()`](date/totimestring) Returns the "time" portion of the [`Date`](date) as a human-readable string.
[`Date.prototype.toUTCString()`](date/toutcstring) Converts a date to a string using the UTC timezone.
[`Date.prototype.valueOf()`](date/valueof) Returns the primitive value of a [`Date`](date) object. Overrides the [`Object.prototype.valueOf()`](object/valueof) method.
Examples
--------
### Several ways to create a Date object
The following examples show several ways to create JavaScript dates:
**Note:** When parsing date strings with the `Date` constructor (and `Date.parse`, they are equivalent), always make sure that the input conforms to the [ISO 8601 format](https://tc39.es/ecma262/#sec-date-time-string-format) (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.
```
const today = new Date();
const birthday = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes
const birthday2 = new Date("1995-12-17T03:24:00"); // This is ISO8601-compliant and will work reliably
const birthday3 = new Date(1995, 11, 17); // the month is 0-indexed
const birthday4 = new Date(1995, 11, 17, 3, 24, 0);
const birthday5 = new Date(628021800000); // passing epoch timestamp
```
### Formats of toString method return values
```
const date = new Date("2020-05-12T23:50:21.817Z");
date.toString(); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)
date.toDateString(); // Tue May 12 2020
date.toTimeString(); // 18:50:21 GMT-0500 (Central Daylight Time)
date.toISOString(); // 2020-05-12T23:50:21.817Z
date.toUTCString(); // Tue, 12 May 2020 23:50:21 GMT
date.toJSON(); // 2020-05-12T23:50:21.817Z
date.toLocaleString(); // 5/12/2020, 6:50:21 PM
date.toLocaleDateString(); // 5/12/2020
date.toLocaleTimeString(); // 6:50:21 PM
```
### To get Date, Month and Year or Time
```
const date = new Date();
const [month, day, year] = [
date.getMonth(),
date.getDate(),
date.getFullYear(),
];
const [hour, minutes, seconds] = [
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
```
### Interpretation of two-digit years
`new Date()` exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a `new Date()` call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the year `1900`, but in other cases, as an offset from the year `2000`.
```
let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date = new Date(22, 1); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
date = new Date("2/1/22"); // Tue Feb 01 2022 00:00:00 GMT+0000 (GMT)
// Legacy method; always interprets two-digit year values as relative to 1900
date.setYear(98);
date.toString(); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date.setYear(22);
date.toString(); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
```
So, to create and get dates between the years `0` and `99`, instead use the preferred [`setFullYear()`](date/setfullyear) and [`getFullYear()`](date/getfullyear) methods:.
```
// Preferred method; never interprets any value as being a relative offset,
// but instead uses the year value as-is
date.setFullYear(98);
date.getFullYear(); // 98 (not 1998)
date.setFullYear(22);
date.getFullYear(); // 22 (not 1922, not 2022)
```
### Calculating elapsed time
The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.
Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted.
```
// Using Date objects
const start = Date.now();
// The event to time goes here:
doSomethingForALongTime();
const end = Date.now();
const elapsed = end - start; // elapsed time in milliseconds
```
```
// Using built-in methods
const start = new Date();
// The event to time goes here:
doSomethingForALongTime();
const end = new Date();
const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
```
```
// To test a function and get back its return
function printElapsedTime(testFn) {
const startTime = Date.now();
const result = testFn();
const endTime = Date.now();
console.log(`Elapsed time: ${String(endTime - startTime)} milliseconds`);
return result;
}
const yourFunctionReturn = printElapsedTime(yourFunction);
```
**Note:** In browsers that support the [Web Performance API](https://developer.mozilla.org/en-US/docs/Web/API/performance_property)'s high-resolution time feature, [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) can provide more reliable and precise measurements of elapsed time than [`Date.now()`](date/now).
### Get the number of seconds since the ECMAScript Epoch
```
const seconds = Math.floor(Date.now() / 1000);
```
In this case, it's important to return only an integer—so a simple division won't do. It's also important to only return actually elapsed seconds. (That's why this code uses [`Math.floor()`](math/floor), and *not* [`Math.round()`](math/round).)
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-date-objects](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@toPrimitive` | 47 | 15 | 44 | No | 34 | 10 | 47 | 47 | 44 | 34 | 10 | 5.0 | 1.0 | 6.0.0 |
| `Date` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `UTC` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Date` | 1 | 12 | 1 | 3
The [ISO8601 Date Format](https://en.wikipedia.org/wiki/ISO_8601) is not supported in Internet Explorer 8 or earlier. | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getDate` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getDay` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getHours` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getMinutes` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getMonth` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getSeconds` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getTime` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getTimezoneOffset` | 1 | 12 | 1 | 5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCDate` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCDay` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCHours` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCMinutes` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCMonth` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getUTCSeconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `getYear` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `now` | 1 | 12 | 1 | 9 | 10.5 | 4 | 4.4 | 18 | 4 | 14 | 4 | 1.0 | 1.0 | 0.10.0 |
| `parse` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setDate` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setHours` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setMinutes` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setMonth` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setSeconds` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setTime` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCDate` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCFullYear` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCHours` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCMilliseconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCMinutes` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCMonth` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setUTCSeconds` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `setYear` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toDateString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toGMTString` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toISOString` | 3 | 12 | 1 | 9 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 3.2 | 1.0 | 1.0 | 0.10.0 |
| `toJSON` | 3 | 12 | 1 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 3.2 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleDateString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleString` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toLocaleTimeString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 3 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toTimeString` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `toUTCString` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `valueOf` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Date()`](date/date) constructor
| programming_docs |
javascript Error Error
=====
`Error` objects are thrown when runtime errors occur. The `Error` object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.
Description
-----------
Runtime errors result in new `Error` objects being created and thrown.
`Error` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
### Error types
Besides the generic `Error` constructor, there are other core error constructors in JavaScript. For client-side exceptions, see [Exception handling statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements).
[`EvalError`](evalerror) Creates an instance representing an error that occurs regarding the global function [`eval()`](eval).
[`RangeError`](rangeerror) Creates an instance representing an error that occurs when a numeric variable or parameter is outside its valid range.
[`ReferenceError`](referenceerror) Creates an instance representing an error that occurs when de-referencing an invalid reference.
[`SyntaxError`](syntaxerror) Creates an instance representing a syntax error.
[`TypeError`](typeerror) Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
[`URIError`](urierror) Creates an instance representing an error that occurs when [`encodeURI()`](encodeuri) or [`decodeURI()`](decodeuri) are passed invalid parameters.
[`AggregateError`](aggregateerror) Creates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example by [`Promise.any()`](promise/any).
[`InternalError`](internalerror) Non-standard
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
Constructor
-----------
[`Error()`](error/error) Creates a new `Error` object.
Static methods
--------------
`Error.captureStackTrace()` Non-standard
A non-standard V8 function that creates the [`stack`](error/stack) property on an Error instance.
`Error.stackTraceLimit` Non-standard
A non-standard V8 numerical property that limits how many stack frames to include in an error stacktrace.
`Error.prepareStackTrace()` Non-standard Optional
A non-standard V8 function that, if provided by usercode, is called by the V8 JavaScript engine for thrown exceptions, allowing the user to provide custom formatting for stacktraces.
Instance properties
-------------------
[`Error.prototype.message`](error/message) Error message. For user-created `Error` objects, this is the string provided as the constructor's first argument.
[`Error.prototype.name`](error/name) Error name. This is determined by the constructor function.
[`Error.prototype.cause`](error/cause) Error cause indicating the reason why the current error is thrown — usually another caught error. For user-created `Error` objects, this is the value provided as the `cause` property of the constructor's second argument.
[`Error.prototype.fileName`](error/filename) Non-standard
A non-standard Mozilla property for the path to the file that raised this error.
[`Error.prototype.lineNumber`](error/linenumber) Non-standard
A non-standard Mozilla property for the line number in the file that raised this error.
[`Error.prototype.columnNumber`](error/columnnumber) Non-standard
A non-standard Mozilla property for the column number in the line that raised this error.
[`Error.prototype.stack`](error/stack) Non-standard
A non-standard property for a stack trace.
Instance methods
----------------
[`Error.prototype.toString()`](error/tostring) Returns a string representing the specified object. Overrides the [`Object.prototype.toString()`](object/tostring) method.
Examples
--------
### Throwing a generic error
Usually you create an `Error` object with the intention of raising it using the [`throw`](../statements/throw) keyword. You can handle the error using the [`try...catch`](../statements/try...catch) construct:
```
try {
throw new Error("Whoops!");
} catch (e) {
console.error(`${e.name}: ${e.message}`);
}
```
### Handling a specific error type
You can choose to handle only specific error types by testing the error type with the error's [`constructor`](object/constructor) property or, if you're writing for modern JavaScript engines, [`instanceof`](../operators/instanceof) keyword:
```
try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
console.error(`${e.name}: ${e.message}`);
} else if (e instanceof RangeError) {
console.error(`${e.name}: ${e.message}`);
}
// etc.
else {
// If none of our cases matched leave the Error unhandled
throw e;
}
}
```
### Differentiate between similar errors
Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e. with the same type and message).
If you don't have control over the original errors that are thrown, one option is to catch them and throw new `Error` objects that have more specific messages. The original error should be passed to the new `Error` in the constructor's [`options`](error/error#options) parameter as its `cause` property. This ensures that the original error and stack trace are available to higher-level try/catch blocks.
The example below shows this for two methods that would otherwise fail with similar errors (`doFailSomeWay()` and `doFailAnotherWay()`):
```
function doWork() {
try {
doFailSomeWay();
} catch (err) {
throw new Error("Failed in some way", { cause: err });
}
try {
doFailAnotherWay();
} catch (err) {
throw new Error("Failed in another way", { cause: err });
}
}
try {
doWork();
} catch (err) {
switch (err.message) {
case "Failed in some way":
handleFailSomeWay(err.cause);
break;
case "Failed in another way":
handleFailAnotherWay(err.cause);
break;
}
}
```
**Note:** If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See the [error cause page](error/cause#providing_structured_data_as_the_error_cause) for an example.
[Custom error types](#custom_error_types) can also use the [`cause`](#error.prototype.cause) property, provided the subclasses' constructor passes the `options` parameter when calling `super()`. The `Error()` base class constructor will read `options.cause` and define the `cause` property on the new error instance.
```
class MyError extends Error {
constructor(message, options) {
// Need to pass `options` as the second parameter to install the "cause" property.
super(message, options);
}
}
console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
```
### Custom error types
You might want to define your own error types deriving from `Error` to be able to `throw new MyError()` and use `instanceof MyError` to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code.
See ["What's a good way to extend Error in JavaScript?"](https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript) on StackOverflow for an in-depth discussion.
**Warning:** Builtin subclassing cannot be reliably transpiled to pre-ES6 code, because there's no way to construct the base class with a particular `new.target` without [`Reflect.construct()`](reflect/construct). You need [additional configuration](https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend) or manually call [`Object.setPrototypeOf(this, CustomError.prototype)`](object/setprototypeof) at the end of the constructor; otherwise, the constructed instance will not be a `CustomError` instance. See [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work) for more information.
**Note:** Some browsers include the `CustomError` constructor in the stack trace when using ES2015 classes.
```
class CustomError extends Error {
constructor(foo = "bar", ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params);
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = "CustomError";
// Custom debugging information
this.foo = foo;
this.date = new Date();
}
}
try {
throw new CustomError("baz", "bazMessage");
} catch (e) {
console.error(e.name); // CustomError
console.error(e.foo); // baz
console.error(e.message); // bazMessage
console.error(e.stack); // stacktrace
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-error-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Error` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Error` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `cause` | 93 | 93 | 91 | No | No | 15 | 93 | 93 | 91 | No | 15 | 17.0 | 1.13 | 16.9.0 |
| `columnNumber` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `fileName` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `lineNumber` | No | No | 1 | No | No | No | No | No | 4 | No | No | No | No | No |
| `message` | 1 | 12 | 1 | 6 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `name` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serialized properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 additionally supports serialization of `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serialized properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 additionally supports serialization of `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
| `stack` | 3 | 12 | 1 | 10 | 10.5 | 6 | ≤37 | 18 | 4 | 11 | 6 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 6 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [A polyfill of `Error`](https://github.com/zloirock/core-js#ecmascript-error) with modern behavior like support `cause` is available in [`core-js`](https://github.com/zloirock/core-js)
* [`throw`](../statements/throw)
* [`try...catch`](../statements/try...catch)
* The [V8 documentation](https://v8.dev/docs/stack-trace-api) for `Error.captureStackTrace()`, `Error.stackTraceLimit`, and `Error.prepareStackTrace()`.
javascript decodeURIComponent() decodeURIComponent()
====================
The `decodeURIComponent()` function decodes a Uniform Resource Identifier (URI) component previously created by [`encodeURIComponent()`](encodeuricomponent) or by a similar routine.
Try it
------
Syntax
------
```
decodeURIComponent(encodedURI)
```
### Parameters
`encodedURI` An encoded component of a Uniform Resource Identifier.
### Return value
A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component.
### Exceptions
[`URIError`](urierror) Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.
Description
-----------
`decodeURIComponent()` is a function property of the global object.
`decodeURIComponent()` uses the same decoding algorithm as described in [`decodeURI()`](decodeuri). It decodes *all* escape sequences, including those that are not created by [`encodeURIComponent`](encodeuricomponent), like `-.!~*'()`.
Examples
--------
### Decoding a Cyrillic URL component
```
decodeURIComponent("JavaScript\_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript\_шеллы"
```
### Catching errors
```
try {
const a = decodeURIComponent("%E0%A4%A");
} catch (e) {
console.error(e);
}
// URIError: malformed URI sequence
```
### Decoding query parameters from a URL
`decodeURIComponent()` cannot be used directly to parse query parameters from a URL. It needs a bit of preparation.
```
function decodeQueryParam(p) {
return decodeURIComponent(p.replace(/\+/g, " "));
}
decodeQueryParam("search+query%20%28correct%29");
// 'search query (correct)'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-decodeuricomponent-encodeduricomponent](https://tc39.es/ecma262/multipage/global-object.html#sec-decodeuricomponent-encodeduricomponent) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `decodeURIComponent` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`decodeURI`](decodeuri)
* [`encodeURI`](encodeuri)
* [`encodeURIComponent`](encodeuricomponent)
javascript SyntaxError SyntaxError
===========
The `SyntaxError` object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
`SyntaxError` is a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) or copied between [Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage).
Constructor
-----------
[`SyntaxError()`](syntaxerror/syntaxerror) Creates a new `SyntaxError` object.
Instance properties
-------------------
[`SyntaxError.prototype.message`](error/message) Error message. Inherited from [`Error`](error).
[`SyntaxError.prototype.name`](error/name) Error name. Inherited from [`Error`](error).
[`SyntaxError.prototype.cause`](error/cause) Error cause. Inherited from [`Error`](error).
[`SyntaxError.prototype.fileName`](error/filename) Non-standard
Path to file that raised this error. Inherited from [`Error`](error).
[`SyntaxError.prototype.lineNumber`](error/linenumber) Non-standard
Line number in file that raised this error. Inherited from [`Error`](error).
[`SyntaxError.prototype.columnNumber`](error/columnnumber) Non-standard
Column number in line that raised this error. Inherited from [`Error`](error).
[`SyntaxError.prototype.stack`](error/stack) Non-standard
Stack trace. Inherited from [`Error`](error).
Examples
--------
### Catching a SyntaxError
```
try {
eval("hoo bar");
} catch (e) {
console.error(e instanceof SyntaxError);
console.error(e.message);
console.error(e.name);
console.error(e.fileName);
console.error(e.lineNumber);
console.error(e.columnNumber);
console.error(e.stack);
}
```
### Creating a SyntaxError
```
try {
throw new SyntaxError("Hello", "someFile.js", 10);
} catch (e) {
console.error(e instanceof SyntaxError); // true
console.error(e.message); // Hello
console.error(e.name); // SyntaxError
console.error(e.fileName); // someFile.js
console.error(e.lineNumber); // 10
console.error(e.columnNumber); // 0
console.error(e.stack); // @debugger eval code:3:9
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-syntaxerror](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-native-error-types-used-in-this-standard-syntaxerror) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `SyntaxError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `SyntaxError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `serializable_object` | 77 | 79 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | No | 64 | No | 77 | 77 | 103
["Version 103 serializable properties: `name`, `message`, `cause`, `fileName`, `lineNumber` and `columnNumber`.", "Version 104 also serializes `stack` in [`window.postMessage()`](https://developer.mozilla.org/docs/Web/API/Window/postMessage) and [`structuredClone()`](https://developer.mozilla.org/docs/Web/API/structuredClone)."] | 55 | No | 12.0 | No | No |
See also
--------
* [`Error`](error)
javascript Function Function
========
Every JavaScript function is actually a `Function` object. This can be seen with the code `(function () {}).constructor === Function`, which returns true.
Constructor
-----------
[`Function()`](function/function) Creates a new `Function` object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to [`eval()`](eval). However, unlike `eval()`, the `Function` constructor creates functions that execute in the global scope only.
Instance properties
-------------------
[`Function.prototype.arguments`](function/arguments) Deprecated Non-standard
Represents the arguments passed to this function. For [strict](../strict_mode), arrow, async, and generator functions, accessing the `arguments` property throws a [`TypeError`](typeerror). Use the [`arguments`](../functions/arguments) object inside function closures instead.
[`Function.prototype.caller`](function/caller) Non-standard Deprecated
Represents the function that invoked this function. For [strict](../strict_mode), arrow, async, and generator functions, accessing the `caller` property throws a [`TypeError`](typeerror).
[`Function.prototype.displayName`](function/displayname) Non-standard Optional
The display name of the function.
[`Function.prototype.length`](function/length) Specifies the number of arguments expected by the function.
[`Function.prototype.name`](function/name) The name of the function.
[`Function.prototype.prototype`](function/prototype) Used when the function is used as a constructor with the [`new`](../operators/new) operator. It will become the new object's prototype.
Instance methods
----------------
[`Function.prototype.apply()`](function/apply) Calls a function with a given `this` value and optional arguments provided as an array (or an [array-like object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)).
[`Function.prototype.bind()`](function/bind) Creates a new function that, when called, has its `this` keyword set to a provided value, optionally with a given sequence of arguments preceding any provided when the new function is called.
[`Function.prototype.call()`](function/call) Calls a function with a given `this` value and optional arguments.
[`Function.prototype.toString()`](function/tostring) Returns a string representing the source code of the function. Overrides the [`Object.prototype.toString`](object/tostring) method.
Examples
--------
### Difference between Function constructor and function declaration
Functions created with the `Function` constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the `Function` constructor was created. This is different from using [`eval()`](eval) with code for a function expression.
```
// Create a global property with `var`
var x = 10;
function createFunction1() {
const x = 20;
return new Function("return x;"); // this `x` refers to global `x`
}
function createFunction2() {
const x = 20;
function f() {
return x; // this `x` refers to the local `x` above
}
return f;
}
const f1 = createFunction1();
console.log(f1()); // 10
const f2 = createFunction2();
console.log(f2()); // 20
```
While this code works in web browsers, `f1()` will produce a `ReferenceError` in Node.js, as `x` will not be found. This is because the top-level scope in Node is not the global scope, and `x` will be local to the module.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-function-objects](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Function` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `Function` | 1 | 12 | 1 | 4 | 3 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `apply` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `arguments` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `bind` | 7 | 12 | 4 | 9 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 6 | 1.0 | 1.0 | 0.10.0 |
| `call` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0
When calling this method, `thisArg` does not default to the global object. |
| `caller` | 1 | 12 | 1 | 8 | 9.6 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `displayName` | No | No | 13 | No | No | No | No | No | 14 | No | No | No | No | No |
| `length` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `name` | 15 | 14 | 1 | No | 10.5 | 6 | 4.4 | 18 | 4 | 11 | 6 | 1.0 | 1.0 | 0.10.0 |
| `toString` | 1 | 12 | 1 | 5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`function` declaration](../statements/function)
* [`function` expression](../operators/function)
* [`AsyncFunction`](asyncfunction)
* [`AsyncGeneratorFunction`](asyncgeneratorfunction)
* [`GeneratorFunction`](generatorfunction)
* [Functions](../functions)
| programming_docs |
javascript Float64Array Float64Array
============
The `Float64Array` typed array represents an array of 64-bit floating point numbers (corresponding to the C `double` data type) in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Float64Array()`](float64array/float64array) Creates a new `Float64Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Float64Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of `Float64Array`.
[`Float64Array.name`](typedarray/name) Returns the string value of the constructor name. `"Float64Array"` in the case of `Float64Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Float64Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `8` in the case of a `Float64Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a `Float64Array`
```
// From a length
const float64 = new Float64Array(2);
float64[0] = 42;
console.log(float64[0]); // 42
console.log(float64.length); // 2
console.log(float64.BYTES\_PER\_ELEMENT); // 8
// From an array
const x = new Float64Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Float64Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new Float64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const float64FromIterable = new Float64Array(iterable);
console.log(float64FromIterable);
// Float64Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Float64Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Float64Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Float64Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript Generator Generator
=========
The `Generator` object is returned by a [generator function](../statements/function*) and it conforms to both the [iterable protocol](../iteration_protocols#the_iterable_protocol) and the [iterator protocol](../iteration_protocols#the_iterator_protocol).
Try it
------
Constructor
-----------
The `Generator` constructor is not available globally. Instances of `Generator` must be returned from [generator functions](../statements/function*):
```
function\* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator(); // "Generator { }"
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
```
Instance properties
-------------------
`Generator.prototype[@@toStringTag]` The initial value of the [`@@toStringTag`](symbol/tostringtag) property is the string `"Generator"`. This property is used in [`Object.prototype.toString()`](object/tostring).
Instance methods
----------------
[`Generator.prototype.next()`](generator/next) Returns a value yielded by the [`yield`](../operators/yield) expression.
[`Generator.prototype.return()`](generator/return) Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](../statements/try...catch#the_finally-block) block.
[`Generator.prototype.throw()`](generator/throw) Acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.
Examples
--------
### An infinite iterator
With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.
```
function\* infinite() {
let index = 0;
while (true) {
yield index++;
}
}
const generator = infinite(); // "Generator { }"
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generator-objects](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generator-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Generator` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `next` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
| `return` | 50 | 13 | 38 | No | 37 | 10 | 50 | 50 | 38 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
| `throw` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [`function*`](../statements/function*)
* [`function*` expression](../operators/function*)
* [`GeneratorFunction`](generatorfunction)
* [The Iterator protocol](../iteration_protocols)
javascript Uint8Array Uint8Array
==========
The `Uint8Array` typed array represents an array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Constructor
-----------
[`Uint8Array()`](uint8array/uint8array) Creates a new `Uint8Array` object.
Static properties
-----------------
*Also inherits static properties from its parent [`TypedArray`](typedarray)*.
[`Uint8Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of `Uint8Array`.
[`Uint8Array.name`](typedarray/name) Returns the string value of the constructor name. `"Uint8Array"` in the case of `Uint8Array`.
Static methods
--------------
*Inherits static methods from its parent [`TypedArray`](typedarray)*.
Instance properties
-------------------
*Also inherits instance properties from its parent [`TypedArray`](typedarray)*.
[`Uint8Array.prototype.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) Returns a number value of the element size. `1` in the case of a `Uint8Array`.
Instance methods
----------------
*Inherits instance methods from its parent [`TypedArray`](typedarray)*.
Examples
--------
### Different ways to create a Uint8Array
```
// From a length
const uint8 = new Uint8Array(2);
uint8[0] = 42;
console.log(uint8[0]); // 42
console.log(uint8.length); // 2
console.log(uint8.BYTES\_PER\_ELEMENT); // 1
// From an array
const x = new Uint8Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uint8FromIterable = new Uint8Array(iterable);
console.log(uint8FromIterable);
// Uint8Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # table-49](https://tc39.es/ecma262/multipage/indexed-collections.html#table-49) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint8Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `Uint8Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Uint8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](arraybuffer)
* [`DataView`](dataview)
javascript Uint8ClampedArray() constructor Uint8ClampedArray() constructor
===============================
The `Uint8ClampedArray()` constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Syntax
------
```
new Uint8ClampedArray()
new Uint8ClampedArray(length)
new Uint8ClampedArray(typedArray)
new Uint8ClampedArray(object)
new Uint8ClampedArray(buffer)
new Uint8ClampedArray(buffer, byteOffset)
new Uint8ClampedArray(buffer, byteOffset, length)
```
**Note:** `Uint8ClampedArray()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
See [`TypedArray`](../typedarray#parameters).
### Exceptions
See [`TypedArray`](../typedarray#exceptions).
Examples
--------
### Different ways to create a Uint8ClampedArray
```
// From a length
const uintc8 = new Uint8ClampedArray(2);
uintc8[0] = 42;
uintc8[1] = 1337;
console.log(uintc8[0]); // 42
console.log(uintc8[1]); // 255 (clamped)
console.log(uintc8.length); // 2
console.log(uintc8.BYTES\_PER\_ELEMENT); // 1
// From an array
const x = new Uint8ClampedArray([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8ClampedArray(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8ClampedArray(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uintc8FromIterable = new Uint8ClampedArray(iterable);
console.log(uintc8FromIterable);
// Uint8ClampedArray [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray-constructors](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray-constructors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint8ClampedArray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `constructor_without_parameters` | 7 | 12 | 55 | 10 | 11.6 | 5.1 | ≤37 | 18 | 55 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `iterable_allowed` | 39 | 14 | 52 | No | 26 | 10 | 39 | 39 | 52 | 26 | 10 | 4.0 | 1.0 | 4.0.0 |
| `new_required` | 7 | 14 | 44 | No | 15 | 5.1 | ≤37 | 18 | 44 | 14 | 5 | 1.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Uint8ClampedArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](../arraybuffer)
* [`DataView`](../dataview)
javascript WeakMap.prototype.has() WeakMap.prototype.has()
=======================
The `has()` method returns a boolean indicating whether an element with the specified key exists in the `WeakMap` object or not.
Try it
------
Syntax
------
```
has(key)
```
### Parameters
`key` Required. The key of the element to test for presence in the `WeakMap` object.
### Return value
Boolean Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`.
Examples
--------
### Using the has method
```
const wm = new WeakMap();
wm.set(window, "foo");
wm.has(window); // returns true
wm.has("baz"); // returns false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap.prototype.has](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap.prototype.has) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `has` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`WeakMap`](../weakmap)
* [`WeakMap.prototype.set()`](set)
* [`WeakMap.prototype.get()`](get)
javascript WeakMap() constructor WeakMap() constructor
=====================
The `WeakMap()` creates a [`WeakMap`](../weakmap) object, optionally based on a provided [`Array`](../array) or other iterable object.
Syntax
------
```
new WeakMap()
new WeakMap(iterable)
```
**Note:** `WeakMap()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`iterable` An [`Array`](../array) or other iterable object that implements an [@@iterator](../array/@@iterator) method that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined.
Examples
--------
### Using WeakMap
```
const wm1 = new WeakMap();
const wm2 = new WeakMap();
const wm3 = new WeakMap();
const o1 = {};
const o2 = function () {};
const o3 = window;
wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value
wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')
wm3.set(o1, 37);
wm3.get(o1); // 37
wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap-constructor](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `WeakMap` | 36 | 12 | 6 | 11 | 23 | 8 | 37 | 36 | 6 | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
| `iterable_allowed` | 38 | 12 | 36 | No | 25 | 9 | 38 | 38 | 36 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `new_required` | 36 | 12 | 42 | 11 | 23 | 9 | 37 | 36 | 42 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `null_allowed` | 36 | 12 | 37 | 11 | 23 | 8 | 37 | 36 | 37 | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [Polyfill of `WeakMap` in `core-js`](https://github.com/zloirock/core-js#weakmap)
* [`WeakMap` in the JavaScript guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object)
* [Hiding Implementation Details with ECMAScript 6 WeakMaps](https://fitzgeraldnick.com/2014/01/13/hiding-implementation-details-with-e6-weakmaps.html)
* [`Map`](../map)
* [`Set`](../set)
* [`WeakSet`](../weakset)
javascript WeakMap.prototype.set() WeakMap.prototype.set()
=======================
The `set()` method adds a new element with a specified key and value to a `WeakMap` object.
Try it
------
Syntax
------
```
set(key, value)
```
### Parameters
`key` Required. Must be `object`. The key of the element to add to the `WeakMap` object.
`value` Required. Any value. The value of the element to add to the `WeakMap` object.
### Return value
The `WeakMap` object.
Examples
--------
### Using the set() method
```
const wm = new WeakMap();
const obj = {};
// Add new elements to the WeakMap
wm.set(obj, "foo").set(window, "bar"); // chainable
// Update an element in the WeakMap
wm.set(obj, "baz");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap.prototype.set](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap.prototype.set) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `set` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11
Returns 'undefined' instead of the 'Map' object. | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`WeakMap`](../weakmap)
* [`WeakMap.prototype.get()`](get)
* [`WeakMap.prototype.has()`](has)
javascript WeakMap.prototype.delete() WeakMap.prototype.delete()
==========================
The `delete()` method removes the specified element from a [`WeakMap`](../weakmap) object.
Try it
------
Syntax
------
```
delete(key)
```
### Parameters
`key` The key of the element to remove from the `WeakMap` object.
### Return value
`true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap` or if the key is not an object.
Examples
--------
### Using the delete() method
```
const wm = new WeakMap();
wm.set(window, "foo");
wm.delete(window); // Returns true. Successfully removed.
wm.has(window); // Returns false. The window object is no longer in the WeakMap.
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap.prototype.delete](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap.prototype.delete) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `delete` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. This has been fixed in version 38 and later to return `false` as per the ES2015 standard. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`WeakMap`](../weakmap)
| programming_docs |
javascript WeakMap.prototype.get() WeakMap.prototype.get()
=======================
The `get()` method returns a specified element from a `WeakMap` object.
Try it
------
Syntax
------
```
get(key)
```
### Parameters
`key` Required. The key of the element to return from the `WeakMap` object.
### Return value
The element associated with the specified key in the `WeakMap` object. If the key can't be found, [`undefined`](../undefined) is returned.
Examples
--------
### Using the get() method
```
const wm = new WeakMap();
wm.set(window, "foo");
wm.get(window); // Returns "foo".
wm.get("baz"); // Returns undefined.
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakmap.prototype.get](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap.prototype.get) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `get` | 36 | 12 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. However, the ES2015 specification specifies to return `undefined` instead. Furthermore, `WeakMap.prototype.get` accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher. | 11 | 23 | 8 | 37 | 36 | 6
Before Firefox 38, this method threw a `TypeError` when the key parameter was not an object. However, the ES2015 specification specifies to return `undefined` instead. Furthermore, `WeakMap.prototype.get` accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher. | 24 | 8 | 3.0 | 1.0 | 0.12.0
0.10.0 |
See also
--------
* [`WeakMap`](../weakmap)
* [`WeakMap.prototype.set()`](set)
* [`WeakMap.prototype.has()`](has)
javascript AsyncGeneratorFunction() constructor AsyncGeneratorFunction() constructor
====================================
The `AsyncGeneratorFunction()` constructor creates a new [`AsyncGeneratorFunction`](../asyncgeneratorfunction) object. In JavaScript, every [async generator function](../../statements/async_function*) is actually an `AsyncGeneratorFunction` object.
Note that `AsyncGeneratorFunction` is not a global object. It could be obtained by evaluating the following code.
```
const AsyncGeneratorFunction = async function\* () {}.constructor;
```
The `AsyncGeneratorFunction()` constructor is not intended to be used directly, and all caveats mentioned in the [`Function()`](../function/function) description apply to `AsyncGeneratorFunction()`.
Syntax
------
```
new AsyncGeneratorFunction(functionBody)
new AsyncGeneratorFunction(arg0, functionBody)
new AsyncGeneratorFunction(arg0, arg1, functionBody)
new AsyncGeneratorFunction(arg0, arg1, /\* … ,\*/ argN, functionBody)
AsyncGeneratorFunction(functionBody)
AsyncGeneratorFunction(arg0, functionBody)
AsyncGeneratorFunction(arg0, arg1, functionBody)
AsyncGeneratorFunction(arg0, arg1, /\* … ,\*/ argN, functionBody)
```
**Note:** `AsyncGeneratorFunction()` can be called with or without [`new`](../../operators/new). Both create a new `AsyncGeneratorFunction` instance.
### Parameters
See [`Function()`](../function/function).
Examples
--------
### Using the constructor
The following example uses the `AsyncGeneratorFunction` constructor to create an async generator function.
```
const AsyncGeneratorFunction = async function\* () {}.constructor;
const createAsyncGenerator = new AsyncGeneratorFunction("a", "yield a \* 2");
const asyncGen = createAsyncGenerator(10);
asyncGen.next().then((res) => console.log(res.value)); // 20
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgeneratorfunction-constructor](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgeneratorfunction-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `AsyncGeneratorFunction` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*` declaration](../../statements/async_function*)
* [`async function*` expression](../../operators/async_function*)
* [`Function()` constructor](../function/function)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
* [Functions](../../functions)
javascript BigInt() constructor BigInt() constructor
====================
The `BigInt()` function returns a value of type **bigint**.
Syntax
------
```
BigInt(value)
```
**Note:** `BigInt()` can only be called without [`new`](../../operators/new). Attempting to construct it with `new` throws a [`TypeError`](../typeerror).
### Parameters
`value` The numeric value of the object being created. It may be a string, an integer, a boolean, or another `BigInt`.
### Return value
A [`BigInt`](../bigint) value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`.
### Exceptions
[`RangeError`](../rangeerror) Thrown if the parameter is a non-integral number.
[`TypeError`](../typeerror) Thrown if at least one of these conditions is met:
* The parameter cannot be converted to a primitive.
* After conversion to a primitive, the result is [`undefined`](../undefined), [`null`](../../operators/null), [`symbol`](../symbol).
[`SyntaxError`](../syntaxerror) Thrown if the parameter is a string that cannot be parsed as a `BigInt`.
Examples
--------
### Using BigInt() to convert a number to a BigInt
`BigInt()` is the only case where a number can be converted to a BigInt without throwing, because it's very explicit. However, only integers are allowed.
```
BigInt(123); // 123n
BigInt(123.3); // RangeError: The number 123.3 cannot be converted to a BigInt because it is not an integer
```
### Using string values
```
BigInt("123"); // 123n
BigInt("0b10101"); // 4161n, which is 10101 in binary
BigInt("0o123"); // 83n, which is 123 in octal
BigInt("0x123"); // 291n, which is 123 in hexadecimal
BigInt(" 123 "); // 123n, leading and trailing whitespaces are allowed
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint-constructor](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `BigInt` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`BigInt`](../bigint) class
javascript BigInt.prototype.toLocaleString() BigInt.prototype.toLocaleString()
=================================
The `toLocaleString()` method returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](../intl/numberformat) support, this method simply calls `Intl.NumberFormat`.
Try it
------
Syntax
------
```
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```
### Parameters
The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the [`Intl.NumberFormat` API](../intl/numberformat), these parameters correspond exactly to the [`Intl.NumberFormat()`](../intl/numberformat/numberformat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](../intl/numberformat/numberformat#locales) parameter of the `Intl.NumberFormat()` constructor.
In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used.
`options` Optional
An object adjusting the output format. Corresponds to the [`options`](../intl/numberformat/numberformat#options) parameter of the `Intl.NumberFormat()` constructor.
In implementations without `Intl.NumberFormat` support, this parameter is ignored.
See the [`Intl.NumberFormat()` constructor](../intl/numberformat/numberformat) for details on these parameters and how to use them.
### Return value
A string with a language-sensitive representation of the given BigInt.
In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`.
Performance
-----------
When formatting large numbers of numbers, it is better to create a [`Intl.NumberFormat`](../intl/numberformat) object and use the function provided by its [`format()`](../intl/numberformat/format) method.
Examples
--------
### Using `toLocaleString`
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
const bigint = 3500n;
console.log(bigint.toLocaleString());
// "3,500" if in U.S. English locale
```
### Using `locales`
This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
const bigint = 123456789123456789n;
// German uses period for thousands
console.log(bigint.toLocaleString('de-DE'));
// 123.456.789.123.456.789
// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(bigint.toLocaleString('ar-EG'));
// ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩
// India uses thousands/lakh/crore separators
console.log(bigint.toLocaleString('en-IN'));
// 1,23,45,67,89,12,34,56,789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(bigint.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// 一二三,四五六,七八九,一二三,四五六,七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(bigint.toLocaleString(['ban', 'id']));
// 123.456.789.123.456.789
```
### Using `options`
The results provided by `toLocaleString` can be customized using the `options` argument:
```
const bigint = 123456789123456789n;
// request a currency format
console.log(bigint.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// 123.456.789.123.456.789,00 €
// the Japanese yen doesn't use a minor unit
console.log(bigint.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// ¥123,456,789,123,456,789
// limit to three significant digits
console.log(bigint.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// 1,23,00,00,00,00,00,00,000
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sup-bigint.prototype.tolocalestring](https://tc39.es/ecma402/#sup-bigint.prototype.tolocalestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleString` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
| `locales` | 76 | 79 | 70 | No | No | 14 | 76 | 76 | 79 | 54 | 14 | 12.0 | 1.8
1.0-1.8
Only the locale data for `en-US` is available. | 12.9.0 |
| `options` | 76 | 79 | 70 | No | No | 14 | 76 | 76 | 79 | 54 | 14 | 12.0 | ? | 12.9.0 |
See also
--------
* [`BigInt.prototype.toString()`](tostring)
javascript BigInt.prototype.valueOf() BigInt.prototype.valueOf()
==========================
The `valueOf()` method returns the wrapped primitive value of a [`BigInt`](../bigint) object.
Try it
------
Syntax
------
```
bigIntObj.valueOf()
```
### Return value
A BigInt representing the primitive value of the specified [`BigInt`](../bigint) object.
Examples
--------
### Using `valueOf`
```
typeof Object(1n); // object
typeof Object(1n).valueOf(); // bigint
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint.prototype.valueof](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint.prototype.valueof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `valueOf` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`BigInt.prototype.toString()`](tostring)
javascript BigInt.asUintN() BigInt.asUintN()
================
The `BigInt.asUintN` static method clamps a `BigInt` value to the given number of bits, and returns that value as an unsigned integer.
Try it
------
Syntax
------
```
BigInt.asUintN(bits, bigint)
```
### Parameters
`bits` The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive.
`bigint` The BigInt value to clamp to fit into the supplied bits.
### Return value
The value of `bigint` modulo 2^`bits`, as an unsigned integer.
### Exceptions
[`RangeError`](../rangeerror) Thrown if `bits` is negative or greater than 253 - 1.
Description
-----------
The `BigInt.asUintN` method clamps a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is clamped to `9n`:
```
25n = 00011001 (base 2)
^==== Clamp to four remaining bits
===> 1001 (base 2) = 9n
```
**Note:** `BigInt` values are always encoded as two's complement in binary.
Unlike similar language APIs such as [`Number.prototype.toExponential()`](../number/toexponential), `asUintN` is a static property of [`BigInt`](../bigint), so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs).
Examples
--------
### Staying in 64-bit ranges
The `BigInt.asUintN()` method can be useful to stay in the range of 64-bit arithmetic.
```
const max = 2n \*\* 64n - 1n;
BigInt.asUintN(64, max); // 18446744073709551615n
BigInt.asUintN(64, max + 1n); // 0n
// zero because of overflow: the lowest 64 bits are all zeros
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint.asuintn](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint.asuintn) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `asUintN` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`BigInt`](../bigint)
* [`BigInt.asIntN()`](asintn)
javascript BigInt.prototype.toString() BigInt.prototype.toString()
===========================
The `toString()` method returns a string representing the specified [`BigInt`](../bigint) value. The trailing "n" is not part of the string.
Try it
------
Syntax
------
```
toString()
toString(radix)
```
### Parameters
`radix` Optional
An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10.
### Return value
A string representing the specified [`BigInt`](../bigint) value.
### Exceptions
[`RangeError`](../rangeerror) Thrown if `radix` is less than 2 or greater than 36.
Description
-----------
The [`BigInt`](../bigint) object overrides the `toString` method of [`Object`](../object); it does not inherit [`Object.prototype.toString()`](../object/tostring). For [`BigInt`](../bigint) values, the `toString()` method returns a string representation of the value in the specified radix.
For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used.
If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value.
The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a [`TypeError`](../typeerror) for other `this` values without attempting to coerce them to BigInt values.
Because `BigInt` doesn't have a [`[@@toPrimitive]()`](../symbol/toprimitive) method, JavaScript calls the `toString()` method automatically when a `BigInt` *object* is used in a context expecting a string, such as in a [template literal](../../template_literals). However, BigInt *primitive* values do not consult the `toString()` method to be [coerced to strings](../string#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation.
```
BigInt.prototype.toString = () => "Overridden";
console.log(`${1n}`); // "1"
console.log(`${Object(1n)}`); // "Overridden"
```
Examples
--------
### Using toString()
```
17n.toString(); // "17"
66n.toString(2); // "1000010"
254n.toString(16); // "fe"
(-10n).toString(2); // "-1010"
(-0xffn).toString(2); // "-11111111"
```
### Negative-zero BigInt
There is no negative-zero `BigInt` as there are no negative zeros in integers. `-0.0` is an IEEE floating-point concept that only appears in the JavaScript [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type) type.
```
(-0n).toString(); // "0"
BigInt(-0).toString(); // "0"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint.prototype.tostring](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint.prototype.tostring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toString` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`BigInt.prototype.toLocaleString()`](tolocalestring)
* [`BigInt.prototype.valueOf()`](valueof)
* [`Number.prototype.toString()`](../number/tostring)
| programming_docs |
javascript BigInt.asIntN() BigInt.asIntN()
===============
The `BigInt.asIntN` static method clamps a `BigInt` value to the given number of bits, and returns that value as a signed integer.
Try it
------
Syntax
------
```
BigInt.asIntN(bits, bigint)
```
### Parameters
`bits` The amount of bits available for the returned BigInt. Should be an integer between 0 and 253 - 1, inclusive.
`bigint` The BigInt value to clamp to fit into the supplied bits.
### Return value
The value of `bigint` modulo 2^`bits`, as a signed integer.
### Exceptions
[`RangeError`](../rangeerror) Thrown if `bits` is negative or greater than 253 - 1.
Description
-----------
The `BigInt.asIntN` method clamps a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is clamped to `1n`:
```
25n = 00011001 (base 2)
^=== Clamp to three remaining bits
===> 001 (base 2) = 1n
```
If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement:
```
25n = 00011001 (base 2)
^==== Clamp to four remaining bits
===> 1001 (base 2) = -7n
```
**Note:** `BigInt` values are always encoded as two's complement in binary.
Unlike similar language APIs such as [`Number.prototype.toExponential()`](../number/toexponential), `asIntN` is a static property of [`BigInt`](../bigint), so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs).
Examples
--------
### Staying in 64-bit ranges
The `BigInt.asIntN()` method can be useful to stay in the range of 64-bit arithmetic.
```
const max = 2n \*\* (64n - 1n) - 1n;
BigInt.asIntN(64, max); // 9223372036854775807n
BigInt.asIntN(64, max + 1n); // -9223372036854775808n
// negative because the 64th bit of 2^63 is 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-bigint.asintn](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint.asintn) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `asIntN` | 67 | 79 | 68 | No | 54 | 14 | 67 | 67 | 68 | 48 | 14 | 9.0 | 1.0 | 10.4.0 |
See also
--------
* [`BigInt`](../bigint)
* [`BigInt.asUintN()`](asuintn)
javascript GeneratorFunction() constructor GeneratorFunction() constructor
===============================
The `GeneratorFunction()` constructor creates a new [`GeneratorFunction`](../generatorfunction) object. In JavaScript, every [generator function](../../statements/function*) is actually a `GeneratorFunction` object.
Note that `GeneratorFunction` is *not* a global object. It can be obtained with the following code:
```
const GeneratorFunction = function\* () {}.constructor;
```
The `GeneratorFunction()` constructor is not intended to be used directly, and all caveats mentioned in the [`Function()`](../function/function) description apply to `GeneratorFunction()`.
Syntax
------
```
new GeneratorFunction(functionBody)
new GeneratorFunction(arg0, functionBody)
new GeneratorFunction(arg0, arg1, functionBody)
new GeneratorFunction(arg0, arg1, /\* … ,\*/ argN, functionBody)
GeneratorFunction(functionBody)
GeneratorFunction(arg0, functionBody)
GeneratorFunction(arg0, arg1, functionBody)
GeneratorFunction(arg0, arg1, /\* … ,\*/ argN, functionBody)
```
**Note:** `GeneratorFunction()` can be called with or without [`new`](../../operators/new). Both create a new `GeneratorFunction` instance.
### Parameters
See [`Function()`](../function/function).
Examples
--------
### Creating and using a GeneratorFunction() constructor
```
const GeneratorFunction = function\* () {}.constructor;
const g = new GeneratorFunction("a", "yield a \* 2");
const iterator = g(10);
console.log(iterator.next().value); // 20
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-generatorfunction-constructor](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-generatorfunction-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `GeneratorFunction` | 39 | 13 | 26 | No | 26 | 10 | 39 | 39 | 26 | 26 | 10 | 4.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [`function*` declaration](../../statements/function*)
* [`function*` expression](../../operators/function*)
* [`Function()` constructor](../function/function)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
* [Functions](../../functions)
javascript RegExp.prototype[@@search]() RegExp.prototype[@@search]()
============================
The `[@@search]()` method of a regular expression specifies how [`String.prototype.search`](../string/search) should behave.
Try it
------
Syntax
------
```
regexp[Symbol.search](str)
```
### Parameters
`str` A [`String`](../string) that is a target of the search.
### Return value
The index of the first match between the regular expression and the given string, or `-1` if no match was found.
Description
-----------
This method is called internally in [`String.prototype.search()`](../string/search). For example, the following two examples return the same result.
```
"abc".search(/a/);
/a/[Symbol.search]("abc");
```
This method does not copy the regular expression, unlike [`@@split`](@@split) or [`@@matchAll`](@@matchall). However, unlike [`@@match`](@@match) or [`@@replace`](@@replace), it will set [`lastIndex`](lastindex) to 0 when execution starts and restore it to the previous value when it exits, therefore generally avoiding side effects. This means that the `g` flag has no effect with this method, and it always returns the first match in the string even when `lastIndex` is non-zero. This also means sticky regexps will always search strictly at the beginning of the string.
```
const re = /[abc]/g;
re.lastIndex = 2;
console.log("abc".search(re)); // 0
const re2 = /[bc]/y;
re2.lastIndex = 1;
console.log("abc".search(re2)); // -1
console.log("abc".match(re2)); // [ 'b' ]
```
`@@search` always calls the regex's [`exec()`](exec) method exactly once, and returns the `index` property of the result, or `-1` if the result is `null`.
This method exists for customizing the search behavior in `RegExp` subclasses.
Examples
--------
### Direct call
This method can be used in almost the same way as [`String.prototype.search()`](../string/search), except for the different value of `this` and the different arguments order.
```
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.search](str);
console.log(result); // 4
```
### Using @@search in subclasses
Subclasses of [`RegExp`](../regexp) can override `[@@search]()` method to modify the behavior.
```
class MyRegExp extends RegExp {
constructor(str) {
super(str);
this.pattern = str;
}
[Symbol.search](str) {
return str.indexOf(this.pattern);
}
}
const re = new MyRegExp("a+b");
const str = "ab a+b";
const result = str.search(re); // String.prototype.search calls re[@@search].
console.log(result); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype-@@search](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype-@@search) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@search` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype[@@search]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.search()`](../string/search)
* [`RegExp.prototype[@@match]()`](@@match)
* [`RegExp.prototype[@@replace]()`](@@replace)
* [`RegExp.prototype[@@split]()`](@@split)
* [`RegExp.prototype.exec()`](exec)
* [`RegExp.prototype.test()`](test)
javascript RegExp.prototype.compile() RegExp.prototype.compile()
==========================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** The `compile()` method is only specified for compatibility reasons. Using `compile()` causes the otherwise immutable regex source and flags to become mutable, which may break user expectations. You can use the [`RegExp()`](regexp) constructor to construct a new regular expression object instead.
The `compile()` method of a `RegExp` object is used to recompile a regular expression with new source and flags after the `RegExp` object has already been created.
Syntax
------
```
compile(pattern, flags)
```
### Parameters
`pattern` The text of the regular expression.
`flags` Any combination of [flag values](regexp#flags).
Examples
--------
### Using compile()
The following example shows how to recompile a regular expression with a new pattern and a new flag.
```
const regexObj = new RegExp("foo", "gi");
regexObj.compile("new foo", "g");
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype.compile](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-regexp.prototype.compile) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `compile` | 1 | 12 | 1 | 4 | 6 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp`](../regexp)
javascript RegExp.prototype.flags RegExp.prototype.flags
======================
The `flags` accessor property represents the [flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags) of the current regular expression object.
Try it
------
Description
-----------
`RegExp.prototype.flags` has a string as its value. Flags in the `flags` property are sorted alphabetically (from left to right, e.g. `"dgimsuy"`). It actually invokes the other flag accessors ([`hasIndices`](hasindices), [`global`](global), etc.) one-by-one and concatenates the results.
All built-in functions read the `flags` property instead of reading individual flag accessors.
The set accessor of `flags` is `undefined`. You cannot change this property directly.
Examples
--------
### Using flags
```
/foo/ig.flags; // "gi"
/bar/myu.flags; // "muy"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.flags](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.flags) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `flags` | 49 | 79 | 37 | No | 39 | 9 | 49 | 49 | 37 | 41 | 9 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype.flags` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`RegExp.prototype.source`](source)
javascript RegExp.prototype.ignoreCase RegExp.prototype.ignoreCase
===========================
The `ignoreCase` accessor property indicates whether or not the `i` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.ignoreCase` has the value `true` if the `i` flag was used; otherwise, `false`. The `i` flag indicates that case should be ignored while attempting a match in a string.
If the regex has the [`unicode`](unicode) flag, the case mapping happens as specified in [`CaseFolding.txt`](https://unicode.org/Public/UCD/latest/ucd/CaseFolding.txt). Otherwise, case mapping uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html) — the same algorithm used in [`String.prototype.toUpperCase()`](../string/touppercase) and [`String.prototype.toLowerCase()`](../string/tolowercase).
The set accessor of `ignoreCase` is `undefined`. You cannot change this property directly.
Examples
--------
### Using ignoreCase
```
const regex = /foo/i;
console.log(regex.ignoreCase); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.ignorecase](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.ignorecase) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ignoreCase` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `prototype_accessor` | 48 | 12 | 38 | 5.5 | 35 | 1.3 | 48 | 48 | 38 | 35 | 1 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
javascript RegExp.$1, …, RegExp.$9 RegExp.$1, …, RegExp.$9
=======================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.$1, …, RegExp.$9` static accessor properties return parenthesized substring matches.
Description
-----------
Because `$1`–`$9` are static properties of [`RegExp`](../regexp), you always use them as `RegExp.$1`, `RegExp.$2`, etc., rather than as properties of a `RegExp` object you created.
The values of `$1, …, $9` update whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the last match does not have the corresponding capturing group, the respective property is an empty string. The set accessor of each property is `undefined`, so you cannot change the properties directly.
The number of possible parenthesized substrings is unlimited, but the `RegExp` object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.
`$1, …, $9` can also be used in the replacement string of [`String.prototype.replace()`](../string/replace), but that's unrelated to the `RegExp.$n` legacy properties.
Examples
--------
### Using $n with RegExp.prototype.test()
The following script uses the [`test()`](test) method of the [`RegExp`](../regexp) instance to grab a number in a generic string.
```
const str = "Test 24";
const number = /(\d+)/.test(str) ? RegExp.$1 : "0";
number; // "24"
```
Please note that any operation involving the usage of other regular expressions between a `re.test(str)` call and the `RegExp.$n` property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `n` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.input ($_)`](input)
* [`RegExp.lastMatch ($&)`](lastmatch)
* [`RegExp.lastParen ($+)`](lastparen)
* [`RegExp.leftContext ($`)`](leftcontext)
* [`RegExp.rightContext ($')`](rightcontext)
javascript RegExp.prototype[@@matchAll]() RegExp.prototype[@@matchAll]()
==============================
The `[@@matchAll]()` method of a regular expression specifies how [`String.prototype.matchAll`](../string/matchall) should behave.
Try it
------
Syntax
------
```
regexp[Symbol.matchAll](str)
```
### Parameters
`str` A [`String`](../string) that is a target of the match.
### Return value
An [iterable iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) (which is not restartable) of matches. Each match is an array with the same shape as the return value of [`RegExp.prototype.exec()`](exec).
Description
-----------
This method is called internally in [`String.prototype.matchAll()`](../string/matchall). For example, the following two examples return the same result.
```
"abc".matchAll(/a/g);
/a/g[Symbol.matchAll]("abc");
```
Like [`@@split`](@@split), `@@matchAll` starts by using [`@@species`](@@species) to construct a new regex, thus avoiding mutating the original regexp in any way. [`lastIndex`](lastindex) starts as the original regex's value.
```
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex}${m[0]}`);
// [ "1 b", "1 c" ]
```
The validation that the input is a global regex happens in [`String.prototype.matchAll()`](../string/matchall). `@@matchAll` does not validate the input. If the regex is not global, the returned iterator yields the [`exec()`](exec) result once and then returns `undefined`. If the regexp is global, each time the returned iterator's `next()` method is called, the regex's [`exec()`](exec) is called and the result is yielded.
When the regex is sticky and global, it will still perform sticky matches — i.e. it will not match any occurrences beyond the `lastIndex`.
```
console.log(Array.from("ab-c".matchAll(/[abc]/gy)));
// [ [ "a" ], [ "b" ] ]
```
If the current match is an empty string, the [`lastIndex`](lastindex) will still be advanced. If the regex has the [`u`](unicode) flag, it advances by one Unicode codepoint; otherwise, it advances by one UTF-16 codepoint.
```
console.log(Array.from("😄".matchAll(/(?:)/g)));
// [ [ "" ], [ "" ], [ "" ] ]
console.log(Array.from("😄".matchAll(/(?:)/gu)));
// [ [ "" ], [ "" ] ]
```
This method exists for customizing the behavior of `matchAll()` in [`RegExp`](../regexp) subclasses.
Examples
--------
### Direct call
This method can be used in almost the same way as [`String.prototype.matchAll()`](../string/matchall), except for the different value of `this` and the different order of arguments.
```
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.matchAll](str);
console.log(Array.from(result, (x) => x[0]));
// [ "2016", "01", "02" ]
```
### Using @@matchAll in subclasses
Subclasses of [`RegExp`](../regexp) can override the `[@@matchAll]()` method to modify the default behavior.
For example, to return an [`Array`](../array) instead of an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators):
```
class MyRegExp extends RegExp {
[Symbol.matchAll](str) {
const result = RegExp.prototype[Symbol.matchAll].call(this, str);
return result ? Array.from(result) : null;
}
}
const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)", "g");
const str = "2016-01-02|2019-03-07";
const result = str.matchAll(re);
console.log(result[0]);
// [ "2016-01-02", "2016", "01", "02" ]
console.log(result[1]);
// [ "2019-03-07", "2019", "03", "07" ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp-prototype-matchall](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp-prototype-matchall) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@matchAll` | 73 | 79 | 67 | No | 60 | 13 | 73 | 73 | 67 | 52 | 13 | 5.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype[@@matchAll]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.matchAll()`](../string/matchall)
* [`Symbol.matchAll`](../symbol/matchall)
| programming_docs |
javascript RegExp.lastMatch ($&) RegExp.lastMatch ($&)
=====================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.lastMatch` static accessor property returns the last matched substring. `RegExp["$&"]` is an alias for this property.
Description
-----------
Because `lastMatch` is a static property of [`RegExp`](../regexp), you always use it as `RegExp.lastMatch` or `RegExp["$&"]`, rather than as a property of a `RegExp` object you created.
The value of `lastMatch` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `lastMatch` is an empty string. The set accessor of `lastMatch` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$&`), because `&` is not a valid identifier part, so this causes a [`SyntaxError`](../syntaxerror). Use the [bracket notation](../../operators/property_accessors) instead.
`$&` can also be used in the replacement string of [`String.prototype.replace()`](../string/replace), but that's unrelated to the `RegExp["$&"]` legacy property.
Examples
--------
### Using lastMatch and $&
```
const re = /hi/g;
re.test("hi there!");
RegExp.lastMatch; // "hi"
RegExp["$&"]; // "hi"
```
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `lastMatch` | 1 | 12 | 1 | 5.5 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.input ($_)`](input)
* [`RegExp.lastParen ($+)`](lastparen)
* [`RegExp.leftContext ($`)`](leftcontext)
* [`RegExp.rightContext ($')`](rightcontext)
* [`RegExp.$1, …, RegExp.$9`](n)
javascript RegExp.prototype.global RegExp.prototype.global
=======================
The `global` accessor property indicates whether or not the `g` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.global` has the value `true` if the `g` flag was used; otherwise, `false`. The `g` flag indicates that the regular expression should be tested against all possible matches in a string. Each call to [`exec()`](exec) will update its [`lastIndex`](lastindex) property, so that the next call to `exec()` will start at the next character.
Some methods, such as [`String.prototype.matchAll()`](../string/matchall) and [`String.prototype.replaceAll()`](../string/replaceall), will validate that, if the parameter is a regex, it is global. The regex's [`@@match`](@@match) and [`@@replace`](@@replace) methods (called by [`String.prototype.match()`](../string/match) and [`String.prototype.replace()`](../string/replace)) would also have different behaviors when the regex is global.
The set accessor of `global` is `undefined`. You cannot change this property directly.
Examples
--------
### Using global
```
const regex = /foo/g;
console.log(regex.global); // true
const str = "fooexamplefoo";
const str1 = str.replace(regex, "");
console.log(str1); // example
const regex1 = /foo/;
const str2 = str.replace(regex1, '');
console.log(str2); // examplefoo
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.global](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.global) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `global` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `prototype_accessor` | 48 | 12 | 38 | 5.5 | 35 | 1.3 | 48 | 48 | 38 | 35 | 1 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
javascript RegExp.prototype[@@replace]() RegExp.prototype[@@replace]()
=============================
The `[@@replace]()` method of a regular expression specifies how [`String.prototype.replace()`](../string/replace) and [`String.prototype.replaceAll()`](../string/replaceall) should behave when the regular expression is passed in as the pattern.
Try it
------
Syntax
------
```
regexp[Symbol.replace](str, replacement)
```
### Parameters
`str` A [`String`](../string) that is a target of the replacement.
`replacement` Can be a string or a function.
* If it's a string, it will replace the substring matched by the current regexp. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](../string/replace#specifying_a_string_as_the_replacement) section of `String.prototype.replace`.
* If it's a function, it will be invoked for every match and the return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](../string/replace#specifying_a_function_as_the_replacement) section of `String.prototype.replace`.
### Return value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.
Description
-----------
This method is called internally in [`String.prototype.replace()`](../string/replace) and [`String.prototype.replaceAll()`](../string/replaceall) if the `pattern` argument is a [`RegExp`](../regexp) object. For example, the following two examples return the same result.
```
"abc".replace(/a/, "A");
/a/[Symbol.replace]("abc", "A");
```
If the regex is global (with the `g` flag), the regex's [`exec()`](exec) method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once. For each `exec()` result, the substitution will be prepared based on the description in [`String.prototype.replace()`](../string/replace#description).
Because `@@replace` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's [`lastIndex`](lastindex) to 0 when the last match fails, `@@replace` would typically not have side effects when it exits. However, when the regex is <sticky> but not global, `lastIndex` would not be reset. In this case, each call to `replace()` may return a different result.
```
const re = /a/y;
for (let i = 0; i < 5; i++) {
console.log("aaa".replace(re, "b"), re.lastIndex);
}
// baa 1
// aba 2
// aab 3
// aaa 0
// baa 1
```
When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.
```
console.log("aa-a".replace(/a/gy, "b")); // "bb-a"
```
If the current match is an empty string, the `lastIndex` would still be advanced — if the regex has the [`u`](unicode) flag, it would advance by one Unicode codepoint; otherwise, it advances by one UTF-16 code unit.
```
console.log("😄".replace(/(?:)/g, " ")); // " \ud83d \ude04 "
console.log("😄".replace(/(?:)/gu, " ")); // " 😄 "
```
This method exists for customizing replace behavior in `RegExp` subclasses.
Examples
--------
### Direct call
This method can be used in almost the same way as [`String.prototype.replace()`](../string/replace), except the different `this` and the different arguments order.
```
const re = /-/g;
const str = "2016-01-01";
const newstr = re[Symbol.replace](str, ".");
console.log(newstr); // 2016.01.01
```
### Using @@replace in subclasses
Subclasses of [`RegExp`](../regexp) can override the `[@@replace]()` method to modify the default behavior.
```
class MyRegExp extends RegExp {
constructor(pattern, flags, count) {
super(pattern, flags);
this.count = count;
}
[Symbol.replace](str, replacement) {
// Perform @@replace |count| times.
let result = str;
for (let i = 0; i < this.count; i++) {
result = RegExp.prototype[Symbol.replace].call(this, result, replacement);
}
return result;
}
}
const re = new MyRegExp("\\d", "", 3);
const str = "01234567";
const newstr = str.replace(re, "#"); // String.prototype.replace calls re[@@replace].
console.log(newstr); // ###34567
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype-@@replace](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype-@@replace) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@replace` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype[@@replace]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.replace()`](../string/replace)
* [`String.prototype.replaceAll()`](../string/replaceall)
* [`RegExp.prototype[@@match]()`](@@match)
* [`RegExp.prototype[@@search]()`](@@search)
* [`RegExp.prototype[@@split]()`](@@split)
* [`RegExp.prototype.exec()`](exec)
* [`RegExp.prototype.test()`](test)
* [`Symbol.replace`](../symbol/replace)
javascript RegExp.prototype[@@match]() RegExp.prototype[@@match]()
===========================
The `[@@match]()` method of a regular expression specifies how [`String.prototype.match()`](../string/match) should behave. In addition, its presence (or absence) can influence whether an object is regarded as a regular expression.
Try it
------
Syntax
------
```
regexp[Symbol.match](str)
```
### Parameters
`str` A [`String`](../string) that is a target of the match.
### Return value
An [`Array`](../array) whose contents depend on the presence or absence of the global (`g`) flag, or [`null`](../../operators/null) if no matches are found.
* If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
* If the `g` flag is not used, only the first complete match and its related capturing groups are returned. In this case, `match()` will return the same result as [`RegExp.prototype.exec()`](exec) (an array with some extra properties).
Description
-----------
This method is called internally in [`String.prototype.match()`](../string/match).
For example, the following two examples return same result.
```
"abc".match(/a/);
/a/[Symbol.match]("abc");
```
If the regex is global (with the `g` flag), the regex's [`exec()`](exec) method will be repeatedly called until `exec()` returns `null`. Otherwise, `exec()` would only be called once and its result becomes the return value of `@@match`.
Because `@@match` would keep calling `exec()` until it returns `null`, and `exec()` would automatically reset the regex's [`lastIndex`](lastindex) to 0 when the last match fails, `@@match` would typically not have side effects when it exits. However, when the regex is <sticky> but not global, `lastIndex` would not be reset. In this case, each call to `match()` may return a different result.
```
const re = /[abc]/y;
for (let i = 0; i < 5; i++) {
console.log("abc".match(re), re.lastIndex);
}
// [ 'a' ] 1
// [ 'b' ] 2
// [ 'c' ] 3
// null 0
// [ 'a' ] 1
```
When the regex is sticky and global, it would still perform sticky matches — i.e. it would fail to match any occurrences beyond the `lastIndex`.
```
console.log("ab-c".match(/[abc]/gy)); // [ 'a', 'b' ]
```
If the current match is an empty string, the `lastIndex` would still be advanced — if the regex has the [`u`](unicode) flag, it would advance by one Unicode codepoint; otherwise, it advances by one UTF-16 code unit.
```
console.log("😄".match(/(?:)/g)); // [ '', '', '' ]
console.log("😄".match(/(?:)/gu)); // [ '', '' ]
```
This method exists for customizing match behavior within `RegExp` subclasses.
In addition, the `@@match` property is used to check [whether an object is a regular expression](../regexp#special_handling_for_regexes).
Examples
--------
### Direct call
This method can be used in *almost* the same way as [`String.prototype.match()`](../string/match), except the different `this` and the different arguments order.
```
const re = /[0-9]+/g;
const str = "2016-01-02";
const result = re[Symbol.match](str);
console.log(result); // ["2016", "01", "02"]
```
### Using @@match in subclasses
Subclasses of [`RegExp`](../regexp) can override the `[@@match]()` method to modify the default behavior.
```
class MyRegExp extends RegExp {
[Symbol.match](str) {
const result = RegExp.prototype[Symbol.match].call(this, str);
if (!result) return null;
return {
group(n) {
return result[n];
},
};
}
}
const re = new MyRegExp("([0-9]+)-([0-9]+)-([0-9]+)");
const str = "2016-01-02";
const result = str.match(re); // String.prototype.match calls re[@@match].
console.log(result.group(1)); // 2016
console.log(result.group(2)); // 01
console.log(result.group(3)); // 02
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype-@@match](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype-@@match) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@match` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype[@@match]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.match()`](../string/match)
* [`RegExp.prototype[@@replace]()`](@@replace)
* [`RegExp.prototype[@@search]()`](@@search)
* [`RegExp.prototype[@@split]()`](@@split)
* [`RegExp.prototype.exec()`](exec)
* [`RegExp.prototype.test()`](test)
javascript RegExp.prototype.hasIndices RegExp.prototype.hasIndices
===========================
The `hasIndices` accessor property indicates whether or not the `d` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.hasIndices` has the value `true` if the `d` flag was used; otherwise, `false`. The `d` flag indicates that the result of a regular expression match should contain the start and end indices of the substrings of each capture group. It does not change the regex's interpretation or matching behavior in any way, but only provides additional information in the matching result.
This flag primarily affects the return value of [`exec()`](exec). If the `d` flag is present, the array returned by `exec()` has an additional `indices` property as described in the `exec()` method's [return value](exec#return_value). Because all other regex-related methods (such as [`String.prototype.match()`](../string/match)) call `exec()` internally, they will also return the indices if the regex has the `d` flag.
The set accessor of `hasIndices` is `undefined`. You cannot change this property directly.
Examples
--------
There's a more detailed usage example at [Groups and backreferences > Using groups and match indices](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences#using_groups_and_match_indices).
### Using hasIndices
```
const str1 = "foo bar foo";
const regex1 = /foo/dg;
console.log(regex1.hasIndices); // true
console.log(regex1.exec(str1).indices[0]); // [0, 3]
console.log(regex1.exec(str1).indices[0]); // [8, 11]
const str2 = "foo bar foo";
const regex2 = /foo/;
console.log(regex2.hasIndices); // false
console.log(regex2.exec(str2).indices); // undefined
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.hasIndices](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.hasIndices) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hasIndices` | 90 | 90 | 88 | No | 76 | 15 | 90 | 90 | 88 | 64 | 15 | 15.0 | 1.8 | 16.0.0 |
See also
--------
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.exec()`](exec)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
javascript RegExp.prototype.multiline RegExp.prototype.multiline
==========================
The `multiline` accessor property indicates whether or not the `m` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.multiline` has the value `true` if the `m` flag was used; otherwise, `false`. The `m` flag indicates that a multiline input string should be treated as multiple lines. For example, if `m` is used, `^` and `$` change from matching at only the start or end of the entire string to the start or end of any line within the string.
The set accessor of `multiline` is `undefined`. You cannot change this property directly.
Examples
--------
### Using multiline
```
const regex = /foo/m;
console.log(regex.multiline); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.multiline](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.multiline) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `multiline` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `prototype_accessor` | 48 | 12 | 38 | 5.5 | 35 | 1.3 | 48 | 48 | 38 | 35 | 1 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
| programming_docs |
javascript RegExp.prototype.unicode RegExp.prototype.unicode
========================
The `unicode` accessor property indicates whether or not the `u` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.unicode` has the value `true` if the `u` flag was used; otherwise, `false`. The `u` flag enables various Unicode-related features. With the "u" flag:
* Any [Unicode code point escapes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes) (`\u{xxxx}`, `\p{UnicodePropertyValue}`) will be interpreted as such instead of as literal characters.
* Surrogate pairs will be interpreted as whole characters instead of two separate characters. For example, `/[😄]/u` would only match `"😄"` but not `"\ud83d"`.
* When [`lastIndex`](lastindex) is automatically advanced (such as when calling [`exec()`](exec)), unicode regexes advance by Unicode code points instead of UTF-16 code units.
There are other changes to the parsing behavior that prevent possible syntax mistakes (which are analogous to [strict mode](../../strict_mode) for regex syntax). This is explained in more detail in [Using Unicode regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#using_unicode_regular_expressions).
The set accessor of `unicode` is `undefined`. You cannot change this property directly.
Examples
--------
### Using the unicode property
```
const regex = /\u{61}/u;
console.log(regex.unicode); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.unicode](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.unicode) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `unicode` | 50 | 12
Case folding is implemented in version 13 | 46 | No | 37 | 10 | 50 | 50 | 46 | 37 | 10 | 5.0 | 1.0 | 6.0.0
Case folding is implemented in version 8.6.0 |
See also
--------
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
javascript RegExp.prototype.test() RegExp.prototype.test()
=======================
The `test()` method executes a search for a match between a regular expression and a specified string. Returns `true` or `false`.
JavaScript [`RegExp`](../regexp) objects are **stateful** when they have the [`global`](global) or [`sticky`](sticky) flags set (e.g., `/foo/g` or `/foo/y`). They store a [`lastIndex`](lastindex) from the previous match. Using this internally, `test()` can be used to iterate over multiple matches in a string of text (with capture groups).
Try it
------
Syntax
------
```
test(str)
```
### Parameters
`str` The string against which to match the regular expression.
### Returns
`true` if there is a match between the regular expression and the string `str`. Otherwise, `false`.
Description
-----------
Use `test()` whenever you want to know whether a pattern is found in a string. `test()` returns a boolean, unlike the [`String.prototype.search()`](../string/search) method (which returns the index of a match, or `-1` if not found).
To get more information (but with slower execution), use the [`exec()`](exec) method. (This is similar to the [`String.prototype.match()`](../string/match) method.)
As with `exec()` (or in combination with it), `test()` called multiple times on the same global regular expression instance will advance past the previous match.
Examples
--------
### Using test()
Simple example that tests if `"hello"` is contained at the very beginning of a string, returning a boolean result.
```
const str = "hello world!";
const result = /^hello/.test(str);
console.log(result); // true
```
The following example logs a message which depends on the success of the test:
```
function testInput(re, str) {
const midstring = re.test(str) ? "contains" : "does not contain";
console.log(`${str}${midstring}${re.source}`);
}
```
### Using test() on a regex with the "global" flag
When a regex has the [global flag](global) set, `test()` will advance the [`lastIndex`](lastindex) of the regex. ([`RegExp.prototype.exec()`](exec) also advances the `lastIndex` property.)
Further calls to `test(str)` will resume searching `str` starting from `lastIndex`. The `lastIndex` property will continue to increase each time `test()` returns `true`.
**Note:** As long as `test()` returns `true`, `lastIndex` will *not* reset—even when testing a different string!
When `test()` returns `false`, the calling regex's `lastIndex` property will reset to `0`.
The following example demonstrates this behavior:
```
const regex = /foo/g; // the "global" flag is set
// regex.lastIndex is at 0
regex.test("foo"); // true
// regex.lastIndex is now at 3
regex.test("foo"); // false
// regex.lastIndex is at 0
regex.test("barfoo"); // true
// regex.lastIndex is at 6
regex.test("foobar"); // false
// regex.lastIndex is at 0
regex.test("foobarfoo"); // true
// regex.lastIndex is at 3
regex.test("foobarfoo"); // true
// regex.lastIndex is at 9
regex.test("foobarfoo"); // false
// regex.lastIndex is at 0
// (...and so on)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype.test](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype.test) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `test` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) chapter in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* [`RegExp`](../regexp)
javascript RegExp() constructor RegExp() constructor
====================
The `RegExp` constructor creates a regular expression object for matching text with a pattern.
For an introduction to regular expressions, read the [Regular Expressions chapter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide).
Try it
------
Syntax
------
```
new RegExp(pattern)
new RegExp(pattern, flags)
RegExp(pattern)
RegExp(pattern, flags)
```
**Note:** `RegExp()` can be called with or without [`new`](../../operators/new), but sometimes with different effects. See [Return value](#return_value).
### Parameters
`pattern` The text of the regular expression. This can also be another `RegExp` object.
`flags` Optional
If specified, `flags` is a string that contains the flags to add. Alternatively, if a `RegExp` object is supplied for the `pattern`, the `flags` string will replace any of that object's flags (and `lastIndex` will be reset to `0`).
`flags` may contain any combination of the following characters:
[`d` (indices)](hasindices) Generate indices for substring matches.
[`g` (global)](global) Find all matches rather than stopping after the first match.
[`i` (ignore case)](ignorecase) When matching, casing differences are ignored.
[`m` (multiline)](multiline) Treat beginning and end assertions (`^` and `$`) as working over multiple lines. In other words, match the beginning or end of *each* line (delimited by `\n` or `\r`), not only the very beginning or end of the whole input string.
[`s` (dotAll)](dotall) Allows `.` to match newlines.
[`u` (unicode)](unicode) Treat `pattern` as a sequence of Unicode code points.
[`y` (sticky)](sticky) Matches only from the index indicated by the `lastIndex` property of this regular expression in the target string. Does not attempt to match from any later indexes.
### Return value
`RegExp(pattern)` returns `pattern` directly if all of the following are true:
* `RegExp()` is called without [`new`](../../operators/new);
* [`pattern` is a regex](../regexp#special_handling_for_regexes);
* `pattern.constructor === RegExp` (usually meaning it's not a subclass);
* `flags` is `undefined`.
In all other cases, calling `RegExp()` with or without `new` both create a new `RegExp` object. If `pattern` is a regex, the new object's <source> is `pattern.source`; otherwise, its source is `pattern` [coerced to a string](../string#string_coercion). If the `flags` parameter is not `undefined`, the new object's [`flags`](flags) is the parameter's value; otherwise, its `flags` is `pattern.flags` (if `pattern` is a regex).
### Exceptions
[`SyntaxError`](../syntaxerror) Thrown if one of the following is true:
* `pattern` cannot be parsed as a valid regular expression.
* `flags` contains repeated characters or any character outside of those allowed.
Examples
--------
### Literal notation and constructor
There are two ways to create a `RegExp` object: a *literal notation* and a *constructor*.
* The *literal notation* takes a pattern between two slashes, followed by optional flags, after the second slash.
* The *constructor function* takes either a string or a `RegExp` object as its first parameter and a string of optional flags as its second parameter.
The following three expressions create the same regular expression:
```
/ab+c/i;
new RegExp(/ab+c/, "i"); // literal notation
new RegExp("ab+c", "i"); // constructor
```
Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. There are two ways to compile and get a `RegExp` object.
The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the `RegExp` object, `new RegExp('ab+c')`, results in runtime compilation of the regular expression.
Use a string as the first argument to the `RegExp()` constructor when you want to [build the regular expression from dynamic input](#building_a_regular_expression_from_dynamic_inputs).
### Building a regular expression from dynamic inputs
```
const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";
order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp-constructor](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `RegExp` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of many modern `RegExp` features (`dotAll`, `sticky` flags, named capture groups, etc.) in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) chapter in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* [`String.prototype.match()`](../string/match)
* [`String.prototype.replace()`](../string/replace)
javascript RegExp.input ($_) RegExp.input ($\_)
==================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.input` static accessor property returns the string against which a regular expression is matched. `RegExp.$_` is an alias for this property.
Description
-----------
Because `input` is a static property of [`RegExp`](../regexp), you always use it as `RegExp.input` or `RegExp.$_`, rather than as a property of a `RegExp` object you created.
The value of `input` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `input` is an empty string. You can set the value of `input`, but this does not affect other behaviors of the regex, and the value will be overwritten again when the next successful match is made.
Examples
--------
### Using input and $\_
```
const re = /hi/g;
re.test("hi there!");
RegExp.input; // "hi there!"
re.test("foo"); // new test, non-matching
RegExp.$_; // "hi there!"
re.test("hi world!"); // new test, matching
RegExp.$_; // "hi world!"
```
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `input` | 1 | 12 | 1 | 5.5 | 15 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.lastMatch ($&)`](lastmatch)
* [`RegExp.lastParen ($+)`](lastparen)
* [`RegExp.leftContext ($`)`](leftcontext)
* [`RegExp.rightContext ($')`](rightcontext)
* [`RegExp.$1, …, RegExp.$9`](n)
javascript RegExp.rightContext ($') RegExp.rightContext ($')
========================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.rightContext` static accessor property returns the substring following the most recent match. `RegExp["$'"]` is an alias for this property.
Description
-----------
Because `rightContext` is a static property of [`RegExp`](../regexp), you always use it as `RegExp.rightContext` or `RegExp["$'"]`, rather than as a property of a `RegExp` object you created.
The value of `rightContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `rightContext` is an empty string. The set accessor of `rightContext` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$'`), because `'` is not a valid identifier part, so this causes a [`SyntaxError`](../syntaxerror). Use the [bracket notation](../../operators/property_accessors) instead.
`$'` can also be used in the replacement string of [`String.prototype.replace()`](../string/replace), but that's unrelated to the `RegExp["$'"]` legacy property.
Examples
--------
### Using rightContext and $'
```
const re = /hello/g;
re.test("hello world!");
RegExp.rightContext; // " world!"
RegExp["$'"]; // " world!"
```
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `rightContext` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.input ($_)`](input)
* [`RegExp.lastMatch ($&)`](lastmatch)
* [`RegExp.lastParen ($+)`](lastparen)
* [`RegExp.leftContext ($`)`](leftcontext)
* [`RegExp.$1, …, RegExp.$9`](n)
javascript RegExp.prototype.sticky RegExp.prototype.sticky
=======================
The `sticky` accessor property indicates whether or not the `y` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.sticky` has the value `true` if the `y` flag was used; otherwise, `false`. The `y` flag indicates that the regex attempts to match the target string only from the index indicated by the [`lastIndex`](lastindex) property (and unlike a global regex, does not attempt to match from any later indexes).
The set accessor of `sticky` is `undefined`. You cannot change this property directly.
For both sticky regexes and <global> regexes:
* They start matching at `lastIndex`.
* When the match succeeds, `lastIndex` is advanced to the end of the match.
* When `lastIndex` is out of bounds of the currently matched string, `lastIndex` is reset to 0.
However, for the [`exec()`](exec) method, the behavior when matching fails is different:
* When the [`exec()`](exec) method is called on a sticky regex, if the regex fails to match at `lastIndex`, the regex immediately returns `null` and resets `lastIndex` to 0.
* When the [`exec()`](exec) method is called on a global regex, if the regex fails to match at `lastIndex`, it tries to match from the next character, and so on until a match is found or the end of the string is reached.
For the [`exec()`](exec) method, a regex that's both sticky and global behaves the same as a sticky and non-global regex. Because [`test()`](test) is a simple wrapper around `exec()`, `test()` would ignore the global flag and perform sticky matches as well. However, due to many other methods special-casing the behavior of global regexes, the global flag is, in general, orthogonal to the sticky flag.
* [`String.prototype.matchAll()`](../string/matchall) (which calls [`RegExp.prototype[@@matchAll]()`](@@matchall)): `y`, `g` and `gy` are all different.
+ For `y` regexes: `matchAll()` throws; `[@@matchAll]()` yields the `exec()` result exactly once, without updating the regex's `lastIndex`.
+ For `g` or `gy` regexes: returns an iterator that yields a sequence of `exec()` results.
* [`String.prototype.match()`](../string/match) (which calls [`RegExp.prototype[@@match]()`](@@match)): `y`, `g` and `gy` are all different.
+ For `y` regexes: returns the `exec()` result and updates the regex's `lastIndex`.
+ For `g` or `gy` regexes: returns an array of all `exec()` results.
* [`String.prototype.search()`](../string/search) (which calls [`RegExp.prototype[@@search]()`](@@search)): the `g` flag is always irrelevant.
+ For `y` or `gy` regexes: always returns `0` (if the very beginning of the string matches) or `-1` (if the beginning doesn't match), without updating the regex's `lastIndex` when it exits.
+ For `g` regexes: returns the index of the first match in the string, or `-1` if no match is found.
* [`String.prototype.split()`](../string/split) (which calls [`RegExp.prototype[@@split]()`](@@split)): `y`, `g`, and `gy` all have the same behavior.
* [`String.prototype.replace()`](../string/replace) (which calls [`RegExp.prototype[@@replace]()`](@@replace)): `y`, `g` and `gy` are all different.
+ For `y` regexes: replaces once at the current `lastIndex` and updates `lastIndex`.
+ For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
* [`String.prototype.replaceAll()`](../string/replace) (which calls [`RegExp.prototype[@@replace]()`](@@replace)): `y`, `g` and `gy` are all different.
+ For `y` regexes: `replaceAll()` throws.
+ For `g` and `gy` regexes: replaces all occurrences matched by `exec()`.
Examples
--------
### Using a regular expression with the sticky flag
```
const str = "#foo#";
const regex = /foo/y;
regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)
```
### Anchored sticky flag
For several versions, Firefox's SpiderMonkey engine had [a bug](https://bugzilla.mozilla.org/show_bug.cgi?id=773687) with regard to the `^` assertion and the sticky flag which allowed expressions starting with the `^` assertion and using the sticky flag to match when they shouldn't. The bug was introduced some time after Firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. Perhaps because of the bug, the specification [specifically calls out](https://tc39.es/ecma262/#sec-compileassertion) the fact that:
> Even when the `y` flag is used with a pattern, `^` always matches only at the beginning of *Input*, or (if *rer*.[[Multiline]] is `true`) at the beginning of a line.
>
>
Examples of correct behavior:
```
const regex = /^foo/y;
regex.lastIndex = 2;
regex.test("..foo"); // false - index 2 is not the beginning of the string
const regex2 = /^foo/my;
regex2.lastIndex = 2;
regex2.test("..foo"); // false - index 2 is not the beginning of the string or line
regex2.lastIndex = 2;
regex2.test(".\nfoo"); // true - index 2 is the beginning of a line
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.sticky](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.sticky) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sticky` | 49 | 13 | 3 | No | 36 | 10 | 49 | 49 | 4 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `anchored_sticky_flag` | 49 | 13 | 44 | No | 36 | 10 | 49 | 49 | 44 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
| `prototype_accessor` | 49 | 13 | 38 | No | 36 | 10 | 49 | 49 | 38 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of the `sticky` flag in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.unicode`](unicode)
| programming_docs |
javascript RegExp.prototype.dotAll RegExp.prototype.dotAll
=======================
The `dotAll` accessor property indicates whether or not the `s` flag is used with the regular expression.
Try it
------
Description
-----------
`RegExp.prototype.dotAll` has the value `true` if the `s` flag was used; otherwise, `false`. The `s` flag indicates that the dot special character (`.`) should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise:
* U+000A LINE FEED (LF) (`\n`)
* U+000D CARRIAGE RETURN (CR) (`\r`)
* U+2028 LINE SEPARATOR
* U+2029 PARAGRAPH SEPARATOR
This effectively means the dot will match any character on the Unicode Basic Multilingual Plane (BMP). To allow it to match astral characters, the `u` (unicode) flag should be used. Using both flags in conjunction allows the dot to match any Unicode character, without exceptions.
The set accessor of `dotAll` is `undefined`. You cannot change this property directly.
Examples
--------
### Using dotAll
```
const str1 = "bar\nexample foo example";
const regex1 = /bar.example/s;
console.log(regex1.dotAll); // true
console.log(str1.replace(regex1, "")); // foo example
const str2 = "bar\nexample foo example";
const regex2 = /bar.example/;
console.log(regex2.dotAll); // false
console.log(str2.replace(regex2, ""));
// bar
// example foo example
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.dotAll](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.dotAll) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `dotAll` | 62 | 79 | 78 | No | 49 | 11.1 | 62 | 62 | 79 | 46 | 11.3 | 8.0 | 1.0 | 8.10.0
8.3.0 |
See also
--------
* [Polyfill of the `dotAll` flag in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`RegExp.prototype.lastIndex`](lastindex)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
javascript get RegExp[@@species] get RegExp[@@species]
=====================
The `RegExp[@@species]` accessor property returns the constructor used to construct copied regular expressions in certain `RegExp` methods.
**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
Try it
------
Syntax
------
```
RegExp[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `RegExp` instances.
Description
-----------
The `@@species` accessor property returns the default constructor for `RegExp` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```
// Hypothetical underlying implementation for illustration
class RegExp {
static get [Symbol.species]() {
return this;
}
}
```
Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.
```
class SubRegExp extends SubRegExp {}
SubRegExp[Symbol.species] === SubRegExp; // true
```
Some `RegExp` methods create a copy of the current regex instance before running [`exec()`](exec), so that side effects such as changes to [`lastIndex`](lastindex) are not retained. The `@@species` property is used to determine the constructor of the new instance. The methods that copy the current regex instance are:
* [`[@@matchAll]()`](@@matchall)
* [`[@@split]()`](@@split)
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `RegExp` constructor for `RegExp` objects:
```
RegExp[Symbol.species]; // function RegExp()
```
### Species in derived objects
In an instance of a custom `RegExp` subclass, such as `MyRegExp`, the `MyRegExp` species is the `MyRegExp` constructor. However, you might want to overwrite this, in order to return parent `RegExp` objects in your derived class methods:
```
class MyRegExp extends RegExp {
// Overwrite MyRegExp species to the parent RegExp constructor
static get [Symbol.species]() {
return RegExp;
}
}
```
Or you can use this to observe the copying process:
```
class MyRegExp extends RegExp {
constructor(...args) {
console.log("Creating a new MyRegExp instance with args: ", args);
super(...args);
}
static get [Symbol.species]() {
console.log("Copying MyRegExp");
return this;
}
exec(value) {
console.log("Executing with lastIndex: ", this.lastIndex);
return super.exec(value);
}
}
Array.from("aabbccdd".matchAll(new MyRegExp("[ac]", "g")));
// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]
// Copying MyRegExp
// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]
// Executing with lastIndex: 0
// Executing with lastIndex: 1
// Executing with lastIndex: 2
// Executing with lastIndex: 5
// Executing with lastIndex: 6
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp-@@species](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp-@@species) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@species` | 50 | 13 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`RegExp`](../regexp)
* [`Symbol.species`](../symbol/species)
javascript RegExp: lastIndex RegExp: lastIndex
=================
The `lastIndex` data property of a [`RegExp`](../regexp) instance specifies the index at which to start the next match.
Try it
------
Value
-----
A non-negative integer.
| Property attributes of `RegExp: lastIndex` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |
Description
-----------
This property is set only if the regular expression instance used the `g` flag to indicate a global search, or the `y` flag to indicate a sticky search. The following rules apply when [`test()`](test) and [`exec()`](exec) are called on a given input:
* If `lastIndex` is greater than the length of the input, `exec()` or `test()` will not find a match, and `lastIndex` will be set to 0.
* If `lastIndex` is equal to or less than the length of the input, `exec()` or `test()` will attempt to match the input starting from `lastIndex`.
+ If `exec()` or `test()` find a match, then `lastIndex` will be set to the position of the end of the matched string in the input.
+ If `exec()` or `test()` do not find a match, then `lastIndex` will be set to 0.
Examples
--------
### Using lastIndex
Consider the following sequence of statements:
```
const re = /(hi)?/g;
```
Matches the empty string.
```
console.log(re.exec("hi"));
console.log(re.lastIndex);
```
Returns `["hi", "hi"]` with `lastIndex` equal to 2.
```
console.log(re.exec("hi"));
console.log(re.lastIndex);
```
Returns `["", undefined]`, an empty array whose zeroth element is the match string. In this case, the empty string because `lastIndex` was 2 (and still is 2) and `hi` has length 2.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-properties-of-regexp-instances](https://tc39.es/ecma262/multipage/text-processing.html#sec-properties-of-regexp-instances) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `lastIndex` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.prototype.dotAll`](dotall)
* [`RegExp.prototype.global`](global)
* [`RegExp.prototype.hasIndices`](hasindices)
* [`RegExp.prototype.ignoreCase`](ignorecase)
* [`RegExp.prototype.multiline`](multiline)
* [`RegExp.prototype.source`](source)
* [`RegExp.prototype.sticky`](sticky)
* [`RegExp.prototype.unicode`](unicode)
javascript RegExp.prototype.exec() RegExp.prototype.exec()
=======================
The `exec()` method executes a search for a match in a specified string and returns a result array, or [`null`](../../operators/null).
Try it
------
Syntax
------
```
exec(str)
```
### Parameters
`str` The string against which to match the regular expression.
### Return value
If the match fails, the `exec()` method returns [`null`](../../operators/null), and sets the regex's [`lastIndex`](lastindex) to `0`.
If the match succeeds, the `exec()` method returns an array and updates the [`lastIndex`](lastindex) property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text. The array also has the following additional properties:
`index` The 0-based index of the match in the string.
`input` The original string that was matched against.
`groups` A [`null`-prototype object](../object#null-prototype_objects) of named capturing groups, whose keys are the names, and values are the capturing groups, or [`undefined`](../undefined) if no named capturing groups were defined. See [capturing groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences) for more information.
`indices` Optional
This property is only present when the [`d`](hasindices) flag is set. It is an array where each entry represents the bounds of a substring match. The index of each element in this array corresponds to the index of the respective substring match in the array returned by `exec()`. In other words, the first `indices` entry represents the entire match, the second `indices` entry represents the first capturing group, etc. Each entry itself is a two-element array, where the first number represents the match's start index, and the second number, its end index.
The `indices` array additionally has a `groups` property, which holds a [`null`-prototype object](../object#null-prototype_objects) of all named capturing groups. The keys are the names of the capturing groups, and each value is a two-element array, with the first number being the start index, and the second number being the end index of the capturing group. If the regular expression doesn't contain any named capturing groups, `groups` is `undefined`.
Description
-----------
JavaScript [`RegExp`](../regexp) objects are *stateful* when they have the <global> or <sticky> flags set (e.g. `/foo/g` or `/foo/y`). They store a [`lastIndex`](lastindex) from the previous match. Using this internally, `exec()` can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with [`String.prototype.match()`](../string/match).
When using `exec()`, the global flag has no effect when the sticky flag is set — the match is always sticky.
`exec()` is the primitive method of regexps. Many other regexp methods call `exec()` internally — including those called by string methods, like [`@@replace`](@@replace). While `exec()` itself is powerful (and is the most efficient), it often does not convey the intent most clearly.
* If you only care whether the regex matches a string, but not what is actually being matched, use [`RegExp.prototype.test()`](test) instead.
* If you are finding all occurrences of a global regex and you don't care about information like capturing groups, use [`String.prototype.match()`](../string/match) instead. In addition, [`String.prototype.matchAll()`](../string/matchall) helps to simplify matching multiple parts of a string (with capture groups) by allowing you to iterate over the matches.
* If you are executing a match to find its index position in the string, use the [`String.prototype.search()`](../string/search) method instead.
Examples
--------
### Using exec()
Consider the following example:
```
// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
const re = /quick\s(?<color>brown).+?(jumps)/dgi;
const result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog");
```
The following table shows the state of `result` after running this script:
| Property | Value |
| --- | --- |
| `[0]` | `"Quick Brown Fox Jumps"` |
| `[1]` | `"Brown"` |
| `[2]` | `"Jumps"` |
| `index` | `4` |
| `indices` | `[[4, 25], [10, 15], [20, 25]]``groups: { color: [10, 15 ]}` |
| `input` | `"The Quick Brown Fox Jumps Over The Lazy Dog"` |
| `groups` | `{ color: "brown" }` |
In addition, `re.lastIndex` will be set to `25`, due to this regex being global.
### Finding successive matches
If your regular expression uses the [`g`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags) flag, you can use the `exec()` method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of `str` specified by the regular expression's [`lastIndex`](lastindex) property ([`test()`](test) will also advance the [`lastIndex`](lastindex) property). Note that the [`lastIndex`](lastindex) property will not be reset when searching a different string, it will start its search at its existing [`lastIndex`](lastindex).
For example, assume you have this script:
```
const myRe = /ab\*/g;
const str = "abbcdefabh";
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
let msg = `Found ${myArray[0]}. `;
msg += `Next match starts at ${myRe.lastIndex}`;
console.log(msg);
}
```
This script displays the following text:
```
Found abb. Next match starts at 3
Found ab. Next match starts at 9
```
**Warning:** There are many pitfalls that can lead to this becoming an infinite loop!
* Do *not* place the regular expression literal (or [`RegExp`](../regexp) constructor) within the `while` condition — it will recreate the regex for every iteration and reset [`lastIndex`](lastindex).
* Be sure that the [global (`g`) flag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags) is set, or `lastIndex` will never be advanced.
* If the regex may match zero-length characters (e.g. `/^/gm`), increase its [`lastIndex`](lastindex) manually each time to avoid being stuck in the same place.
You can usually replace this kind of code with [`String.prototype.matchAll()`](../string/matchall) to make it less error-prone.
### Using exec() with RegExp literals
You can also use `exec()` without creating a [`RegExp`](../regexp) object explicitly:
```
const matches = /(hello \S+)/.exec("This is a hello world!");
console.log(matches[1]);
```
This will log a message containing `'hello world!'`.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype.exec](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype.exec) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `exec` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) chapter in the [JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
* [`RegExp`](../regexp)
javascript RegExp.prototype[@@split]() RegExp.prototype[@@split]()
===========================
The `[@@split]()` method of a regular expression specifies how [`String.prototype.split`](../string/split) should behave when the regular expression is passed in as the separator.
Try it
------
Syntax
------
```
regexp[Symbol.split](str[, limit])
```
### Parameters
`str` The target of the split operation.
`limit` Optional
Integer specifying a limit on the number of splits to be found. The `[@@split]()` method still splits on every match of `this` RegExp pattern (or, in the Syntax above, `regexp`), until the number of split items match the `limit` or the string falls short of `this` pattern.
### Return value
An [`Array`](../array) containing substrings as its elements. Capturing groups are included.
Description
-----------
This method is called internally in [`String.prototype.split()`](../string/split) when a `RegExp` is passed as the separator. For example, the following two examples return the same result.
```
"a-b-c".split(/-/);
/-/[Symbol.split]("a-b-c");
```
This method exists for customizing the behavior of `split()` in `RegExp` subclasses.
The `RegExp.prototype[@@split]()` base method exhibits the following behaviors:
* It starts by using [`@@species`](@@species) to construct a new regexp, thus avoiding mutating the original regexp in any way.
* The regexp's `g` ("global") flag is ignored, and the `y` ("sticky") flag is always applied even when it was not originally present.
* If the target string is empty, and the regexp can match empty strings (for example, `/a?/`), an empty array is returned. Otherwise, if the regexp can't match an empty string, `[""]` is returned.
* The matching proceeds by continuously calling `this.exec()`. Since the regexp is always sticky, this will move along the string, each time yielding a matching string, index, and any capturing groups.
* For each match, the substring between the last matched string's end and the current matched string's beginning is first appended to the result array. Then, the capturing groups' values are appended one-by-one.
* If the current match is an empty string, or if the regexp doesn't match at the current position (since it's sticky), the `lastIndex` would still be advanced — if the regex has the [`u`](unicode) flag, it would advance by one Unicode codepoint; otherwise, it advances by one UTF-16 code unit.
* If the regexp doesn't match the target string, the target string is returned as-is, wrapped in an array.
* The returned array's length will never exceed the `limit` parameter, if provided, while trying to be as close as possible. Therefore, the last match and its capturing groups may not all be present in the returned array if the array is already filled.
Examples
--------
### Direct call
This method can be used in almost the same way as [`String.prototype.split()`](../string/split), except the different `this` and the different order of arguments.
```
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.split](str);
console.log(result); // ["2016", "01", "02"]
```
### Using @@split in subclasses
Subclasses of [`RegExp`](../regexp) can override the `[@@split]()` method to modify the default behavior.
```
class MyRegExp extends RegExp {
[Symbol.split](str, limit) {
const result = RegExp.prototype[Symbol.split].call(this, str, limit);
return result.map((x) => `(${x})`);
}
}
const re = new MyRegExp("-");
const str = "2016-01-02";
const result = str.split(re); // String.prototype.split calls re[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype-@@split](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype-@@split) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@split` | 50 | 79 | 49 | No | 37 | 10 | 50 | 50 | 49 | 37 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [Polyfill of `RegExp.prototype[@@split]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
* [`String.prototype.split()`](../string/split)
* [`RegExp.prototype[@@match]()`](@@match)
* [`RegExp.prototype[@@replace]()`](@@replace)
* [`RegExp.prototype[@@search]()`](@@search)
* [`RegExp.prototype.exec()`](exec)
* [`RegExp.prototype.test()`](test)
| programming_docs |
javascript RegExp.prototype.source RegExp.prototype.source
=======================
The `source` accessor property is a string containing the source text of the regex object, without the two forward slashes on both sides or any flags.
Try it
------
Description
-----------
Conceptually, the `source` property is the text between the two forward slashes in the regular expression literal. The language requires the returned string to be properly escaped, so that when the `source` is concatenated with a forward slash on both ends, it would form a parsable regex literal. For example, for `new RegExp("/")`, the `source` is `\\/`, because if it generates `/`, the resulting literal becomes `///`, which is a line comment. Similarly, all [line terminators](../../lexical_grammar#line_terminators) will be escaped because line terminator *characters* would break up the regex literal. There's no requirement for other characters, as long as the result is parsable. For empty regular expressions, the string `(?:)` is returned.
Examples
--------
### Using source
```
const regex = /fooBar/gi;
console.log(regex.source); // "fooBar", doesn't contain /.../ and "gi".
```
### Empty regular expressions and escaping
```
new RegExp().source; // "(?:)"
new RegExp("\n").source === "\\n"; // true, starting with ES5
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-regexp.prototype.source](https://tc39.es/ecma262/multipage/text-processing.html#sec-get-regexp.prototype.source) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `source` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `empty_regex_string` | 6 | 12 | 38 | No | 15 | 5 | ≤37 | 18 | 38 | 14 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `escaping` | 73 | 12 | 38 | 10 | 60 | 6 | 73 | 73 | 38 | 52 | 6 | 11.0 | 1.0 | 12.0.0 |
| `prototype_accessor` | 48 | 12 | 41 | 4 | 35 | 1.3 | 48 | 48 | 41 | 35 | 1 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`RegExp.prototype.flags`](flags)
javascript RegExp.prototype.toString() RegExp.prototype.toString()
===========================
The `toString()` method returns a string representing the regular expression.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the given object.
Description
-----------
The [`RegExp`](../regexp) object overrides the `toString()` method of the [`Object`](../object) object; it does not inherit [`Object.prototype.toString()`](../object/tostring). For [`RegExp`](../regexp) objects, the `toString()` method returns a string representation of the regular expression.
In practice, it reads the regex's [`source`](source) and [`flags`](flags) properties and returns a string in the form `/source/flags`. The `toString()` return value is guaranteed to be a parsable regex literal, although it may not be the exact same text as what was originally specified for the regex (for example, the flags may be reordered).
Examples
--------
### Using toString()
The following example displays the string value of a [`RegExp`](../regexp) object:
```
const myExp = new RegExp("a+b+c");
console.log(myExp.toString()); // '/a+b+c/'
const foo = new RegExp("bar", "g");
console.log(foo.toString()); // '/bar/g'
```
### Empty regular expressions and escaping
Since `toString()` accesses the [`source`](source) property, an empty regular expression returns the string `"/(?:)/"`, and line terminators such as `\n` are escaped. This makes the returned value always a valid regex literal.
```
new RegExp().toString(); // "/(?:)/"
new RegExp("\n").toString() === "/\\n/"; // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-regexp.prototype.tostring](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp.prototype.tostring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toString` | 1 | 12 | 1 | 4 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `escaping` | 73 | 12 | 38 | 9 | 60 | 6 | 73 | 73 | 38 | 52 | 6 | 11.0 | 1.0 | 12.0.0 |
See also
--------
* [`Object.prototype.toString()`](../object/tostring)
javascript RegExp.lastParen ($+) RegExp.lastParen ($+)
=====================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.lastParen` static accessor property returns the last parenthesized substring match, if any. `RegExp["$+"]` is an alias for this property.
Description
-----------
Because `lastParen` is a static property of [`RegExp`](../regexp), you always use it as `RegExp.lastParen` or `RegExp["$+"]`, rather than as a property of a `RegExp` object you created.
The value of `lastParen` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, or if the most recent regex execution contains no capturing groups, `lastParen` is an empty string. The set accessor of `lastParen` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$+`), because `+` is not a valid identifier part, so this causes a [`SyntaxError`](../syntaxerror). Use the [bracket notation](../../operators/property_accessors) instead.
Examples
--------
### Using lastParen and $+
```
const re = /(hi)/g;
re.test("hi there!");
RegExp.lastParen; // "hi"
RegExp["$+"]; // "hi"
```
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `lastParen` | 1 | 12 | 1 | 5.5 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.input ($_)`](input)
* [`RegExp.lastMatch ($&)`](lastmatch)
* [`RegExp.leftContext ($`)`](leftcontext)
* [`RegExp.rightContext ($')`](rightcontext)
* [`RegExp.$1, …, RegExp.$9`](n)
javascript RegExp.leftContext ($`) RegExp.leftContext ($`)
=======================
**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
**Note:** All `RegExp` static properties that expose the last match state globally are deprecated. See [deprecated RegExp features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp) for more information.
The `RegExp.leftContext` static accessor property returns the substring preceding the most recent match. `RegExp["$`"]` is an alias for this property.
Description
-----------
Because `leftContext` is a static property of [`RegExp`](../regexp), you always use it as `RegExp.leftContext` or `RegExp["$`"]`, rather than as a property of a `RegExp` object you created.
The value of `leftContext` updates whenever a `RegExp` (but not a `RegExp` subclass) instance makes a successful match. If no matches have been made, `leftContext` is an empty string. The set accessor of `leftContext` is `undefined`, so you cannot change this property directly.
You cannot use the shorthand alias with the dot property accessor (`RegExp.$`` ), because ``` is not a valid identifier part, so this causes a [`SyntaxError`](../syntaxerror). Use the [bracket notation](../../operators/property_accessors) instead.
`$`` can also be used in the replacement string of [`String.prototype.replace()`](../string/replace), but that's unrelated to the `RegExp["$`"]` legacy property.
Examples
--------
### Using leftContext and $`
```
const re = /world/g;
re.test("hello world!");
RegExp.leftContext; // "hello "
RegExp["$`"]; // "hello "
```
Specifications
--------------
| Specification |
| --- |
| [Legacy RegExp features # additional-properties-of-the-regexp-constructor](https://github.com/tc39/proposal-regexp-legacy-features/#additional-properties-of-the-regexp-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `leftContext` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`RegExp.input ($_)`](input)
* [`RegExp.lastMatch ($&)`](lastmatch)
* [`RegExp.lastParen ($+)`](lastparen)
* [`RegExp.rightContext ($')`](rightcontext)
* [`RegExp.$1, …, RegExp.$9`](n)
javascript URIError() constructor URIError() constructor
======================
The `URIError()` constructor creates an error when a global URI handling function was used in a wrong way.
Syntax
------
```
new URIError()
new URIError(message)
new URIError(message, options)
new URIError(message, fileName)
new URIError(message, fileName, lineNumber)
URIError()
URIError(message)
URIError(message, options)
URIError(message, fileName)
URIError(message, fileName, lineNumber)
```
**Note:** `URIError()` can be called with or without [`new`](../../operators/new). Both create a new `URIError` instance.
### Parameters
`message` Optional
Human-readable description of the error.
`options` Optional
An object that has the following properties:
`cause` Optional
A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
`fileName` Optional Non-standard
The name of the file containing the code that caused the exception.
`lineNumber` Optional Non-standard
The line number of the code that caused the exception.
Examples
--------
### Catching an URIError
```
try {
decodeURIComponent('%')
} catch (e) {
console.log(e instanceof URIError) // true
console.log(e.message) // "malformed URI sequence"
console.log(e.name) // "URIError"
console.log(e.fileName) // "Scratchpad/1"
console.log(e.lineNumber) // 2
console.log(e.columnNumber) // 2
console.log(e.stack) // "@Scratchpad/2:2:3\n"
}
```
### Creating an URIError
```
try {
throw new URIError('Hello', 'someFile.js', 10)
} catch (e) {
console.log(e instanceof URIError) // true
console.log(e.message) // "Hello"
console.log(e.name) // "URIError"
console.log(e.fileName) // "someFile.js"
console.log(e.lineNumber) // 10
console.log(e.columnNumber) // 0
console.log(e.stack) // "@Scratchpad/2:2:9\n"
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-nativeerror-constructors](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-nativeerror-constructors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `URIError` | 1 | 12 | 1 | 5.5 | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Error`](../error)
* [`decodeURI()`](../decodeuri)
* [`decodeURIComponent()`](../decodeuricomponent)
* [`encodeURI()`](../encodeuri)
* [`encodeURIComponent()`](../encodeuricomponent)
javascript Proxy.revocable() Proxy.revocable()
=================
The `Proxy.revocable()` static method creates a revocable [`Proxy`](../proxy) object.
Syntax
------
```
Proxy.revocable(target, handler)
```
### Parameters
`target` A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy.
`handler` An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it.
### Return value
A plain object with the following two properties:
`proxy` A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](proxy) call.
`revoke` A function with no parameters to revoke (switch off) the `proxy`.
Description
-----------
The `Proxy.revocable()` factory function is the same as the [`Proxy()`](proxy) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object.
The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](../../classes/private_class_fields) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is *not* captured within the [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive).
After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a [`TypeError`](../typeerror). Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object.
Letting users interact with an object through a revocable proxy allows you to [control the lifetime](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy.
Examples
--------
### Using Proxy.revocable()
```
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 is thrown
proxy.foo = 1; // TypeError again
delete proxy.foo; // still TypeError
typeof proxy; // "object", typeof doesn't trigger any trap
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy.revocable](https://tc39.es/ecma262/multipage/reflection.html#sec-proxy.revocable) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `revocable` | 63 | 12 | 34 | No | 50 | 10 | 63 | 63 | 34 | 46 | 10 | 8.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../proxy)
javascript Proxy() constructor Proxy() constructor
===================
The `Proxy()` constructor is used to create [`Proxy`](../proxy) objects.
Syntax
------
```
new Proxy(target, handler)
```
**Note:** `Proxy()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`target` A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy.
`handler` An object whose properties are functions that define the behavior of the proxy when an operation is performed on it.
Description
-----------
Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments:
* `target` is the object for which you want to create the proxy
* `handler` is the object that defines the custom behavior of the proxy.
An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](../../operators/property_accessors).
### Handler functions
This section lists all the handler functions you can define. Handler functions are sometimes called *traps*, because they trap calls to the underlying target object.
[`handler.apply()`](proxy/apply) A trap for a function call.
[`handler.construct()`](proxy/construct) A trap for the [`new`](../../operators/new) operator.
[`handler.defineProperty()`](proxy/defineproperty) A trap for [`Object.defineProperty`](../object/defineproperty).
[`handler.deleteProperty()`](proxy/deleteproperty) A trap for the [`delete`](../../operators/delete) operator.
[`handler.get()`](proxy/get) A trap for getting property values.
[`handler.getOwnPropertyDescriptor()`](proxy/getownpropertydescriptor) A trap for [`Object.getOwnPropertyDescriptor`](../object/getownpropertydescriptor).
[`handler.getPrototypeOf()`](proxy/getprototypeof) A trap for [`Object.getPrototypeOf`](../object/getprototypeof).
[`handler.has()`](proxy/has) A trap for the [`in`](../../operators/in) operator.
[`handler.isExtensible()`](proxy/isextensible) A trap for [`Object.isExtensible`](../object/isextensible).
[`handler.ownKeys()`](proxy/ownkeys) A trap for [`Object.getOwnPropertyNames`](../object/getownpropertynames) and [`Object.getOwnPropertySymbols`](../object/getownpropertysymbols).
[`handler.preventExtensions()`](proxy/preventextensions) A trap for [`Object.preventExtensions`](../object/preventextensions).
[`handler.set()`](proxy/set) A trap for setting property values.
[`handler.setPrototypeOf()`](proxy/setprototypeof) A trap for [`Object.setPrototypeOf`](../object/setprototypeof).
Examples
--------
### Selectively proxy property accessors
In this example the target has two properties, `notProxied` and `proxied`. We define a handler that returns a different value for `proxied`, and lets any other accesses through to the target.
```
const target = {
notProxied: "original value",
proxied: "original value",
};
const handler = {
get(target, prop, receiver) {
if (prop === "proxied") {
return "replaced value";
}
return Reflect.get(...arguments);
},
};
const proxy = new Proxy(target, handler);
console.log(proxy.notProxied); // "original value"
console.log(proxy.proxied); // "replaced value"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-constructor](https://tc39.es/ecma262/multipage/reflection.html#sec-proxy-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Proxy` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy` and `Reflect` in the JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming)
* [`Reflect`](../reflect)
| programming_docs |
javascript handler.has() handler.has()
=============
The `handler.has()` method is a trap for the [`in`](../../../operators/in) operator.
Try it
------
Syntax
------
```
new Proxy(target, {
has(target, prop) {
}
});
```
### Parameters
The following parameters are passed to `has()` method. `this` is bound to the handler.
`target` The target object.
`prop` The name or [`Symbol`](../../symbol) of the property to check for existence.
### Return value
The `has()` method must return a boolean value.
Description
-----------
The `handler.has()` method is a trap for the [`in`](../../../operators/in) operator.
### Interceptions
This trap can intercept these operations:
* The [`in`](../../../operators/in) operator: `foo in proxy`
* [`with`](../../../statements/with) check: `with(proxy) { (foo); }`
* [`Reflect.has()`](../../reflect/has)
Or any other operation that invokes the `[[HasProperty]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
* A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
Examples
--------
### Trapping the in operator
The following code traps the [`in`](../../../operators/in) operator.
```
const p = new Proxy(
{},
{
has(target, prop) {
console.log(`called: ${prop}`);
return true;
},
}
);
console.log("a" in p);
// "called: a"
// true
```
The following code violates an invariant.
```
const obj = { a: 10 };
Object.preventExtensions(obj);
const p = new Proxy(obj, {
has(target, prop) {
return false;
},
});
"a" in p; // TypeError is thrown
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `has` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`in`](../../../operators/in) operator
* [`Reflect.has()`](../../reflect/has)
javascript handler.apply() handler.apply()
===============
The `handler.apply()` method is a trap for a function call.
Try it
------
Syntax
------
```
new Proxy(target, {
apply(target, thisArg, argumentsList) {
}
});
```
### Parameters
The following parameters are passed to the `apply()` method. `this` is bound to the handler.
`target` The target callable object.
`thisArg` The `this` argument for the call.
`argumentsList` The list of arguments for the call.
### Return value
The `apply()` method can return any value.
Description
-----------
The `handler.apply()` method is a trap for a function call.
### Interceptions
This trap can intercept these operations:
* Function call: `proxy(...args)`
* [`Function.prototype.apply()`](../../function/apply) and [`Function.prototype.call()`](../../function/call)
* [`Reflect.apply()`](../../reflect/apply)
Or any other operation that invokes the `[[Call]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* The `target` must be a callable itself. That is, it must be a function object.
Examples
--------
### Trapping a function call
The following code traps a function call.
```
const p = new Proxy(function () {}, {
apply(target, thisArg, argumentsList) {
console.log(`called: ${argumentsList}`);
return argumentsList[0] + argumentsList[1] + argumentsList[2];
}
});
console.log(p(1, 2, 3)); // "called: 1,2,3"
// 6
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `apply` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Function.prototype.apply()`](../../function/apply)
* [`Function.prototype.call()`](../../function/call)
* [`Reflect.apply()`](../../reflect/apply)
javascript handler.setPrototypeOf() handler.setPrototypeOf()
========================
The `handler.setPrototypeOf()` method is a trap for [`Object.setPrototypeOf()`](../../object/setprototypeof).
Try it
------
Syntax
------
```
new Proxy(target, {
setPrototypeOf(target, prototype) {
}
});
```
### Parameters
The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler.
`target` The target object.
`prototype` The object's new prototype or `null`.
### Return value
The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`.
Description
-----------
The `handler.setPrototypeOf()` method is a trap for [`Object.setPrototypeOf()`](../../object/setprototypeof).
### Interceptions
This trap can intercept these operations:
* [`Object.setPrototypeOf()`](../../object/setprototypeof)
* [`Reflect.setPrototypeOf()`](../../reflect/setprototypeof)
Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`.
Examples
--------
If you want to disallow setting a new prototype for your object, your handler's `setPrototypeOf()` method can either return `false`, or it can throw an exception.
### Approach 1: Returning false
This approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself.
For example, [`Object.setPrototypeOf()`](../../object/setprototypeof) will create and throw a [`TypeError`](../../typeerror) itself. If the mutation is performed by an operation that *doesn't* ordinarily throw in case of failure, such as [`Reflect.setPrototypeOf()`](../../reflect/setprototypeof), no exception will be thrown.
```
const handlerReturnsFalse = {
setPrototypeOf(target, newProto) {
return false;
},
};
const newProto = {},
target = {};
const p1 = new Proxy(target, handlerReturnsFalse);
Object.setPrototypeOf(p1, newProto); // throws a TypeError
Reflect.setPrototypeOf(p1, newProto); // returns false
```
### Approach 2: Throwing an Exception
The latter approach will cause *any* operation that attempts to mutate, to throw. This approach is best if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value.
```
const handlerThrows = {
setPrototypeOf(target, newProto) {
throw new Error("custom error");
},
};
const newProto = {},
target = {};
const p2 = new Proxy(target, handlerThrows);
Object.setPrototypeOf(p2, newProto); // throws new Error("custom error")
Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error")
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setPrototypeOf` | 49 | 12 | 49 | No | 36 | 10 | 49 | 49 | 49 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.setPrototypeOf()`](../../object/setprototypeof)
* [`Reflect.setPrototypeOf()`](../../reflect/setprototypeof)
javascript handler.construct() handler.construct()
===================
The `handler.construct()` method is a trap for the [`new`](../../../operators/new) operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself have a `[[Construct]]` internal method (i.e. `new target` must be valid).
Try it
------
Syntax
------
```
new Proxy(target, {
construct(target, argumentsList, newTarget) {
}
});
```
### Parameters
The following parameters are passed to the `construct()` method. `this` is bound to the handler.
`target` The target object.
`argumentsList` The list of arguments for the constructor.
`newTarget` The constructor that was originally called, `p` above.
### Return value
The `construct` method must return an object.
Description
-----------
The `handler.construct()` method is a trap for the [`new`](../../../operators/new) operator.
### Interceptions
This trap can intercept these operations:
* The [`new`](../../../operators/new) operator: `new myFunction(...args)`
* [`Reflect.construct()`](../../reflect/construct)
Or any other operation that invokes the `[[Construct]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* The result must be an `Object`.
Examples
--------
### Trapping the new operator
The following code traps the [`new`](../../../operators/new) operator.
```
const p = new Proxy(function () {}, {
construct(target, argumentsList, newTarget) {
console.log(`called: ${argumentsList}`);
return { value: argumentsList[0] \* 10 };
}
});
console.log(new p(1).value); // "called: 1"
// 10
```
The following code violates the invariant.
```
const p = new Proxy(function () {}, {
construct(target, argumentsList, newTarget) {
return 1;
}
});
new p(); // TypeError is thrown
```
The following code improperly initializes the proxy. The `target` in Proxy initialization must itself be a valid constructor for the [`new`](../../../operators/new) operator.
```
const p = new Proxy({}, {
construct(target, argumentsList, newTarget) {
return {};
}
});
new p(); // TypeError is thrown, "p" is not a constructor
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `construct` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`new`](../../../operators/new) operator.
* [`Reflect.construct()`](../../reflect/construct)
javascript handler.preventExtensions() handler.preventExtensions()
===========================
The `handler.preventExtensions()` method is a trap for [`Object.preventExtensions()`](../../object/preventextensions).
Try it
------
Syntax
------
```
new Proxy(target, {
preventExtensions(target) {
}
});
```
### Parameters
The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler.
`target` The target object.
### Return value
The `preventExtensions()` method must return a boolean value.
Description
-----------
The `handler.preventExtensions()` method is a trap for [`Object.preventExtensions()`](../../object/preventextensions).
### Interceptions
This trap can intercept these operations:
* [`Object.preventExtensions()`](../../object/preventextensions)
* [`Reflect.preventExtensions()`](../../reflect/preventextensions)
* [`Object.seal()`](../../object/seal)
* [`Object.freeze()`](../../object/freeze)
Or any other operation that invokes the `[[PreventExtensions]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`.
Examples
--------
### Trapping of preventExtensions
The following code traps [`Object.preventExtensions()`](../../object/preventextensions).
```
const p = new Proxy(
{},
{
preventExtensions(target) {
console.log("called");
Object.preventExtensions(target);
return true;
},
}
);
console.log(Object.preventExtensions(p));
// "called"
// false
```
The following code violates the invariant.
```
const p = new Proxy(
{},
{
preventExtensions(target) {
return true;
},
}
);
Object.preventExtensions(p); // TypeError is thrown
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-preventextensions](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-preventextensions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `preventExtensions` | 49 | 12 | 22 | No | 36 | 10 | 49 | 49 | 22 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.preventExtensions()`](../../object/preventextensions)
* [`Reflect.preventExtensions()`](../../reflect/preventextensions)
javascript handler.ownKeys() handler.ownKeys()
=================
The `handler.ownKeys()` method is a trap for [`Reflect.ownKeys()`](../../reflect/ownkeys).
Try it
------
Syntax
------
```
new Proxy(target, {
ownKeys(target) {
}
});
```
### Parameters
The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler.
`target` The target object.
### Return value
The `ownKeys()` method must return an enumerable object.
Description
-----------
The `handler.ownKeys()` method is a trap for [`Reflect.ownKeys()`](../../reflect/ownkeys).
### Interceptions
This trap can intercept these operations:
* [`Object.getOwnPropertyNames()`](../../object/getownpropertynames)
* [`Object.getOwnPropertySymbols()`](../../object/getownpropertysymbols)
* [`Object.keys()`](../../object/keys)
* [`Reflect.ownKeys()`](../../reflect/ownkeys)
Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* The result of `ownKeys()` must be an array.
* The type of each array element is either a [`String`](../../string) or a [`Symbol`](../../symbol).
* The result List must contain the keys of all non-configurable own properties of the target object.
* If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.
Examples
--------
### Trapping of getOwnPropertyNames
The following code traps [`Object.getOwnPropertyNames()`](../../object/getownpropertynames).
```
const p = new Proxy(
{},
{
ownKeys(target) {
console.log("called");
return ["a", "b", "c"];
},
}
);
console.log(Object.getOwnPropertyNames(p));
// "called"
// [ 'a', 'b', 'c' ]
```
The following code violates an invariant.
```
const obj = {};
Object.defineProperty(obj, "a", {
configurable: false,
enumerable: true,
value: 10,
});
const p = new Proxy(obj, {
ownKeys(target) {
return [123, 12.5, true, false, undefined, null, {}, []];
},
});
console.log(Object.getOwnPropertyNames(p));
// TypeError: proxy [[OwnPropertyKeys]] must return an array
// with only string and symbol elements
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ownKeys` | 49 | 12 | 18
In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore. | No | 36 | 10 | 49 | 49 | 18
In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore. | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.getOwnPropertyNames()`](../../object/getownpropertynames)
* [`Reflect.ownKeys()`](../../reflect/ownkeys)
javascript handler.isExtensible() handler.isExtensible()
======================
The `handler.isExtensible()` method is a trap for [`Object.isExtensible()`](../../object/isextensible).
Try it
------
Syntax
------
```
new Proxy(target, {
isExtensible(target) {
}
});
```
### Parameters
The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler.
`target` The target object.
### Return value
The `isExtensible()` method must return a boolean value.
Description
-----------
The `handler.isExtensible()` method is a trap for [`Object.isExtensible()`](../../object/isextensible).
### Interceptions
This trap can intercept these operations:
* [`Object.isExtensible()`](../../object/isextensible)
* [`Reflect.isExtensible()`](../../reflect/isextensible)
Or any other operation that invokes the `[[IsExtensible]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`.
Examples
--------
### Trapping of isExtensible
The following code traps [`Object.isExtensible()`](../../object/isextensible).
```
const p = new Proxy(
{},
{
isExtensible(target) {
console.log("called");
return true;
},
}
);
console.log(Object.isExtensible(p));
// "called"
// true
```
The following code violates the invariant.
```
const p = new Proxy(
{},
{
isExtensible(target) {
return false;
},
}
);
Object.isExtensible(p); // TypeError is thrown
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-isextensible](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-isextensible) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isExtensible` | 49 | 12 | 31 | No | 36 | 10 | 49 | 49 | 31 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.isExtensible()`](../../object/isextensible)
* [`Reflect.isExtensible()`](../../reflect/isextensible)
* [`Reflect.preventExtensions()`](../../reflect/preventextensions)
| programming_docs |
javascript handler.getOwnPropertyDescriptor() handler.getOwnPropertyDescriptor()
==================================
The `handler.getOwnPropertyDescriptor()` method is a trap for [`Object.getOwnPropertyDescriptor()`](../../object/getownpropertydescriptor).
Try it
------
Syntax
------
```
new Proxy(target, {
getOwnPropertyDescriptor(target, prop) {
}
});
```
### Parameters
The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler.
`target` The target object.
`prop` The name of the property whose description should be retrieved.
### Return value
The `getOwnPropertyDescriptor()` method must return an object or `undefined`.
Description
-----------
The `handler.getOwnPropertyDescriptor()` method is a trap for [`Object.getOwnPropertyDescriptor()`](../../object/getownpropertydescriptor).
### Interceptions
This trap can intercept these operations:
* [`Object.getOwnPropertyDescriptor()`](../../object/getownpropertydescriptor)
* [`Reflect.getOwnPropertyDescriptor()`](../../reflect/getownpropertydescriptor)
Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* `getOwnPropertyDescriptor()` must return an object or `undefined`.
* A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
* A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
* A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.
* A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
* The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception.
Examples
--------
### Trapping of getOwnPropertyDescriptor
The following code traps [`Object.getOwnPropertyDescriptor()`](../../object/getownpropertydescriptor).
```
const p = new Proxy(
{ a: 20 },
{
getOwnPropertyDescriptor(target, prop) {
console.log(`called: ${prop}`);
return { configurable: true, enumerable: true, value: 10 };
},
}
);
console.log(Object.getOwnPropertyDescriptor(p, "a").value);
// "called: a"
// 10
```
The following code violates an invariant.
```
const obj = { a: 10 };
Object.preventExtensions(obj);
const p = new Proxy(obj, {
getOwnPropertyDescriptor(target, prop) {
return undefined;
},
});
Object.getOwnPropertyDescriptor(p, "a"); // TypeError is thrown
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getOwnPropertyDescriptor` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.getOwnPropertyDescriptor()`](../../object/getownpropertydescriptor)
* [`Reflect.getOwnPropertyDescriptor()`](../../reflect/getownpropertydescriptor)
javascript handler.getPrototypeOf() handler.getPrototypeOf()
========================
The `handler.getPrototypeOf()` method is a trap for the `[[GetPrototypeOf]]` internal method.
Try it
------
Syntax
------
```
new Proxy(obj, {
getPrototypeOf(target) {
// …
}
});
```
### Parameters
The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler.
`target` The target object.
### Return value
The `getPrototypeOf()` method must return an object or `null`.
Description
-----------
### Interceptions
This trap can intercept these operations:
* [`Object.getPrototypeOf()`](../../object/getprototypeof)
* [`Reflect.getPrototypeOf()`](../../reflect/getprototypeof)
* [`__proto__`](../../object/proto)
* [`Object.prototype.isPrototypeOf()`](../../object/isprototypeof)
* [`instanceof`](../../../operators/instanceof)
Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* `getPrototypeOf()` method must return an object or `null`.
* If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`.
Examples
--------
### Basic usage
```
const obj = {};
const proto = {};
const handler = {
getPrototypeOf(target) {
console.log(target === obj); // true
console.log(this === handler); // true
return proto;
},
};
const p = new Proxy(obj, handler);
console.log(Object.getPrototypeOf(p) === proto); // true
```
### Five ways to trigger the getPrototypeOf trap
```
const obj = {};
const p = new Proxy(obj, {
getPrototypeOf(target) {
return Array.prototype;
},
});
console.log(
Object.getPrototypeOf(p) === Array.prototype, // true
Reflect.getPrototypeOf(p) === Array.prototype, // true
p.__proto__ === Array.prototype, // true
Array.prototype.isPrototypeOf(p), // true
p instanceof Array // true
);
```
### Two kinds of exceptions
```
const obj = {};
const p = new Proxy(obj, {
getPrototypeOf(target) {
return "foo";
},
});
Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null
const obj = Object.preventExtensions({});
const p = new Proxy(obj, {
getPrototypeOf(target) {
return {};
},
});
Object.getPrototypeOf(p); // TypeError: expected same prototype value
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-getprototypeof](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getPrototypeOf` | 49 | 79 | 49 | No | 36 | 10 | 49 | 49 | 49 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.getPrototypeOf()`](../../object/getprototypeof)
* [`Reflect.getPrototypeOf()`](../../reflect/getprototypeof)
javascript handler.defineProperty() handler.defineProperty()
========================
The `handler.defineProperty()` method is a trap for [`Object.defineProperty()`](../../object/defineproperty).
Try it
------
Syntax
------
```
new Proxy(target, {
defineProperty(target, property, descriptor) {
}
});
```
### Parameters
The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler.
`target` The target object.
`property` The name or [`Symbol`](../../symbol) of the property whose description is to be retrieved.
`descriptor` The descriptor for the property being defined or modified.
### Return value
The `defineProperty()` method must return a [`Boolean`](../../boolean) indicating whether or not the property has been successfully defined.
Description
-----------
The `handler.defineProperty()` method is a trap for [`Object.defineProperty()`](../../object/defineproperty).
### Interceptions
This trap can intercept these operations:
* [`Object.defineProperty()`](../../object/defineproperty), [`Object.defineProperties()`](../../object/defineproperties)
* [`Reflect.defineProperty()`](../../reflect/defineproperty)
Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* A property cannot be added, if the target object is not extensible.
* A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.
* A property may not be non-configurable, if a corresponding configurable property of the target object exists.
* If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception.
* In strict mode, a `false` return value from the `defineProperty()` handler will throw a [`TypeError`](../../typeerror) exception.
Examples
--------
### Trapping of defineProperty
The following code traps [`Object.defineProperty()`](../../object/defineproperty).
```
const p = new Proxy({}, {
defineProperty(target, prop, descriptor) {
console.log(`called: ${prop}`);
return true;
}
});
const desc = { configurable: true, enumerable: true, value: 10 };
Object.defineProperty(p, 'a', desc); // "called: a"
```
When calling [`Object.defineProperty()`](../../object/defineproperty) or [`Reflect.defineProperty()`](../../reflect/defineproperty), the `descriptor` passed to `defineProperty()` trap has one restriction—only following properties are usable (non-standard properties will be ignored):
* `enumerable`
* `configurable`
* `writable`
* `value`
* `get`
* `set`
```
const p = new Proxy({}, {
defineProperty(target, prop, descriptor) {
console.log(descriptor);
return Reflect.defineProperty(target, prop, descriptor);
}
});
Object.defineProperty(p, 'name', {
value: 'proxy',
type: 'custom'
}); // { value: 'proxy' }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `defineProperty` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Object.defineProperty()`](../../object/defineproperty)
* [`Reflect.defineProperty()`](../../reflect/defineproperty)
javascript handler.set() handler.set()
=============
The `handler.set()` method is a trap for setting a property value.
Try it
------
Syntax
------
```
new Proxy(target, {
set(target, property, value, receiver) {
}
});
```
### Parameters
The following parameters are passed to the `set()` method. `this` is bound to the handler.
`target` The target object.
`property` The name or [`Symbol`](../../symbol) of the property to set.
`value` The new value of the property to set.
`receiver` The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways.
For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver.
### Return value
The `set()` method should return a boolean value.
* Return `true` to indicate that assignment succeeded.
* If the `set()` method returns `false`, and the assignment happened in strict-mode code, a [`TypeError`](../../typeerror) will be thrown.
Description
-----------
The `handler.set()` method is a trap for setting property value.
### Interceptions
This trap can intercept these operations:
* Property assignment: `proxy[foo] = bar` and `proxy.foo = bar`
* [`Reflect.set()`](../../reflect/set)
Or any other operation that invokes the `[[Set]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
* Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute.
* In strict mode, a `false` return value from the `set()` handler will throw a [`TypeError`](../../typeerror) exception.
Examples
--------
### Trap setting of a property value
The following code traps setting a property value.
```
const p = new Proxy(
{},
{
set(target, prop, value, receiver) {
target[prop] = value;
console.log(`property set: ${prop} = ${value}`);
return true;
},
}
);
console.log("a" in p); // false
p.a = 10; // "property set: a = 10"
console.log("a" in p); // true
console.log(p.a); // 10
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `set` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Reflect.set()`](../../reflect/set)
javascript handler.deleteProperty() handler.deleteProperty()
========================
The `handler.deleteProperty()` method is a trap for the [`delete`](../../../operators/delete) operator.
Try it
------
Syntax
------
```
new Proxy(target, {
deleteProperty(target, property) {
}
});
```
### Parameters
The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler.
`target` The target object.
`property` The name or [`Symbol`](../../symbol) of the property to delete.
### Return value
The `deleteProperty()` method must return a [`Boolean`](../../boolean) indicating whether or not the property has been successfully deleted.
Description
-----------
The `handler.deleteProperty()` method is a trap for the [`delete`](../../../operators/delete) operator.
### Interceptions
This trap can intercept these operations:
* The [`delete`](../../../operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo`
* [`Reflect.deleteProperty()`](../../reflect/deleteproperty)
Or any other operation that invokes the `[[Delete]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* A property cannot be deleted, if it exists as a non-configurable own property of the target object.
Examples
--------
### Trapping the delete operator
The following code traps the [`delete`](../../../operators/delete) operator.
```
const p = new Proxy(
{},
{
deleteProperty(target, prop) {
if (!(prop in target)) {
console.log(`property not found: ${prop}`);
return false;
}
delete target[prop];
console.log(`property removed: ${prop}`);
return true;
},
}
);
p.a = 10;
console.log("a" in p); // true
const result1 = delete p.a; // "property removed: a"
console.log(result1); // true
console.log("a" in p); // false
const result2 = delete p.a; // "property not found: a"
console.log(result2); // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-delete-p](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-delete-p) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `deleteProperty` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`delete`](../../../operators/delete) operator
* [`Reflect.deleteProperty()`](../../reflect/deleteproperty)
javascript handler.get() handler.get()
=============
The `handler.get()` method is a trap for getting a property value.
Try it
------
Syntax
------
```
new Proxy(target, {
get(target, property, receiver) {
}
});
```
### Parameters
The following parameters are passed to the `get()` method. `this` is bound to the handler.
`target` The target object.
`property` The name or [`Symbol`](../../symbol) of the property to get.
`receiver` Either the proxy or an object that inherits from the proxy.
### Return value
The `get()` method can return any value.
Description
-----------
The `handler.get()` method is a trap for getting a property value.
### Interceptions
This trap can intercept these operations:
* Property access: `proxy[foo]` and `proxy.bar`
* [`Reflect.get()`](../../reflect/get)
Or any other operation that invokes the `[[Get]]` [internal method](../../proxy#object_internal_methods).
### Invariants
If the following invariants are violated, the trap throws a [`TypeError`](../../typeerror) when invoked.
* The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property.
* The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute.
Examples
--------
### Trap for getting a property value
The following code traps getting a property value.
```
const p = new Proxy(
{},
{
get(target, property, receiver) {
console.log(`called: ${property}`);
return 10;
},
}
);
console.log(p.a);
// "called: a"
// 10
```
The following code violates an invariant.
```
const obj = {};
Object.defineProperty(obj, "a", {
configurable: false,
enumerable: false,
value: 10,
writable: false,
});
const p = new Proxy(obj, {
get(target, property) {
return 20;
},
});
p.a; // TypeError is thrown
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `get` | 49 | 12 | 18 | No | 36 | 10 | 49 | 49 | 18 | 36 | 10 | 5.0 | 1.0 | 6.0.0 |
See also
--------
* [`Proxy`](../../proxy)
* [`Proxy()` constructor](../proxy)
* [`Reflect.get()`](../../reflect/get)
| programming_docs |
javascript Intl.ListFormat Intl.ListFormat
===============
The `Intl.ListFormat` object enables language-sensitive list formatting.
Try it
------
Constructor
-----------
[`Intl.ListFormat()`](listformat/listformat) Creates a new `Intl.ListFormat` object.
Static methods
--------------
[`Intl.ListFormat.supportedLocalesOf()`](listformat/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.ListFormat.prototype.format()`](listformat/format) Returns a language-specific formatted string representing the elements of the list.
[`Intl.ListFormat.prototype.formatToParts()`](listformat/formattoparts) Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
[`Intl.ListFormat.prototype.resolvedOptions()`](listformat/resolvedoptions) Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current [`Intl.ListFormat`](listformat) object.
Examples
--------
### Using format
The following example shows how to create a List formatter using the English language.
```
const list = ['Motorcycle', 'Bus', 'Car'];
console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list));
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat('en-GB', { style: 'short', type: 'disjunction' }).format(list));
// Motorcycle, Bus or Car
console.log(new Intl.ListFormat('en-GB', { style: 'narrow', type: 'unit' }).format(list));
// Motorcycle Bus Car
```
### Using formatToParts
The following example shows how to create a List formatter returning formatted parts
```
const list = ['Motorcycle', 'Bus', 'Car'];
console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).formatToParts(list));
// [ { "type": "element", "value": "Motorcycle" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Bus" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Car" } ];
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # listformat-objects](https://tc39.es/ecma402/#listformat-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ListFormat` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `ListFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `ListFormat` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
| `format` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
| `formatToParts` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
| `resolvedOptions` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
| `supportedLocalesOf` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl`](../intl)
* [A polyfill of `Intl.ListFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-listformat/)
javascript Intl.RelativeTimeFormat Intl.RelativeTimeFormat
=======================
The `Intl.RelativeTimeFormat` object enables language-sensitive relative time formatting.
Try it
------
Constructor
-----------
[`Intl.RelativeTimeFormat()`](relativetimeformat/relativetimeformat) Creates a new `Intl.RelativeTimeFormat` object.
Static methods
--------------
[`Intl.RelativeTimeFormat.supportedLocalesOf()`](relativetimeformat/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.RelativeTimeFormat.prototype.format()`](relativetimeformat/format) Formats a `value` and a `unit` according to the locale and formatting options of the given `Intl.RelativeTimeFormat` object.
[`Intl.RelativeTimeFormat.prototype.formatToParts()`](relativetimeformat/formattoparts) Returns an [`Array`](../array) of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
[`Intl.RelativeTimeFormat.prototype.resolvedOptions()`](relativetimeformat/resolvedoptions) Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
--------
### Basic format usage
The following example shows how to use a relative time formatter for the English language.
```
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using formatToParts
The following example shows how to create a relative time formatter returning formatted parts.
```
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using the day unit.
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]
rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # relativetimeformat-objects](https://tc39.es/ecma402/#relativetimeformat-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `RelativeTimeFormat` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `RelativeTimeFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `RelativeTimeFormat` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `format` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `formatToParts` | 71 | 79 | 70 | No | 58 | 14 | 71 | 71 | 79 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `resolvedOptions` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `supportedLocalesOf` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl`](../intl)
* [The Intl.RelativeTimeFormat API](https://v8.dev/features/intl-relativetimeformat)
* [A polyfill of `Intl.RelativeTimeFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-relativetimeformat/)
javascript Intl.Segmenter Intl.Segmenter
==============
The `Intl.Segmenter` object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.
Try it
------
Constructor
-----------
[`Intl.Segmenter()`](segmenter/segmenter) Creates a new `Intl.Segmenter` object.
Static methods
--------------
[`Intl.Segmenter.supportedLocalesOf()`](segmenter/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.Segmenter.prototype.resolvedOptions()`](segmenter/resolvedoptions) Returns a new object with properties reflecting the locale and granularity options computed during initialization of this `Intl.Segmenter` object.
[`Intl.Segmenter.prototype.segment()`](segmenter/segment) Returns a new iterable [`Segments`](segmenter/segment/segments) instance representing the segments of a string according to the locale and granularity of this `Intl.Segmenter` instance.
Examples
--------
### Basic usage and difference from String.prototype.split()
If we were to use [`String.prototype.split(" ")`](../string/split) to segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).
```
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// The two sentences are not correctly segmented.
```
```
const str = "吾輩は猫である。名前はたぬき。";
const segmenterJa = new Intl.Segmenter('ja-JP', { granularity: 'word' });
const segments = segmenterJa.segment(str);
console.table(Array.from(segments));
// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},
// etc.
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # segmenter-objects](https://tc39.es/ecma402/#segmenter-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Segmenter` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `Segmenter` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `resolvedOptions` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `segment` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `supportedLocalesOf` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
javascript Intl.Collator Intl.Collator
=============
The `Intl.Collator` object enables language-sensitive string comparison.
Try it
------
Constructor
-----------
[`Intl.Collator()`](collator/collator) Creates a new `Collator` object.
Static methods
--------------
[`Intl.Collator.supportedLocalesOf()`](collator/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.Collator.prototype.compare`](collator/compare) Getter function that compares two strings according to the sort order of this [`Intl.Collator`](collator) object.
[`Intl.Collator.prototype.resolvedOptions()`](collator/resolvedoptions) Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
Examples
--------
### Using Collator
The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:
```
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```
Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.
### Using locales
The results provided by [`Intl.Collator.prototype.compare()`](collator/compare) vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
// in German, ä sorts with a
console.log(new Intl.Collator("de").compare("ä", "z"));
// -1, or some other negative value
// in Swedish, ä sorts after z
console.log(new Intl.Collator("sv").compare("ä", "z"));
// 1, or some other positive value
```
### Using options
The results provided by [`Intl.Collator.prototype.compare()`](collator/compare) can be customized using the `options` argument:
```
// in German, ä has a as the base letter
console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a"));
// 0
// in Swedish, ä and a are separate base letters
console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"));
// 1, or some other positive value
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # collator-objects](https://tc39.es/ecma402/#collator-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Collator` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `Collator` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `Collator` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
| `compare` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl`](../intl)
javascript Intl.getCanonicalLocales() Intl.getCanonicalLocales()
==========================
The `Intl.getCanonicalLocales()` static method returns an array containing the canonical locale names. Duplicates will be omitted and elements will be validated as structurally valid language tags.
Try it
------
Syntax
------
```
Intl.getCanonicalLocales(locales)
```
### Parameters
`locales` A list of [`String`](../string) values for which to get the canonical locale names.
### Return value
An array containing the canonical locale names.
Examples
--------
### Using getCanonicalLocales
```
Intl.getCanonicalLocales('EN-US'); // ["en-US"]
Intl.getCanonicalLocales(['EN-US', 'Fr']); // ["en-US", "fr"]
Intl.getCanonicalLocales('EN\_US');
// RangeError:'EN\_US' is not a structurally valid language tag
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.getcanonicallocales](https://tc39.es/ecma402/#sec-intl.getcanonicallocales) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getCanonicalLocales` | 54 | 16 | 48 | No | 41 | 10.1 | 54 | 54 | 56 | 41 | 10.3 | 6.0 | 1.8 | 7.0.0 |
See also
--------
* [`Intl.NumberFormat.supportedLocalesOf()`](numberformat/supportedlocalesof)
* [`Intl.DateTimeFormat.supportedLocalesOf()`](datetimeformat/supportedlocalesof)
* [`Intl.Collator.supportedLocalesOf()`](collator/supportedlocalesof)
* [A polyfill of `Intl.getCanonicalLocales` in FormatJS](https://formatjs.io/docs/polyfills/intl-getcanonicallocales/)
| programming_docs |
javascript Intl.Locale Intl.Locale
===========
The `Intl.Locale` object is a standard built-in property of the Intl object that represents a Unicode locale identifier.
Try it
------
Description
-----------
The `Intl.Locale` object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a *locale identifier*. The locale identifier consists of a *language identifier* and *extension tags*. Language identifiers are the core of the locale, consisting of *language*, *script*, and *region subtags*. Additional information about the locale is stored in the optional *extension tags*. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.
Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags.
Constructor
-----------
[`Intl.Locale()`](locale/locale) Creates a new `Locale` object.
Instance properties
-------------------
[`Intl.Locale.prototype.baseName`](locale/basename) Returns basic, core information about the `Locale` in the form of a substring of the complete data string.
[`Intl.Locale.prototype.calendar`](locale/calendar) Returns the part of the `Locale` that indicates the Locale's calendar era.
[`Intl.Locale.prototype.calendars`](locale/calendars) Returns an [`Array`](../array) of available calendar identifiers, according to the locale's rules.
[`Intl.Locale.prototype.caseFirst`](locale/casefirst) Returns whether case is taken into account for the locale's collation rules.
[`Intl.Locale.prototype.collation`](locale/collation) Returns the collation type for the `Locale`, which is used to order strings according to the locale's rules.
[`Intl.Locale.prototype.collations`](locale/collations) Returns an [`Array`](../array) of the collation types for the `Locale`.
[`Intl.Locale.prototype.hourCycle`](locale/hourcycle) Returns the time keeping format convention used by the locale.
[`Intl.Locale.prototype.hourCycles`](locale/hourcycles) Returns an [`Array`](../array) of hour cycle identifiers, indicating either the 12-hour format ("h11", "h12") or the 24-hour format ("h23", "h24").
[`Intl.Locale.prototype.language`](locale/language) Returns the language associated with the locale.
[`Intl.Locale.prototype.numberingSystem`](locale/numberingsystem) Returns the numeral system used by the locale.
[`Intl.Locale.prototype.numberingSystems`](locale/numberingsystems) Returns an [`Array`](../array) of numbering system identifiers available according to the locale's rules.
[`Intl.Locale.prototype.numeric`](locale/numeric) Returns whether the locale has special collation handling for numeric characters.
[`Intl.Locale.prototype.region`](locale/region) Returns the region of the world (usually a country) associated with the locale.
[`Intl.Locale.prototype.script`](locale/script) Returns the script used for writing the particular language used in the locale.
[`Intl.Locale.prototype.textInfo`](locale/textinfo) Returns the part indicating the ordering of characters `ltr` (left-to-right) or `rtl` (right-to-left).
[`Intl.Locale.prototype.timeZones`](locale/timezones) Returns an [`Array`](../array) of time zone identifiers, associated with the `Locale`.
[`Intl.Locale.prototype.weekInfo`](locale/weekinfo) Returns [UTS 35's Week Elements](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Patterns_Week_Elements) according to the locale rules.
Instance methods
----------------
[`Intl.Locale.prototype.maximize()`](locale/maximize) Gets the most likely values for the language, script, and region of the locale based on existing values.
[`Intl.Locale.prototype.minimize()`](locale/minimize) Attempts to remove information about the locale that would be added by calling [`maximize()`](locale/maximize).
[`Intl.Locale.prototype.toString()`](locale/tostring) Returns the Locale's full locale identifier string.
Examples
--------
### Basic usage
At its very simplest, the [`Intl.Locale()`](locale/locale) constructor takes a locale identifier string as its argument:
```
const us = new Intl.Locale('en-US');
```
### Using the Locale constructor with an options object
The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the [`hourCycle`](locale/hourcycle) property of the configuration object to your desired hour cycle type, and then pass it into the constructor:
```
const us12hour = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(us12hour.hourCycle); // Prints "h12"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # locale-objects](https://tc39.es/ecma402/#locale-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Locale` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `Locale` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `baseName` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `calendar` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `calendars` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `caseFirst` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `collation` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `collations` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `hourCycle` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `hourCycles` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `language` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `maximize` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `minimize` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `numberingSystem` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `numberingSystems` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `numeric` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `region` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `script` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `textInfo` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `timeZones` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
| `toString` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
| `weekInfo` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl`](../intl)
* [The Intl.Locale Polyfill](https://formatjs.io/docs/polyfills/intl-locale/)
* [Unicode locale identifiers spec](https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers)
javascript Intl.DisplayNames Intl.DisplayNames
=================
The `Intl.DisplayNames` object enables the consistent translation of language, region and script display names.
Try it
------
Constructor
-----------
[`Intl.DisplayNames()`](displaynames/displaynames) Creates a new `Intl.DisplayNames` object.
Static methods
--------------
[`Intl.DisplayNames.supportedLocalesOf()`](displaynames/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.DisplayNames.prototype.of()`](displaynames/of) This method receives a `code` and returns a string based on the locale and options provided when instantiating `Intl.DisplayNames`.
[`Intl.DisplayNames.prototype.resolvedOptions()`](displaynames/resolvedoptions) Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
--------
### Region Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a region code.
```
// Get display names of region in English
let regionNames = new Intl.DisplayNames(['en'], {type: 'region'});
regionNames.of('419'); // "Latin America"
regionNames.of('BZ'); // "Belize"
regionNames.of('US'); // "United States"
regionNames.of('BA'); // "Bosnia & Herzegovina"
regionNames.of('MM'); // "Myanmar (Burma)"
// Get display names of region in Traditional Chinese
regionNames = new Intl.DisplayNames(['zh-Hant'], {type: 'region'});
regionNames.of('419'); // "拉丁美洲"
regionNames.of('BZ'); // "貝里斯"
regionNames.of('US'); // "美國"
regionNames.of('BA'); // "波士尼亞與赫塞哥維納"
regionNames.of('MM'); // "緬甸"
```
### Language Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a language-script-region sequence.
```
// Get display names of language in English
let languageNames = new Intl.DisplayNames(['en'], {type: 'language'});
languageNames.of('fr'); // "French"
languageNames.of('de'); // "German"
languageNames.of('fr-CA'); // "Canadian French"
languageNames.of('zh-Hant'); // "Traditional Chinese"
languageNames.of('en-US'); // "American English"
languageNames.of('zh-TW'); // "Chinese (Taiwan)"]
// Get display names of language in Traditional Chinese
languageNames = new Intl.DisplayNames(['zh-Hant'], {type: 'language'});
languageNames.of('fr'); // "法文"
languageNames.of('zh'); // "中文"
languageNames.of('de'); // "德文"
```
### Script Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a script code.
```
// Get display names of script in English
let scriptNames = new Intl.DisplayNames(['en'], {type: 'script'});
// Get script names
scriptNames.of('Latn'); // "Latin"
scriptNames.of('Arab'); // "Arabic"
scriptNames.of('Kana'); // "Katakana"
// Get display names of script in Traditional Chinese
scriptNames = new Intl.DisplayNames(['zh-Hant'], {type: 'script'});
scriptNames.of('Latn'); // "拉丁文"
scriptNames.of('Arab'); // "阿拉伯文"
scriptNames.of('Kana'); // "片假名"
```
### Currency Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for currency code.
```
// Get display names of currency code in English
let currencyNames = new Intl.DisplayNames(['en'], {type: 'currency'});
// Get currency names
currencyNames.of('USD'); // "US Dollar"
currencyNames.of('EUR'); // "Euro"
currencyNames.of('TWD'); // "New Taiwan Dollar"
currencyNames.of('CNY'); // "Chinese Yuan"
// Get display names of currency code in Traditional Chinese
currencyNames = new Intl.DisplayNames(['zh-Hant'], {type: 'currency'});
currencyNames.of('USD'); // "美元"
currencyNames.of('EUR'); // "歐元"
currencyNames.of('TWD'); // "新台幣"
currencyNames.of('CNY'); // "人民幣"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # intl-displaynames-objects](https://tc39.es/ecma402/#intl-displaynames-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `DisplayNames` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
| `DisplayNames` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
| `of` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
| `resolvedOptions` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
| `supportedLocalesOf` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
See also
--------
* [`Intl`](../intl)
javascript Intl.supportedValuesOf() Intl.supportedValuesOf()
========================
The `Intl.supportedValuesOf()` static method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation.
Duplicates are omitted and the array is sorted in ascending alphabetic order (or more precisely, using [`Array.prototype.sort()`](../array/sort) with an `undefined` compare function)
The method can be used to feature-test whether values are supported in a particular implementation and download a polyfill only if necessary. It can also be used to build UIs that allow users to select their preferred localized values, for example when the UI is created from WebGL or server-side.
Try it
------
Syntax
------
```
Intl.supportedValuesOf(key)
```
### Parameters
`key` A key string indicating the category of values to be returned. This is one of: `"calendar"`, `"collation"`, `"currency"`,`"numberingSystem"`, `"timeZone"`, `"unit"`.
### Return value
A sorted array of unique string values indicating the values supported by the implementation for the given key.
### Exceptions
`RangeError` An unsupported key was passed as a parameter.
Examples
--------
### Feature testing
You can check that the method is supported by comparing to `undefined`:
```
if (typeof Intl.supportedValuesOf !== 'undefined') {
// method is supported
}
```
### Get all values for key
To get the supported values for calendar you call the method with the key `"calendar"`. You can then iterate through the returned array as shown below:
```
Intl.supportedValuesOf("calendar").forEach((calendar) => {
// "buddhist", "chinese", "coptic", "dangi", etc.
});
```
**Note:** The array returned for calendar values will always include the value "gregory" (gregorian).
The other values are all obtained in the same way:
```
Intl.supportedValuesOf("collation").forEach((collation) => {
// "big5han", "compat", "dict", "emoji", etc.
});
Intl.supportedValuesOf("currency").forEach((currency) => {
// "ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", etc.
});
Intl.supportedValuesOf("numberingSystem").forEach((numberingSystem) => {
// "adlm", "ahom", "arab", "arabext", "bali", etc.
});
Intl.supportedValuesOf("timeZone").forEach((timeZone) => {
// "Africa/Abidjan", "Africa/Accra", "Africa/Addis\_Ababa", "Africa/Algiers", etc.
});
Intl.supportedValuesOf("unit").forEach((unit) => {
// "acre", "bit", "byte", "celsius", "centimeter", etc.
});
```
### Invalid key throws RangeError
```
try {
Intl.supportedValuesOf("someInvalidKey");
} catch (err) {
//Error: RangeError: invalid key: "someInvalidKey"
}
```
Specifications
--------------
| Specification |
| --- |
| [Intl Enumeration API Specification # sec-intl.supportedvaluesof](https://tc39.es/proposal-intl-enumeration/#sec-intl.supportedvaluesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedValuesOf` | 99 | 99 | 93 | No | 85 | 15.4 | 99 | 99 | 93 | 68 | 15.4 | 18.0 | 1.19 | 18.0.0 |
See also
--------
* [`Intl`](../intl)
* [A polyfill of `Intl.supportedValuesOf` in FormatJS](https://github.com/formatjs/formatjs/tree/main/packages/intl-enumerator)
javascript Intl.NumberFormat Intl.NumberFormat
=================
The `Intl.NumberFormat` object enables language-sensitive number formatting.
Try it
------
Constructor
-----------
[`Intl.NumberFormat()`](numberformat/numberformat) Creates a new `NumberFormat` object.
Static methods
--------------
[`Intl.NumberFormat.supportedLocalesOf()`](numberformat/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.NumberFormat.prototype.format()`](numberformat/format) Getter function that formats a number according to the locale and formatting options of this [`Intl.NumberFormat`](numberformat) object.
[`Intl.NumberFormat.prototype.formatToParts()`](numberformat/formattoparts) Returns an [`Array`](../array) of objects representing the number string in parts that can be used for custom locale-aware formatting.
[`Intl.NumberFormat.prototype.formatRange()`](numberformat/formatrange) Getter function that formats a range of numbers according to the locale and formatting options of the [`Intl.NumberFormat`](numberformat) object from which the method is called.
[`Intl.NumberFormat.prototype.formatRangeToParts()`](numberformat/formatrangetoparts) Returns an [`Array`](../array) of objects representing the range of number strings in parts that can be used for custom locale-aware formatting.
[`Intl.NumberFormat.prototype.resolvedOptions()`](numberformat/resolvedoptions) Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
Examples
--------
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
const number = 3500;
console.log(new Intl.NumberFormat().format(number));
// '3,500' if in US English locale
```
### Using locales
This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
const number = 123456.789;
// German uses comma as decimal separator and period for thousands
console.log(new Intl.NumberFormat('de-DE').format(number));
// 123.456,789
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.NumberFormat('ar-EG').format(number));
// ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
console.log(new Intl.NumberFormat('en-IN').format(number));
// 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(number));
// 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.NumberFormat(['ban', 'id']).format(number));
// 123.456,789
```
### Using options
The results can be customized using the [`options`](numberformat/numberformat#options) argument:
```
const number = 123456.789;
// request a currency format
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// 123.456,79 €
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// ¥123,457
// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// 1,23,000
// Formatting with units
console.log(new Intl.NumberFormat('pt-PT', {
style: 'unit',
unit: 'kilometer-per-hour'
}).format(50));
// 50 km/h
console.log((16).toLocaleString('en-GB', {
style: 'unit',
unit: 'liter',
unitDisplay: 'long',
}));
// 16 litres
```
For an exhaustive list of options, see the [`Intl.NumberFormat()` constructor](numberformat/numberformat#options) page.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # numberformat-objects](https://tc39.es/ecma402/#numberformat-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `NumberFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `NumberFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `NumberFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `format` | 24 | 12
Before Edge 18, numbers are rounded to 15 decimal digits. For example, `new Intl.NumberFormat('en-US').format(1000000000000005)` returns `"1,000,000,000,000,010"`. | 29 | 11
In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, `new Intl.NumberFormat('en-US').format(1000000000000005)` returns `"1,000,000,000,000,010"`. | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `formatRange` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
| `formatRangeToParts` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
| `formatToParts` | 64 | 12 | 58 | No | 51 | 13 | 64 | 64 | 58 | 47 | 13 | 9.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl`](../intl)
* [A polyfill of `Intl.NumberFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-numberformat/)
| programming_docs |
javascript Intl.PluralRules Intl.PluralRules
================
The `Intl.PluralRules` object enables plural-sensitive formatting and plural-related language rules.
Constructor
-----------
[`Intl.PluralRules()`](pluralrules/pluralrules) Creates a new `Intl.PluralRules` object.
Static methods
--------------
[`Intl.PluralRules.supportedLocalesOf()`](pluralrules/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.PluralRules.prototype.resolvedOptions()`](pluralrules/resolvedoptions) Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
[`Intl.PluralRules.prototype.select()`](pluralrules/select) Returns a string indicating which plural rule to use for locale-aware formatting.
[`Intl.PluralRules.prototype.selectRange()`](pluralrules/selectrange) This method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.
Examples
--------
### Using locales
This example shows some of the variations in localized plural rules. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
// Arabic has different plural rules
new Intl.PluralRules('ar-EG').select(0);
// → 'zero'
new Intl.PluralRules('ar-EG').select(1);
// → 'one'
new Intl.PluralRules('ar-EG').select(2);
// → 'two'
new Intl.PluralRules('ar-EG').select(6);
// → 'few'
new Intl.PluralRules('ar-EG').select(18);
// → 'many'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # pluralrules-objects](https://tc39.es/ecma402/#pluralrules-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `PluralRules` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 13.0.0
10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `PluralRules` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `PluralRules` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
| `resolvedOptions` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
| `select` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
| `selectRange` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
| `supportedLocalesOf` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
See also
--------
* [`Intl`](../intl)
* [A polyfill of `Intl.PluralRules` in FormatJS](https://formatjs.io/docs/polyfills/intl-pluralrules/)
javascript Intl.DateTimeFormat Intl.DateTimeFormat
===================
The `Intl.DateTimeFormat` object enables language-sensitive date and time formatting.
Try it
------
Constructor
-----------
[`Intl.DateTimeFormat()`](datetimeformat/datetimeformat) Creates a new `Intl.DateTimeFormat` object.
Static methods
--------------
[`Intl.DateTimeFormat.supportedLocalesOf()`](datetimeformat/supportedlocalesof) Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance methods
----------------
[`Intl.DateTimeFormat.prototype.format()`](datetimeformat/format) Getter function that formats a date according to the locale and formatting options of this [`DateTimeFormat`](datetimeformat) object.
[`Intl.DateTimeFormat.prototype.formatToParts()`](datetimeformat/formattoparts) Returns an [`Array`](../array) of objects representing the date string in parts that can be used for custom locale-aware formatting.
[`Intl.DateTimeFormat.prototype.resolvedOptions()`](datetimeformat/resolvedoptions) Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
[`Intl.DateTimeFormat.prototype.formatRange()`](datetimeformat/formatrange) This method receives two [Dates](../date) and formats the date range in the most concise way based on the locale and options provided when instantiating [`DateTimeFormat`](datetimeformat).
[`Intl.DateTimeFormat.prototype.formatRangeToParts()`](datetimeformat/formatrangetoparts) This method receives two [Dates](../date) and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
Examples
--------
### Using DateTimeFormat
In basic use without specifying a locale, `DateTimeFormat` uses the default locale and default options.
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los\_Angeles (UTC-0800)
```
### Using locales
This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Results below use the time zone of America/Los\_Angeles (UTC-0800, Pacific Standard Time)
// US English uses month-day-year order
console.log(new Intl.DateTimeFormat('en-US').format(date));
// "12/19/2012"
// British English uses day-month-year order
console.log(new Intl.DateTimeFormat('en-GB').format(date));
// "19/12/2012"
// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat('ko-KR').format(date));
// "2012. 12. 19."
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat('ar-EG').format(date));
// "١٩/١٢/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date));
// "24/12/19"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// "19/12/2012"
```
### Using options
The date and time formats can be customized using the `options` argument:
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
// request a weekday along with a long date
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
// "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// "Thursday, December 20, 2012, GMT"
// sometimes you want to be more precise
options = {
hour: 'numeric', minute: 'numeric', second: 'numeric',
timeZone: 'Australia/Sydney',
timeZoneName: 'short'
};
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// "2:00:00 pm AEDT"
// sometimes you want to be very precise
options.fractionalSecondDigits = 3; //number digits for fraction-of-seconds
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// "2:00:00.200 pm AEDT"
// sometimes even the US needs 24-hour time
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false,
timeZone: 'America/Los\_Angeles'
};
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// "12/19/2012, 19:00:00"
// to specify options but use the browser's default locale, use 'default'
console.log(new Intl.DateTimeFormat('default', options).format(date));
// "12/19/2012, 19:00:00"
// sometimes it's helpful to include the period of the day
options = {hour: "numeric", dayPeriod: "short"};
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// 10 at night
```
The used calendar and numbering formats can also be set independently via `options` arguments:
```
const options = {calendar: 'chinese', numberingSystem: 'arab'};
const dateFormat = new Intl.DateTimeFormat('default', options);
const usedOptions = dateFormat.resolvedOptions();
console.log(usedOptions.calendar);
// "chinese"
console.log(usedOptions.numberingSystem);
// "arab"
console.log(usedOptions.timeZone);
// "America/New\_York" (the users default timezone)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # datetimeformat-objects](https://tc39.es/ecma402/#datetimeformat-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `DateTimeFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `DateTimeFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `DateTimeFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `format` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `formatRange` | 76 | 79 | 91 | No | 63 | 14.1 | 76 | 76 | 91 | 54 | 14.5 | 12.0 | 1.8 | 12.9.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `formatRangeToParts` | 76 | 79 | 91 | No | 63 | 14.1 | 76 | 76 | 91 | 54 | 14.5 | 12.0 | 1.8 | 12.9.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `formatToParts` | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 18 | 51 | No | 44
Before version 58, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 58 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 11 | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 56 | 43
Before version 50, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 50 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 11 | 7.0
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 1.8 | 8.0.0
["Before version 12.0.0, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 12.0.0 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351).", "Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details."] |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl`](../intl)
* [A polyfill of `Intl.DateTimeFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-datetimeformat/)
javascript Intl.Locale.prototype.calendars Intl.Locale.prototype.calendars
===============================
The `Intl.Locale.prototype.calendars` accessor property returns a list of one or more unique calendar identifiers for the `Locale`.
Description
-----------
The `calendars` property returns an array of all calendars commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has a [`calendar`](calendar), then the returned array contains that single value.
Below is a list of the supported calendar era types.
### Supported calendar types
`buddhist` Thai Buddhist calendar
`chinese` Traditional Chinese calendar
`coptic` Coptic calendar
`dangi` Traditional Korean calendar
`ethioaa` Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E)
`ethiopic` Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.)
`gregory` Gregorian calendar
`hebrew` Traditional Hebrew calendar
`indian` Indian calendar
`islamic` Islamic calendar
`islamic-umalqura` Islamic calendar, Umm al-Qura
`islamic-tbla` Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch)
`islamic-civil` Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch)
`islamic-rgsa` Islamic calendar, Saudi Arabia sighting
`iso8601` ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules)
`japanese` Japanese Imperial calendar
`persian` Persian calendar
`roc` Civil (algorithmic) Arabic calendar
`islamicc` Civil (algorithmic) Arabic calendar
**Warning:** The `islamicc` calendar key has been deprecated. Please use `islamic-civil`.
Examples
--------
### Obtaining supported calendars
If the `Locale` object doesn't have a `calendar` already, the `calendars` property lists all commonly-used calendars for the given `Locale`. For examples of explicitly setting a `calendar`, see [`calendar` examples](calendar#examples).
```
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.calendars); // ["gregory", "coptic", "islamic", "islamic-civil", "islamic-tbla"]
```
```
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.calendars); // ["gregory", "japanese"]
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.calendars](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.calendars) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `calendars` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.calendar`](calendar)
* [Unicode Calendar Identifiers](https://www.unicode.org/reports/tr35/#UnicodeCalendarIdentifier)
javascript Intl.Locale.prototype.numeric Intl.Locale.prototype.numeric
=============================
The `Intl.Locale.prototype.numeric` property is an accessor property that returns whether the locale has special collation handling for numeric characters.
Description
-----------
Like [`caseFirst`](casefirst), `numeric` represents a modification to the collation rules utilized by the locale. `numeric` is a boolean value, which means that it can be either `true` or `false`. If `numeric` is set to `false`, there will be no special handling of numeric values in strings. If `numeric` is set to `true`, then the locale will take numeric characters into account when collating strings. This special numeric handling means that sequences of decimal digits will be compared as numbers. For example, the string "A-21" will be considered less than "A-123".
Examples
--------
### Setting the numeric value via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), the values that `numeric` represents correspond to the key `kn`. `kn` is considered a locale string "extension subtag". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension key. Thus, the `numeric` value can be added to the initial locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. To set the `numeric` value, first add the `-u` extension key to the string. Next, add the `-kn` extension key to indicate that you are adding a value for `numeric`. Finally, add the `numeric` value to the string. If you want to set `numeric` to `true`, adding the `kn` key will suffice. To set the value to `false`, you must specify in by adding `"false"` after the `kn` key.
```
const locale = new Intl.Locale("fr-Latn-FR-u-kn-false");
console.log(locale.numeric); // Prints "false"
```
### Setting the numeric value via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can be used to pass extension types. Set the `numeric` property of the configuration object to your desired `numeric` value and pass it into the constructor.
```
const locale = new Intl.Locale("en-Latn-US", { numeric: true });
console.log(locale.numeric); // Prints "true"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.numeric](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.numeric) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `numeric` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
| programming_docs |
javascript Intl.Locale.prototype.minimize() Intl.Locale.prototype.minimize()
================================
The `Intl.Locale.prototype.minimize()` method attempts to remove information about the locale that would be added by calling [`maximize()`](maximize).
Try it
------
Syntax
------
```
minimize()
```
### Return value
A [`Locale`](../locale) instance whose `baseName` property returns the result of the [Remove Likely Subtags](https://www.unicode.org/reports/tr35/#Likely_Subtags) algorithm executed against *[`locale.baseName`](basename)*.
Description
-----------
This method carries out the reverse of [`maximize()`](maximize), removing any language, script, or region subtags from the locale language identifier (essentially the contents of `baseName`). This is useful when there are superfluous subtags in the language identifier; for instance, "en-Latn" can be simplified to "en", since "Latn" is the only script used to write English. `minimize()` only affects the main subtags that comprise the [language identifier](https://www.unicode.org/reports/tr35/#Language_Locale_Field_Definitions): language, script, and region subtags. Other subtags after the "-u" in the locale identifier are called extension subtags and are not affected by the `minimize()` method. Examples of these subtags include [`hourCycle`](hourcycle), [`calendar`](calendar), and [`numeric`](numeric).
Examples
--------
### Using minimize
```
const myLocale = new Intl.Locale("fr-Latn-FR", {
hourCycle: "h24",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr-Latn-FR"
console.log(myLocale.toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24"
const myLocMinimized = myLocale.minimize();
// Prints "fr", since French is only written in the Latin script
// and is most likely to be spoken in France.
console.log(myLocMinimized.baseName);
// Prints "fr-u-ca-gregory-hc-h24".
// Note that the extension tags (after "-u") remain unchanged.
console.log(myLocMinimized.toString());
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.minimize](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.minimize) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `minimize` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`baseName`](basename)
javascript Intl.Locale.prototype.weekInfo Intl.Locale.prototype.weekInfo
==============================
The `Intl.Locale.prototype.weekInfo` property is an accessor property which returns a `weekInfo` object with the properties `firstDay`, `weekend` and `minimalDays` for the associated `Locale`.
Description
-----------
Returns the `Locale` information associated with the Locale data specified in [UTS 35's Week Elements.](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Patterns_Week_Elements).
Examples
--------
### Obtaining the Week Information
Return the week information for a given `Locale`.
```
const he = new Intl.Locale("he");
console.log(he.weekInfo); // { firstDay: 7, weekend: [5, 6], minimalDays: 1 }
const af = new Intl.Locale("af");
console.log(af.weekInfo); // { firstDay: 7, weekend: [6, 7], minimalDays: 1 }
const enGB = new Intl.Locale("en-GB");
console.log(enGB.weekInfo) // { firstDay: 1, weekend: [6, 7], minimalDays: 4 }
const msBN = new Intl.Locale("ms-BN");
console.log(msBN.weekInfo) // { firstDay: 7, weekend: [5, 7], minimalDays: 1 }
// Brunei weekend is Friday and Sunday but not Saturday
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.weekInfo](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.weekInfo) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `weekInfo` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
javascript Intl.Locale.prototype.region Intl.Locale.prototype.region
============================
The `Intl.Locale.prototype.region` property is an accessor property that returns the region of the world (usually a country) associated with the locale.
Description
-----------
The region is an essential part of the locale identifier, as it places the locale in a specific area of the world. Knowing the locale's region is vital to identifying differences between locales. For example, English is spoken in the United Kingdom and the United States of America, but there are differences in spelling and other language conventions between those two countries. Knowing the locale's region helps JavaScript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world.
Examples
--------
### Setting the region in the locale identifier string argument
The region is the third part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. The region is a mandatory part of a
```
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.region); // Prints "US"
```
### Setting the region via the configuration object
The [`Intl.Locale()`](locale) constructor takes a configuration object, which can be used to set the region subtag and property.
```
const locale = new Intl.Locale("fr-Latn", { region: "FR" });
console.log(locale.region); // Prints "FR"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.region](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.region) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `region` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [Unicode region chart](https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/territory_containment_un_m_49.html)
javascript Intl.Locale.prototype.caseFirst Intl.Locale.prototype.caseFirst
===============================
The `Intl.Locale.prototype.caseFirst` property is an accessor property that returns whether case is taken into account for the locale's collation rules.
Description
-----------
A locale's collation rules are used to determine how strings are ordered in that locale. Certain locales use a character's case (UPPERCASE or lowercase) in the collation process. This additional rule can be expressed in a [`Locale's`](../locale) `caseFirst` property.
There are 3 values that the `caseFirst` property can have, outlined in the table below.
###
`caseFirst` values
| Value | Description |
| --- | --- |
| `upper` | Upper case to be sorted before lower case. |
| `lower` | Lower case to be sorted before upper case. |
| `false` | No special case ordering. |
Examples
--------
### Setting the caseFirst value via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), the values that `caseFirst` represents correspond to the key `kf`. `kf` is treated as a locale string "extension subtag". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension key. Thus, the `caseFirst` value can be added to the initial locale identifier string that is passed into the `Locale` constructor. To add the `caseFirst` value, first add the `-u` extension key to the string. Next, add the `-kf` extension key to indicate that you are adding a value for `caseFirst`. Finally, add the `caseFirst` value to the string.
```
const locale = new Intl.Locale("fr-Latn-FR-u-kf-upper");
console.log(locale.caseFirst); // Prints "upper"
```
### Setting the caseFirst value via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can be used to pass extension types. Set the `caseFirst` property of the configuration object to your desired `caseFirst` value, and then pass it into the constructor.
```
const locale = new Intl.Locale("en-Latn-US", { caseFirst: "lower" });
console.log(locale.caseFirst); // Prints "lower"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.caseFirst](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.caseFirst) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `caseFirst` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [Unicode case first collation spec](https://github.com/unicode-org/cldr/blob/main/common/bcp47/collation.xml#L49)
javascript Intl.Locale.prototype.calendar Intl.Locale.prototype.calendar
==============================
The `Intl.Locale.prototype.calendar` accessor property returns the calendar type for the `Locale`.
Description
-----------
While most of the world uses the Gregorian calendar, there are several regional calendar eras used around the world. The `calendar` property's value is set at construction time, either through the `ca` key of the locale identifier or through the `calendar` option of the [`Intl.Locale()`](locale) constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported calendar types, see [`Intl.Locale.prototype.calendars`](calendars#supported_calendar_types).
The set accessor of `calendar` is `undefined`. You cannot change this property directly.
Examples
--------
Like other locale subtags, the calendar type can be added to the [`Intl.Locale`](../locale) object via the locale string, or a configuration object argument to the constructor.
### Adding a calendar type via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), calendar era types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the calendar era type can be added to the initial locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. To add the calendar type, first add the `-u` extension to the string. Next, add the `-ca` extension to indicate that you are adding a calendar type. Finally, add the calendar era type to the string.
```
const locale = new Intl.Locale("fr-FR-u-ca-buddhist");
console.log(locale.calendar); // Prints "buddhist"
```
### Adding a calendar type via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can contain any of several extension types, including calendars. Set the `calendar` property of the configuration object to your desired calendar era, and then pass it into the constructor.
```
const locale = new Intl.Locale("fr-FR", { calendar: "buddhist" });
console.log(locale.calendar); // "buddhist"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.calendar](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.calendar) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `calendar` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.calendars`](calendars)
* [Unicode Calendar Identifiers](https://www.unicode.org/reports/tr35/#UnicodeCalendarIdentifier)
javascript Intl.Locale.prototype.baseName Intl.Locale.prototype.baseName
==============================
The `Intl.Locale.prototype.baseName` property returns a substring of the `Locale`'s string representation, containing core information about the `Locale`.
Description
-----------
An [`Intl.Locale`](../locale) object represents a parsed local and options for that locale. The `baseName` property returns basic, core information about the Locale in the form of a substring of the complete data string. Specifically, the property returns the substring containing the language, and the script and region if available.
`baseName` returns the `language ["-" script] ["-" region] *("-" variant)` subsequence of the [unicode\_language\_id grammar](https://www.unicode.org/reports/tr35/#Identifiers).
Examples
--------
### Basic Example
```
const myLoc = new Intl.Locale("fr-Latn-CA"); // Sets locale to Canadian French
console.log(myLoc.toString()); // Prints out "fr-Latn-CA-u-ca-gregory"
console.log(myLoc.baseName); // Prints out "fr-Latn-CA"
```
### Example with options in the input string
```
// Sets language to Japanese, region to Japan,
// calendar to Gregorian, hour cycle to 24 hours
const japan = new Intl.Locale("ja-JP-u-ca-gregory-hc-24");
console.log(japan.toString()); // Prints out "ja-JP-u-ca-gregory-hc-h24"
console.log(japan.baseName); // Prints out "ja-JP"
```
### Example with options that override input string
```
// Input string indicates language as Dutch and region as Belgium,
// but options object overrides the region and sets it to the Netherlands
const dutch = new Intl.Locale("nl-Latn-BE", { region: "NL" });
console.log(dutch.baseName); // Prints out "nl-Latn-NL"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.baseName](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.baseName) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `baseName` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
javascript Intl.Locale.prototype.numberingSystems Intl.Locale.prototype.numberingSystems
======================================
The `Intl.Locale.prototype.numberingSystems` accessor property returns a list of one or more unique [numbering system](https://en.wikipedia.org/wiki/Numeral_system) identifiers for the `Locale`.
Description
-----------
A numeral system is a system for expressing numbers. The `numberingSystems` property returns an array of all numbering systems commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has a [`numberingSystem`](numberingsystem), then the returned array contains that single value.
A table of the standard Unicode numeral systems can be seen below.
### Supported numbering system types
| Value | Description |
| --- | --- |
| adlm | Adlam digits |
| ahom | Ahom digits |
| arab | Arabic-Indic digits |
| arabext | Extended Arabic-Indic digits |
| armn | Armenian upper case numerals — algorithmic |
| armnlow | Armenian lower case numerals — algorithmic |
| bali | Balinese digits |
| beng | Bengali digits |
| bhks | Bhaiksuki digits |
| brah | Brahmi digits |
| cakm | Chakma digits |
| cham | Cham digits |
| cyrl | Cyrillic numerals — algorithmic |
| deva | Devanagari digits |
| ethi | Ethiopic numerals — algorithmic |
| finance | Financial numerals — may be algorithmic |
| fullwide | Full width digits |
| geor | Georgian numerals — algorithmic |
| gong | Gunjala Gondi digits |
| gonm | Masaram Gondi digits |
| grek | Greek upper case numerals — algorithmic |
| greklow | Greek lower case numerals — algorithmic |
| gujr | Gujarati digits |
| guru | Gurmukhi digits |
| hanidays | Han-character day-of-month numbering for lunar/other traditional calendars |
| hanidec | Positional decimal system using Chinese number ideographs as digits |
| hans | Simplified Chinese numerals — algorithmic |
| hansfin | Simplified Chinese financial numerals — algorithmic |
| hant | Traditional Chinese numerals — algorithmic |
| hantfin | Traditional Chinese financial numerals — algorithmic |
| hebr | Hebrew numerals — algorithmic |
| hmng | Pahawh Hmong digits |
| hmnp | Nyiakeng Puachue Hmong digits |
| java | Javanese digits |
| jpan | Japanese numerals — algorithmic |
| jpanfin | Japanese financial numerals — algorithmic |
| jpanyear | Japanese first-year Gannen numbering for Japanese calendar |
| kali | Kayah Li digits |
| khmr | Khmer digits |
| knda | Kannada digits |
| lana | Tai Tham Hora (secular) digits |
| lanatham | Tai Tham (ecclesiastical) digits |
| laoo | Lao digits |
| latn | Latin digits |
| lepc | Lepcha digits |
| limb | Limbu digits |
| mathbold | Mathematical bold digits |
| mathdbl | Mathematical double-struck digits |
| mathmono | Mathematical monospace digits |
| mathsanb | Mathematical sans-serif bold digits |
| mathsans | Mathematical sans-serif digits |
| mlym | Malayalam digits |
| modi | Modi digits |
| mong | Mongolian digits |
| mroo | Mro digits |
| mtei | Meetei Mayek digits |
| mymr | Myanmar digits |
| mymrshan | Myanmar Shan digits |
| mymrtlng | Myanmar Tai Laing digits |
| native | Native digits |
| newa | Newa digits |
| nkoo | N'Ko digits |
| olck | Ol Chiki digits |
| orya | Oriya digits |
| osma | Osmanya digits |
| rohg | Hanifi Rohingya digits |
| roman | Roman upper case numerals — algorithmic |
| romanlow | Roman lowercase numerals — algorithmic |
| saur | Saurashtra digits |
| shrd | Sharada digits |
| sind | Khudawadi digits |
| sinh | Sinhala Lith digits |
| sora | Sora\_Sompeng digits |
| sund | Sundanese digits |
| takr | Takri digits |
| talu | New Tai Lue digits |
| taml | Tamil numerals — algorithmic |
| tamldec | Modern Tamil decimal digits |
| telu | Telugu digits |
| thai | Thai digits |
| tirh | Tirhuta digits |
| tibt | Tibetan digits |
| traditio | Traditional numerals — may be algorithmic |
| vaii | Vai digits |
| wara | Warang Citi digits |
| wcho | Wancho digits |
Examples
--------
### Obtaining supported numbering systems
If the `Locale` object doesn't have a `numberingSystem` already, the `numberingSystems` property lists all commonly-used numbering systems for the given `Locale`. For examples of explicitly setting a `numberingSystem`, see [`numberingSystem` examples](numberingsystem#examples).
```
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.numberingSystems); // ["arab"]
```
```
const ja = new Intl.Locale("ja");
console.log(ja.numberingSystems); // ["latn"]
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.numberingSystems](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.numberingSystems) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `numberingSystems` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.numberingSystem`](numberingsystem)
* [Details on the standard Unicode numeral systems](https://github.com/unicode-org/cldr/blob/main/common/supplemental/numberingSystems.xml)
| programming_docs |
javascript Intl.Locale.prototype.numberingSystem Intl.Locale.prototype.numberingSystem
=====================================
The `Intl.Locale.prototype.numberingSystem` accessor property returns the [numeral system](https://en.wikipedia.org/wiki/Numeral_system) for the locale.
Description
-----------
A numeral system is a system for expressing numbers. The `numberingSystem` property's value is set at construction time, either through the `nu` key of the locale identifier or through the `numberingSystem` option of the [`Intl.Locale()`](locale) constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported numbering system types, see [`Intl.Locale.prototype.numberingSystems`](numberingsystems#supported_numbering_system_types).
Examples
--------
Like other locale subtags, the numbering system type can be added to the [`Intl.Locale`](../locale) object via the locale string, or a configuration object argument to the constructor.
### Adding a numbering system via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), numbering system types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the numbering system type can be added to the initial locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. To add the numbering system type, first add the `-u` extension key to the string. Next, add the `-nu` extension to indicate that you are adding a numbering system. Finally, add the numbering system type to the string.
```
const locale = new Intl.Locale("fr-Latn-FR-u-nu-mong");
console.log(locale.numberingSystem); // "mong"
```
### Adding a numbering system via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can contain any of several extension types, including numbering system types. Set the `numberingSystem` property of the configuration object to your desired numbering system type, and then pass it into the constructor.
```
const locale = new Intl.Locale("en-Latn-US", { numberingSystem: "latn" });
console.log(locale.numberingSystem); // "latn"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.numberingSystem](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.numberingSystem) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `numberingSystem` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.numberingSystems`](numberingsystems)
* [Details on the standard Unicode numeral systems](https://github.com/unicode-org/cldr/blob/main/common/supplemental/numberingSystems.xml)
javascript Intl.Locale.prototype.timeZones Intl.Locale.prototype.timeZones
===============================
The `Intl.Locale.prototype.timeZones` accessor property returns a list of supported time zones for the `Locale`.
Description
-----------
Returns an array with supported time zones for the associated `Locale`, where each value is an [IANA time zone canonical name](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database), sorted in alphabetical order. If the locale identifier does not contain a region subtag, the returned value is `undefined`.
Examples
--------
### Obtaining supported time zones
List supported time zones for a given `Locale`.
```
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.timeZones); // ["Africa/Cairo"]
```
```
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.timeZones); // ["Asia/Tokyo"]
```
```
const ar = new Intl.Locale("ar");
console.log(ar.timeZones); // undefined
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.timeZones](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.timeZones) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `timeZones` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
* [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database)
javascript Intl.Locale() constructor Intl.Locale() constructor
=========================
The `Intl.Locale` constructor is a standard built-in property of the Intl object that represents a Unicode locale identifier.
Try it
------
Syntax
------
```
new Intl.Locale(tag)
new Intl.Locale(tag, options)
```
**Note:** `Intl.Locale()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`tag` The Unicode locale identifier string.
`options` An object that contains configuration for the Locale. Keys are Unicode locale tags, values are valid Unicode tag values. Option values here take priority over extension keys in the locale identifier.
Examples
--------
### Basic usage
At its very simplest, the [`Intl.Locale()`](locale) constructor takes a locale identifier string as its argument:
```
const us = new Intl.Locale('en-US');
```
### Using the Locale constructor with an options object
The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the [`hourCycle`](hourcycle) property of the configuration object to your desired hour cycle type, and then pass it into the constructor:
```
const locale = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(locale.hourCycle); // "h12"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-locale-constructor](https://tc39.es/ecma402/#sec-intl-locale-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Locale` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Collator`](../collator)
* [Unicode locale identifiers spec](https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers)
* [A polyfill of `Intl.Locale` in FormatJS](https://formatjs.io/docs/polyfills/intl-locale/)
javascript Intl.Locale.prototype.textInfo Intl.Locale.prototype.textInfo
==============================
The `Intl.Locale.prototype.textInfo` property is an accessor property which returns the ordering of characters indicated by either `ltr` (left-to-right) or by `rtl` (right-to-left) for the associated `Locale`.
Description
-----------
Returns the `Locale` information associated with the Locale data specified in [UTS 35's Layouts Elements](https://www.unicode.org/reports/tr35/tr35-general.html#Layout_Elements).
Examples
--------
### Obtaining text info
Return the supported text directions for a given `Locale`.
```
const ar = new Intl.Locale("ar");
console.log(ar.textInfo); // { direction: "rtl" }
console.log(ar.textInfo.direction); // "rtl"
```
```
const es = new Intl.Locale("es");
console.log(es.textInfo); // { direction: "ltr" }
console.log(es.textInfo.direction); // "ltr"
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.textInfo](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.textInfo) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `textInfo` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
javascript Intl.Locale.prototype.collations Intl.Locale.prototype.collations
================================
The `Intl.Locale.prototype.collations` accessor property returns a list of one or more [collation types](https://www.unicode.org/reports/tr35/tr35-collation.html#CLDR_collation) for the `Locale`.
Description
-----------
Collation is the process of ordering strings of characters. It is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. While the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. The `collations` property returns an array of all collation types commonly used for the `Locale`, sorted in alphabetical order, with the `standard` and `search` values always excluded. If the `Locale` already has a [`collation`](collation), then the returned array contains that single value.
Below is a list of the supported collation types, adapted from the [Unicode collation specification](https://github.com/unicode-org/cldr/blob/2dd06669d833823e26872f249aa304bc9d9d2a90/common/bcp47/collation.xml).
### Supported collation types
`big5han` Pinyin ordering for Latin, big5 charset ordering for CJK characters (for Chinese)
**Note:** The `big5han` collations type is deprecated, not available in Chrome or Edge, and on the way to be removed in Firefox ([bug 1630920](https://bugzilla.mozilla.org/show_bug.cgi?id=1630920)).
`compat` A previous version of the ordering, for compatibility (for Arabic)
`dict` Dictionary style ordering (for Sinhala)
`direct` Binary code point order
**Warning:** The `direct` collation type has been deprecated. Do not use.
`ducet` The default Unicode collation element table order
**Warning:** The `ducet` collation type is not available to the Web. Use the `und` locale without a collation type specifier instead. `und` is the collation that is the closest to `ducet`.
`emoji` Recommended ordering for emoji characters (for the `und` locale)
`eor` European ordering rules (for the `und` locale)
`gb2312` Pinyin ordering for Latin, gb2312han charset ordering for CJK characters (for Chinese)
**Note:** The `gb2312` collation type is deprecated, not available in Chrome or Edge, and on the way to be removed in Firefox ([bug 1630920](https://bugzilla.mozilla.org/show_bug.cgi?id=1630920)).
`phonebk` Phonebook style ordering (for German)
`phonetic` Phonetic ordering (sorting based on pronunciation; for Lingala)
`pinyin` Pinyin ordering for Latin and for CJK characters (for Chinese)
`reformed` Reformed ordering (for Swedish)
**Note:** This is the default ordering for Swedish whose collation naming is unusual as of May 2022. Since this is the default, request `sv` instead of requesting `sv-u-co-reformed`.
`search` Special collation type for string search
**Warning:** Do not use. In [`Intl.Collator`](../collator), this collation is activated via the `search` value for the `usage` option. Furthermore, there is currently no API for actually using the collator for search.
`searchjl` Special collation type for Korean initial consonant search
`standard` Default ordering for each language, except Chinese and, as of May 2022, Swedish
**Warning:** Do not use explicitly. In general, it's unnecessary to specify this explicitly and specifying this for Swedish is problematic in case the naming of the Swedish collations is changed to be consistent with other languages in the future.
`stroke` Pinyin ordering for Latin, stroke order for CJK characters (for Chinese)
`trad` Traditional style ordering (such as in Spanish)
`unihan` Radical-stroke ordering for Han characters (for Chinese, Japanese, and Korean). Pinyin ordering for Latin in the case of Chinese.
**Note:** The `unihan` collation type is not available in Chrome or Edge.
`zhuyin` Pinyin ordering for Latin, zhuyin order for Bopomofo and CJK characters (for Chinese)
Examples
--------
### Obtaining supported collation types
If the `Locale` object doesn't have a `collation` already, the `collations` property lists all commonly-used collation types for the given `Locale`. For examples of explicitly setting a `collation`, see [`collation` examples](collation#examples).
```
const locale = new Intl.Locale("zh");
console.log(locale.collations); // ["pinyin", "stroke", "zhuyin", "emoji", "eor"]
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.collations](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.collations) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `collations` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.collation`](collation)
javascript Intl.Locale.prototype.collation Intl.Locale.prototype.collation
===============================
The `Intl.Locale.prototype.collation` accessor property returns the [collation type](https://www.unicode.org/reports/tr35/tr35-collation.html#CLDR_Collation) for the `Locale`, which is used to order strings according to the locale's rules.
Description
-----------
Collation is the process of ordering strings of characters. It is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. While the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. The `collation` property's value is set at construction time, either through the `co` key of the locale identifier or through the `collation` option of the [`Intl.Locale()`](locale) constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported collation types, see [`Intl.Locale.prototype.collations`](collations#supported_collation_types).
The set accessor of `collation` is `undefined`. You cannot change this property directly.
Examples
--------
Like other locale subtags, the collation type can be added to the [`Intl.Locale`](../locale) object via the locale string, or a configuration object argument to the constructor.
### Adding a collation type via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), collation types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the collation type can be added to the initial locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. To add the collation type, first add the `-u` extension to the string. Next, add the `-co` extension to indicate that you are adding a collation type. Finally, add the collation type to the string.
```
const locale = new Intl.Locale("zh-Hant-u-co-zhuyin");
console.log(locale.collation); // "zhuyin"
```
### Adding a collation type via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can contain any of several extension types, including collation types. Set the `collation` property of the configuration object to your desired collation type, and then pass it into the constructor.
```
const locale = new Intl.Locale("zh-Hant", { collation: "zhuyin" });
console.log(locale.collation); // "zhuyin"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.collation](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.collation) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `collation` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.collations`](collations)
javascript Intl.Locale.prototype.hourCycle Intl.Locale.prototype.hourCycle
===============================
The `Intl.Locale.prototype.hourCycle` accessor property returns the hour cycle type for the locale.
Description
-----------
There are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. The `hourCycle` property's value is set at construction time, either through the `hc` key of the locale identifier or through the `hourCycle` option of the [`Intl.Locale()`](locale) constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported hour cycle types, see [`Intl.Locale.prototype.hourCycles`](hourcycles#supported_hour_cycle_types).
The set accessor of `hourCycle` is `undefined`. You cannot change this property directly.
Examples
--------
Like other locale subtags, the hour cycle type can be added to the [`Intl.Locale`](../locale) object via the locale string, or a configuration object argument to the constructor.
### Adding an hour cycle via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), hour cycle types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the hour cycle type can be added to the initial locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. To add the hour cycle type, first add the `-u` extension key to the string. Next, add the `-hc` extension to indicate that you are adding an hour cycle. Finally, add the hour cycle type to the string.
```
const locale = new Intl.Locale("fr-FR-u-hc-h23");
console.log(locale.hourCycle); // "h23"
```
### Adding an hour cycle via the configuration object argument
The [`Intl.Locale()`](locale) constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types. Set the `hourCycle` property of the configuration object to your desired hour cycle type, and then pass it into the constructor.
```
const locale = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(locale.hourCycle); // "h12"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.hourCycle](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.hourCycle) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hourCycle` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.hourCycles`](hourcycles)
* [Unicode Hour Cycle extension key spec](https://www.unicode.org/reports/tr35/#UnicodeHourCycleIdentifier)
| programming_docs |
javascript Intl.Locale.prototype.toString() Intl.Locale.prototype.toString()
================================
The `Intl.Locale.prototype.toString()` method returns the Locale's full [locale identifier string](https://www.unicode.org/reports/tr35/#Unicode_locale_identifier).
Try it
------
Syntax
------
```
toString()
```
### Return value
The *locale*'s Unicode locale identifier string.
Description
-----------
The `Locale` object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the `Locale` object was introduced to JavaScript. Calling the `toString` method on a Locale object will return the identifier string for that particular Locale. The `toString` method allows `Locale` instances to be provided as an argument to existing `Intl` constructors, serialized in JSON, or any other context where an exact string representation is useful.
Examples
--------
### Using toString
```
const myLocale = new Intl.Locale("fr-Latn-FR", {
hourCycle: "h24",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr-Latn-FR"
console.log(myLocale.toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.toString](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.toString) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toString` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`baseName`](basename)
javascript Intl.Locale.prototype.script Intl.Locale.prototype.script
============================
The `Intl.Locale.prototype.script` property is an accessor property which returns the script used for writing the particular language used in the locale.
Description
-----------
A script, sometimes called writing system, is one of the core attributes of a locale. It indicates the set of symbols, or glyphs, that are used to write a particular language. For instance, the script associated with English is Latin, whereas the script typically associated with Korean is Hangul. In many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. There are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete Unicode language identifier.
Examples
--------
### Setting the script in the locale identifier string argument
The script is the second part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the [`Intl.Locale()`](locale) constructor. Note that the script is not a required part of a locale identifier.
```
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.script); // Prints "Latn"
```
### Setting the script via the configuration object
The [`Intl.Locale()`](locale) constructor takes a configuration object, which can be used to set the script subtag and property.
```
const locale = new Intl.Locale("fr-FR", { script: "Latn" });
console.log(locale.script); // Prints "Latn"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.script](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.script) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `script` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [Unicode's script subtag specification](https://www.unicode.org/reports/tr35/#unicode_script_subtag_validity)
javascript Intl.Locale.prototype.language Intl.Locale.prototype.language
==============================
The `Intl.Locale.prototype.language` property is an accessor property that returns the language associated with the locale.
Description
-----------
Language is one of the core features of a locale. The Unicode specification treats the language identifier of a locale as the language and the region together (to make a distinction between dialects and variations, e.g. British English vs. American English). The `language` property of a [`Locale`](../locale) returns strictly the locale's language subtag.
Examples
--------
### Setting the language in the locale identifier string argument
In order to be a valid Unicode locale identifier, a string must start with the language subtag. The main argument to the [`Intl.Locale()`](locale) constructor must be a valid Unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag.
```
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.language); // Prints "en"
```
### Overriding language via the configuration object
While the language subtag must be specified, the [`Intl.Locale()`](locale) constructor takes a configuration object, which can override the language subtag.
```
const locale = new Intl.Locale("en-Latn-US", { language: "es" });
console.log(locale.language); // Prints "es"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.language](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.language) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `language` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [Unicode language subtag specification](https://www.unicode.org/reports/tr35/#unicode_language_subtag_validity)
javascript Intl.Locale.prototype.hourCycles Intl.Locale.prototype.hourCycles
================================
The `Intl.Locale.prototype.hourCycles` accessor property returns a list of one or more unique hour cycle identifiers for the `Locale`.
Description
-----------
There are two main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. The `hourCycles` property returns an array of all hour cycle types commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has an [`hourCycle`](hourcycle), then the returned array contains that single value.
Below is a list of supported hour cycle types.
### Supported hour cycle types
| Hour cycle type | Description |
| --- | --- |
| `h12` | Hour system using 1–12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am. |
| `h23` | Hour system using 0–23; corresponds to 'H' in patterns. The 24 hour clock, with midnight starting at 0:00. |
| `h11` | Hour system using 0–11; corresponds to 'K' in patterns. The 12 hour clock, with midnight starting at 0:00 am. |
| `h24` | Hour system using 1–24; corresponds to 'k' in pattern. The 24 hour clock, with midnight starting at 24:00. |
Examples
--------
### Obtaining supported hour cycles
If the `Locale` object doesn't have a `hourCycle` already, the `hourCycles` property lists all commonly-used collation types for the given `Locale`. For examples of explicitly setting a `hourCycle`, see [`hourCycle` examples](hourcycle#examples).
```
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.hourCycles); // ["h12"]
```
```
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.hourCycles); // ["h23"]
```
Specifications
--------------
| Specification |
| --- |
| [Intl Locale Info Proposal # sec-Intl.Locale.prototype.hourCycles](https://tc39.es/proposal-intl-locale-info/#sec-Intl.Locale.prototype.hourCycles) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `hourCycles` | 99 | 99 | No | No | 85 | 15.4 | 99 | 99 | No | 68 | 15.4 | 18.0 | 1.19 | No |
See also
--------
* [`Intl.Locale`](../locale)
* [`Intl.Locale.prototype.hourCycle`](hourcycle)
* [Unicode Hour Cycle extension key spec](https://www.unicode.org/reports/tr35/#UnicodeHourCycleIdentifier)
javascript Intl.Locale.prototype.maximize() Intl.Locale.prototype.maximize()
================================
The `Intl.Locale.prototype.maximize()` method gets the most likely values for the language, script, and region of the locale based on existing values.
Try it
------
Syntax
------
```
maximize()
```
### Return value
A [`Locale`](../locale) instance whose `baseName` property returns the result of the [Add Likely Subtags](https://www.unicode.org/reports/tr35/#Likely_Subtags) algorithm executed against *[`locale.baseName`](basename)*.
Description
-----------
Sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete language ID. The Add Likely Subtags algorithm gives us this functionality. For instance, given the language ID "en", the algorithm would return "en-Latn-US", since English can only be written in the Latin script, and is most likely to be used in the United States, as it is the largest English-speaking country in the world. This functionality is provided to JavaScript programmers via the `maximize()` method. `maximize()` only affects the main subtags that comprise the [language identifier](https://www.unicode.org/reports/tr35/#Language_Locale_Field_Definitions): language, script, and region subtags. Other subtags after the "-u" in the locale identifier are called extension subtags and are not affected by the `maximize()` method. Examples of these subtags include [`hourCycle`](hourcycle), [`calendar`](calendar), and [`numeric`](numeric).
Examples
--------
### Using maximize
```
const myLocale = new Intl.Locale("fr", {
hourCycle: "h24",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr"
console.log(myLocale.toString()); // Prints "fr-u-ca-gregory-hc-h24"
const myLocMaximized = myLocale.maximize();
// Prints "fr-Latn-FR". The "Latn" and "FR" tags are added,
// since French is only written in the Latin script and is most likely to be spoken in France.
console.log(myLocMaximized.baseName);
// Prints "fr-Latn-FR-u-ca-gregory-hc-h24".
// Note that the extension tags (after "-u") remain unchanged.
console.log(myLocMaximized.toString());
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.Locale.prototype.maximize](https://tc39.es/ecma402/#sec-Intl.Locale.prototype.maximize) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `maximize` | 74 | 79 | 75 | No | 62 | 14 | 74 | 74 | 79 | 53 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.Locale`](../locale)
* [`baseName`](basename)
* [Unicode's Likely Subtags spec](https://www.unicode.org/reports/tr35/#Likely_Subtags)
javascript Intl.DateTimeFormat.prototype.format() Intl.DateTimeFormat.prototype.format()
======================================
The `Intl.DateTimeFormat.prototype.format()` method formats a date according to the locale and formatting options of this [`Intl.DateTimeFormat`](../datetimeformat) object.
Try it
------
Syntax
------
```
format(date)
```
### Parameters
`date` The date to format.
Description
-----------
The `format` getter formats a date into a string according to the locale and formatting options of this [`Intl.DateTimeFormat`](../datetimeformat) object.
Examples
--------
### Using format
Use the `format` getter function for formatting a single date, here for Serbia:
```
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."
```
### Using format with map
Use the `format` getter function for formatting all dates in an array. Note that the function is bound to the [`Intl.DateTimeFormat`](../datetimeformat) from which it was obtained, so it can be passed directly to [`Array.prototype.map()`](../../array/map).
```
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"
```
### Avoid comparing formatted date values to static values
Most of the time, the formatting returned by `format()` is consistent. However, this might change in the future and isn't guaranteed for all the languages — output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text.
For this reason you cannot expect to be able to compare the results of `format()` to a static value:
```
let d = new Date("2019-01-01T00:00:00.000000Z");
let formattedDate = Intl.DateTimeFormat(undefined, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).format(d);
"1.1.2019, 01:00:00" === formattedDate;
// true in Firefox and others
// false in IE and Edge
```
**Note:** See also this [StackOverflow thread](https://stackoverflow.com/questions/25574963/ies-tolocalestring-has-strange-characters-in-results) for more details and examples.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.format](https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.format) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `format` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
* [`Date.prototype.toLocaleString()`](../../date/tolocalestring)
* [`Date.prototype.toLocaleDateString()`](../../date/tolocaledatestring)
* [`Date.prototype.toLocaleTimeString()`](../../date/tolocaletimestring)
javascript Intl.DateTimeFormat.prototype.formatRangeToParts() Intl.DateTimeFormat.prototype.formatRangeToParts()
==================================================
The `Intl.DateTimeFormat.prototype.formatRangeToParts()` method returns an array of locale-specific tokens representing each part of the formatted date range produced by [`Intl.DateTimeFormat`](../datetimeformat) formatters.
Try it
------
Syntax
------
```
formatRangeToParts(startDate, endDate)
```
Examples
--------
### Basic formatRangeToParts usage
This method receives two [`Date`](../../date)s and returns an [`Array`](../../array) of objects containing the *locale-specific* tokens representing each part of the formatted date range.
**Note:** The return values shown in your locale may differ from those listed below.
```
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT
const fmt = new Intl.DateTimeFormat("en", {
hour: 'numeric',
minute: 'numeric',
});
console.log(fmt.formatRange(date1, date2)); // '10:00 – 11:00 AM'
fmt.formatRangeToParts(date1, date2);
// [
// { type: 'hour', value: '10', source: "startRange" },
// { type: 'literal', value: ':', source: "startRange" },
// { type: 'minute', value: '00', source: "startRange" },
// { type: 'literal', value: ' – ', source: "shared" },
// { type: 'hour', value: '11', source: "endRange" },
// { type: 'literal', value: ':', source: "endRange" },
// { type: 'minute', value: '00', source: "endRange" },
// { type: 'literal', value: ' ', source: "shared" },
// { type: 'dayPeriod', value: 'AM', source: "shared" }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.DateTimeFormat.prototype.formatRangeToParts](https://tc39.es/ecma402/#sec-Intl.DateTimeFormat.prototype.formatRangeToParts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatRangeToParts` | 76 | 79 | 91 | No | 63 | 14.1 | 76 | 76 | 91 | 54 | 14.5 | 12.0 | 1.8 | 12.9.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
See also
--------
* [`Intl.DateTimeFormat.prototype.formatRange()`](formatrange)
* [`Intl.DateTimeFormat`](../datetimeformat)
javascript Intl.DateTimeFormat.prototype.resolvedOptions() Intl.DateTimeFormat.prototype.resolvedOptions()
===============================================
The `Intl.DateTimeFormat.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this [`Intl.DateTimeFormat`](../datetimeformat) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Return value
A new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given [`Intl.DateTimeFormat`](../datetimeformat) object.
Description
-----------
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`calendar` E.g. "gregory"
`numberingSystem` The values requested using the Unicode extension keys `"ca"` and `"nu"` or filled in as default values.
`timeZone` The value provided for this property in the `options` argument; [`undefined`](../../undefined) (representing the runtime's default time zone) if none was provided. Warning: Applications should not rely on [`undefined`](../../undefined) being returned, as future versions may return a [`String`](../../string) value identifying the runtime's default time zone instead.
`hour12` The value provided for this property in the `options` argument or filled in as a default.
`weekday`, `era`, `year`, `month`, `day`, `hour`, `minute`, `second`, `timeZoneName`
The values resulting from format matching between the corresponding properties in the `options` argument and the available combinations and representations for date-time formatting in the selected locale. Some of these properties may not be present, indicating that the corresponding components will not be represented in formatted output.
Examples
--------
### Using the resolvedOptions method
```
const germanFakeRegion = new Intl.DateTimeFormat('de-XX', { timeZone: 'UTC' });
const usedOptions = germanFakeRegion.resolvedOptions();
usedOptions.locale; // "de"
usedOptions.calendar; // "gregory"
usedOptions.numberingSystem; // "latn"
usedOptions.timeZone; // "UTC"
usedOptions.month; // "numeric"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
| `computed_timezone` | 35 | 14 | 53 | No | 30 | 10 | 37 | 35 | 56 | 22 | 10 | 3.0 | 1.8 | 8.10.0 |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
| programming_docs |
javascript Intl.DateTimeFormat.supportedLocalesOf() Intl.DateTimeFormat.supportedLocalesOf()
========================================
The `Intl.DateTimeFormat.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
Intl.DateTimeFormat.supportedLocalesOf(locales)
Intl.DateTimeFormat.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.DateTimeFormat.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.datetimeformat.supportedlocalesof](https://tc39.es/ecma402/#sec-intl.datetimeformat.supportedlocalesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
javascript Intl.DateTimeFormat.prototype.formatToParts() Intl.DateTimeFormat.prototype.formatToParts()
=============================================
The `Intl.DateTimeFormat.prototype.formatToParts()` method allows locale-aware formatting of strings produced by [`Intl.DateTimeFormat`](../datetimeformat) formatters.
Try it
------
Syntax
------
```
formatToParts(date)
```
### Parameters
`date` Optional
The date to format.
### Return value
An [`Array`](../../array) of objects containing the formatted date in parts.
Description
-----------
The `formatToParts()` method is useful for custom formatting of date strings. It returns an [`Array`](../../array) of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the `formatToParts()` method returns, looks like this:
```
[
{ type: 'day', value: '17' },
{ type: 'weekday', value: 'Monday' }
]
```
Possible types are the following:
day The string used for the day, for example `"17"`.
dayPeriod The string used for the day period, for example, `"AM"`, `"PM"`, `"in the morning"`, or `"noon"`
era The string used for the era, for example `"BC"` or `"AD"`.
fractionalSecond The string used for the fractional seconds, for example `"0"` or `"00"` or `"000"`.
hour The string used for the hour, for example `"3"` or `"03"`.
literal The string used for separating date and time values, for example `"/"`, `","`, `"o'clock"`, `"de"`, etc.
minute The string used for the minute, for example `"00"`.
month The string used for the month, for example `"12"`.
relatedYear The string used for the related 4-digit Gregorian year, in the event that the calendar's representation would be a yearName instead of a year, for example `"2019"`.
second The string used for the second, for example `"07"` or `"42"`.
timeZone The string used for the name of the time zone, for example `"UTC"`. Default is the timezone of the current environment.
weekday The string used for the weekday, for example `"M"`, `"Monday"`, or `"Montag"`.
year The string used for the year, for example `"2012"` or `"96"`.
yearName The string used for the yearName in relevant contexts, for example `"geng-zi"`
Examples
--------
`DateTimeFormat` outputs localized, opaque strings that cannot be manipulated directly:
```
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
const formatter = new Intl.DateTimeFormat('en-us', {
weekday: 'long',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3,
hour12: true,
timeZone: 'UTC'
});
formatter.format(date);
// "Monday, 12/17/2012, 3:00:42.000 AM"
```
However, in many User Interfaces there is a desire to customize the formatting of this string. The `formatToParts` method enables locale-aware formatting of strings produced by `DateTimeFormat` formatters by providing you the string in parts:
```
formatter.formatToParts(date);
// return value:
[
{ type: 'weekday', value: 'Monday' },
{ type: 'literal', value: ', ' },
{ type: 'month', value: '12' },
{ type: 'literal', value: '/' },
{ type: 'day', value: '17' },
{ type: 'literal', value: '/' },
{ type: 'year', value: '2012' },
{ type: 'literal', value: ', ' },
{ type: 'hour', value: '3' },
{ type: 'literal', value: ':' },
{ type: 'minute', value: '00' },
{ type: 'literal', value: ':' },
{ type: 'second', value: '42' },
{ type: 'fractionalSecond', value: '000' },
{ type: 'literal', value: ' ' },
{ type: 'dayPeriod', value: 'AM' }
]
```
Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`](../../array/map), [arrow functions](../../../functions/arrow_functions), a [switch statement](../../../statements/switch), [template literals](../../../template_literals), and [`Array.prototype.join()`](../../array/join).
```
const dateString = formatter.formatToParts(date).map(({type, value}) => {
switch (type) {
case 'dayPeriod': return `<em>${value}</em>`;
default: return value;
}
}).join('');
```
This will emphasize the day period when using the `formatToParts()` method.
```
console.log(formatter.format(date));
// "Monday, 12/17/2012, 3:00:42.000 AM"
console.log(dateString);
// "Monday, 12/17/2012, 3:00:42.000 <em>AM</em>"
```
### Named Years and Mixed calendars
In some cases, calendars use named years. Chinese and Tibetan calendars, for example, use a 60-year [sexagenary cycle](https://en.wikipedia.org/wiki/Sexagenary_cycle) of named years. These years are disambiguated by relationship to corresponding years on the Gregorian calendar. When this is the case, the result of `formatToParts()` will contain an entry for `relatedYear` when a year would normally be present, containing the 4-digit Gregorian year, instead of an entry for `year`. Setting an entry in the bag for `year` (with any value) will yield both the and the `yearName` Gregorian `relatedYear`:
```
const opts = { year: "numeric", month: "numeric", day: "numeric" };
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts);
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));
// return value
[
{ type: 'relatedYear', value: '2012' },
{ type: 'literal', value: '年' },
{ type: 'month', value: '十一月' },
{ type: 'day', value: '4' }
]
```
If the `year` option is not set in the bag (to any value), the result will include only the `relatedYear`:
```
const df = new Intl.DateTimeFormat("zh-u-ca-chinese");
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));
// return value
[
{ type: 'relatedYear', value: '2012' },
{ type: 'literal', value: '年' },
{ type: 'month', value: '十一月' },
{ type: 'day', value: '4' }
]
```
In cases where the `year` would be output, `.format()` may commonly present these side-by-side:
```
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", {year: "numeric"});
df.format(Date.UTC(2012, 11, 17, 3, 0, 42)); // 2012壬辰年
```
This also makes it possible to mix locale and calendar in both `format`:
```
const df = new Intl.DateTimeFormat("en-u-ca-chinese", { year: "numeric" });
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
df.format(date); // 2012(ren-chen)
```
And `formatToParts`:
```
const opts = { month: "numeric", day: "numeric", year: "numeric" };
const df = new Intl.DateTimeFormat("en-u-ca-chinese", opts);
const date = Date.UTC(2012, 11, 17, 3);
df.formatToParts(date);
// [
// { type: 'month', value: '11' },
// { type: 'literal', value: '/' },
// { type: 'day', value: '4' },
// { type: 'literal', value: '/' },
// { type: 'relatedYear', value: '2012' }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.DateTimeFormat.prototype.formatToParts](https://tc39.es/ecma402/#sec-Intl.DateTimeFormat.prototype.formatToParts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatToParts` | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 18 | 51 | No | 44
Before version 58, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 58 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 11 | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 57
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 56 | 43
Before version 50, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 50 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 11 | 7.0
Before version 71, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 71 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351). | 1.8 | 8.0.0
["Before version 12.0.0, `formatToParts()` returned an object with an incorrectly cased type key of `dayperiod`. Version 12.0.0 and later use the specification defined `dayPeriod`. See [Chromium bug 865351](https://crbug.com/865351).", "Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details."] |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
* [`Intl.DateTimeFormat.prototype.format()`](format)
* [`Date.prototype.toLocaleString()`](../../date/tolocalestring)
* [`Date.prototype.toLocaleDateString()`](../../date/tolocaledatestring)
* [`Date.prototype.toLocaleTimeString()`](../../date/tolocaletimestring)
* [A polyfill of `Intl.DateTimeFormat.prototype.formatToParts` in the proposal repository](https://github.com/tc39/proposal-intl-formatToParts)
javascript Intl.DateTimeFormat.prototype.formatRange() Intl.DateTimeFormat.prototype.formatRange()
===========================================
The `Intl.DateTimeFormat.prototype.formatRange()` formats a date range in the most concise way based on the `locale` and `options` provided when instantiating [`Intl.DateTimeFormat`](../datetimeformat) object.
Try it
------
Syntax
------
```
formatRange(startDate, endDate)
```
Examples
--------
### Basic formatRange usage
This method receives two [`Date`](../../date)s and formats the date range in the most concise way based on the `locale` and `options` provided when instantiating [`Intl.DateTimeFormat`](../datetimeformat).
```
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT
const date3 = new Date(Date.UTC(1906, 0, 20, 10, 0, 0)); // Sat, 20 Jan 1906 10:00:00 GMT
const fmt1 = new Intl.DateTimeFormat("en", {
year: '2-digit',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
});
console.log(fmt1.format(date1)); // '1/10/06, 10:00 AM'
console.log(fmt1.formatRange(date1, date2)); // '1/10/06, 10:00 – 11:00 AM'
console.log(fmt1.formatRange(date1, date3)); // '1/10/06, 10:00 AM – 1/20/07, 10:00 AM'
const fmt2 = new Intl.DateTimeFormat("en", {
year: 'numeric',
month: 'short',
day: 'numeric',
});
console.log(fmt2.format(date1)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date2)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date3)); // 'Jan 10 – 20, 1906'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.formatRange](https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.formatRange) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatRange` | 76 | 79 | 91 | No | 63 | 14.1 | 76 | 76 | 91 | 54 | 14.5 | 12.0 | 1.8 | 12.9.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `DateTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for more details. |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
javascript Intl.DateTimeFormat() constructor Intl.DateTimeFormat() constructor
=================================
The `Intl.DateTimeFormat()` constructor creates [`Intl.DateTimeFormat`](../datetimeformat) objects that enable language-sensitive date and time formatting.
Try it
------
Syntax
------
```
new Intl.DateTimeFormat()
new Intl.DateTimeFormat(locales)
new Intl.DateTimeFormat(locales, options)
Intl.DateTimeFormat()
Intl.DateTimeFormat(locales)
Intl.DateTimeFormat(locales, options)
```
**Note:** `Intl.DateTimeFormat()` can be called with or without [`new`](../../../operators/new). Both create a new `Intl.DateTimeFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.DateTimeFormat` instance; see [Return value](#return_value).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation). The following Unicode extension keys are allowed:
`nu` Numbering system. Possible values include: `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"deva"`, `"fullwide"`, `"gujr"`, `"guru"`, `"hanidec"`, `"khmr"`, `"knda"`, `"laoo"`, `"latn"`, `"limb"`, `"mlym"`, `"mong"`, `"mymr"`, `"orya"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`.
`ca` Calendar. Possible values include: `"buddhist"`, `"chinese"`, `"coptic"`, `"dangi"`, `"ethioaa"`, `"ethiopic"`, `"gregory"`, `"hebrew"`, `"indian"`, `"islamic"`, `"islamic-umalqura"`, `"islamic-tbla"`, `"islamic-civil"`, `"islamic-rgsa"`, `"iso8601"`, `"japanese"`, `"persian"`, `"roc"`, `"islamicc"`.
**Warning:** The `islamicc` calendar key has been deprecated. Please use `islamic-civil`.
`hc` Hour cycle. Possible values include: `"h11"`, `"h12"`, `"h23"`, `"h24"`.
`options` Optional
An object with some or all of the following properties:
`dateStyle` The date formatting style to use when calling `format()`. Possible values include:
* `"full"`
* `"long"`
* `"medium"`
* `"short"`
**Note:** `dateStyle` can be used with `timeStyle`, but not with other options (e.g. `weekday`, `hour`, `month`, etc.).
`timeStyle` The time formatting style to use when calling `format()`. Possible values include:
* `"full"`
* `"long"`
* `"medium"`
* `"short"`
**Note:** `timeStyle` can be used with `dateStyle`, but not with other options (e.g. `weekday`, `hour`, `month`, etc.).
`calendar` Calendar. Possible values include: `"buddhist"`, `"chinese"`, `"coptic"`, `"dangi"`, `"ethioaa"`, `"ethiopic"`, `"gregory"`, `"hebrew"`, `"indian"`, `"islamic"`, `"islamic-umalqura"`, `"islamic-tbla"`, `"islamic-civil"`, `"islamic-rgsa"`, `"iso8601"`, `"japanese"`, `"persian"`, `"roc"`, `"islamicc"`.
**Warning:** The `islamicc` calendar key has been deprecated. Please use `islamic-civil`.
`dayPeriod` The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. Possible values include: `"narrow"`, `"short"`, `"long"`.
**Note:**
* This option only has an effect if a 12-hour clock is used.
* Many locales use the same string irrespective of the width specified.
`numberingSystem` Numbering System. Possible values include: `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"deva"`, `"fullwide"`, " `gujr`", `"guru"`, `"hanidec"`, `"khmr"`, " `knda`", `"laoo"`, `"latn"`, `"limb"`, `"mlym"`, `"mong"`, `"mymr"`, `"orya"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`.
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`timeZone` The time zone to use. The only value implementations must recognize is `"UTC"`; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the [IANA time zone database](https://www.iana.org/time-zones), such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.
`hour12` Whether to use 12-hour time (as opposed to 24-hour time). Possible values are `true` and `false`; the default is locale dependent. This option overrides the `hc` language tag and/or the `hourCycle` option in case both are present.
`hourCycle` The hour cycle to use. Possible values are `"h11"`, `"h12"`, `"h23"`, or `"h24"`. This option overrides the `hc` language tag, if both are present, and the `hour12` option takes precedence in case both options have been specified.
`formatMatcher` The format matching algorithm to use. Possible values are `"basic"` and `"best fit"`; the default is `"best fit"`. See the following paragraphs for information about the use of this property.
The following properties describe the date-time components to use in formatted output, and their desired representations. Implementations are required to support at least the following subsets:
* `weekday`, `year`, `month`, `day`, `hour`, `minute`, `second`
* `weekday`, `year`, `month`, `day`
* `year`, `month`, `day`
* `year`, `month`
* `month`, `day`
* `hour`, `minute`, `second`
* `hour`, `minute`
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the `formatMatcher` property: A [fully specified `"basic"` algorithm](https://402.ecma-international.org/1.0/#BasicFormatMatcher) and an implementation-dependent `"best fit"` algorithm.
`weekday` The representation of the weekday. Possible values are:
* `"long"` (e.g., `Thursday`)
* `"short"` (e.g., `Thu`)
* `"narrow"` (e.g., `T`). Two weekdays may have the same narrow style for some locales (e.g. `Tuesday`'s narrow style is also `T`).
`era` The representation of the era. Possible values are:
* `"long"` (e.g., `Anno Domini`)
* `"short"` (e.g., `AD`)
* `"narrow"` (e.g., `A`)
`year` The representation of the year. Possible values are:
* `"numeric"` (e.g., `2012`)
* `"2-digit"` (e.g., `12`)
`month` The representation of the month. Possible values are:
* `"numeric"` (e.g., `3`)
* `"2-digit"` (e.g., `03`)
* `"long"` (e.g., `March`)
* `"short"` (e.g., `Mar`)
* `"narrow"` (e.g., `M`). Two months may have the same narrow style for some locales (e.g. `May`'s narrow style is also `M`).
`day` The representation of the day. Possible values are:
* `"numeric"` (e.g., `1`)
* `"2-digit"` (e.g., `01`)
`hour` The representation of the hour. Possible values are `"numeric"`, `"2-digit"`.
`minute` The representation of the minute. Possible values are `"numeric"`, `"2-digit"`.
`second` The representation of the second. Possible values are `"numeric"`,`"2-digit"`.
`fractionalSecondDigits` The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are:
* `0` (Fractional part dropped.)
* `1` (Fractional part represented as 1 digit. For example, 736 is formatted as `7`.)
* `2` (Fractional part represented as 2 digits. For example, 736 is formatted as `73`.)
* `3` (Fractional part represented as 3 digits. For example, 736 is formatted as `736`.)
`timeZoneName` The localized representation of the time zone name. Possible values are:
* `"long"` Long localized form (e.g., `Pacific Standard Time`, `Nordamerikanische Westküsten-Normalzeit`)
* `"short"` Short localized form (e.g.: `PST`, `GMT-8`)
* `"shortOffset"` Short localized GMT format (e.g., `GMT-8`)
* `"longOffset"` Long localized GMT format (e.g., `GMT-0800`)
* `"shortGeneric"` Short generic non-location format (e.g.: `PT`, `Los Angeles Zeit`).
* `"longGeneric"` Long generic non-location format (e.g.: `Pacific Time`, `Nordamerikanische Westküstenzeit`)
**Note:** Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like "Pacific Time", but may fall back to a timezone like "Los Angeles Time".
The default value for each date-time component property is [`undefined`](../../undefined), but if all component properties are [`undefined`](../../undefined), then `year`, `month`, and `day` are assumed to be `"numeric"`.
### Return value
A new `Intl.DateTimeFormat` object.
**Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the [browser compatibility table](#browser_compatibility).
Normally, `Intl.DateTimeFormat()` can be called with or without [`new`](../../../operators/new), and a new `Intl.DateTimeFormat` instance is returned in both cases. However, if the [`this`](../../../operators/this) value is an object that is [`instanceof`](../../../operators/instanceof) `Intl.DateTimeFormat` (doesn't necessarily mean it's created via `new Intl.DateTimeFormat`; just that it has `Intl.DateTimeFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.DateTimeFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).
```
const formatter = Intl.DateTimeFormat.call(
{ \_\_proto\_\_: Intl.DateTimeFormat.prototype },
"en-US",
{ dateStyle: "full" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: DateTimeFormat [Intl.DateTimeFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```
Note that there's only one actual `Intl.DateTimeFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the [`format()`](format) and [`resolvedOptions()`](resolvedoptions) methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. [`formatRange()`](formatrange)) would fail: "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called `ChainDateTimeFormat`, does not happen when `Intl.DateTimeFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.DateTimeFormat`. If you call it directly as `Intl.DateTimeFormat()`, the `this` value is [`Intl`](../../intl), and a new `Intl.DateTimeFormat` instance is created normally.
Examples
--------
### Using DateTimeFormat
In basic use without specifying a locale, `DateTimeFormat` uses the default locale and default options.
```
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los\_Angeles (UTC-0800)
```
### Using timeStyle and dateStyle
```
const shortTime = new Intl.DateTimeFormat("en", {
timeStyle: "short"
});
console.log(shortTime.format(Date.now())); // "13:31 AM"
const shortDate = new Intl.DateTimeFormat("en", {
dateStyle: "short"
});
console.log(shortDate.format(Date.now())); // "07/07/20"
const mediumTime = new Intl.DateTimeFormat("en", {
timeStyle: "medium",
dateStyle: "short"
});
console.log(mediumTime.format(Date.now())); // "07/07/20, 13:31:55 AM"
```
### Using dayPeriod
Use the `dayPeriod` option to output a string for the times of day ("in the morning", "at night", "noon", etc.). Note, that this only works when formatting for a 12 hour clock (`hourCycle: 'h12'`) and that for many locales the strings are the same irrespective of the value passed for the `dayPeriod`.
```
const date = Date.UTC(2012, 11, 17, 4, 0, 42);
console.log(new Intl.DateTimeFormat('en-GB', {
hour: 'numeric',
hourCycle: 'h12',
dayPeriod: 'short',
timeZone: 'UTC',
}).format(date));
// 4 at night" (same formatting in en-GB for all dayPeriod values)
console.log(new Intl.DateTimeFormat('fr', {
hour: 'numeric',
hourCycle: 'h12',
dayPeriod: 'narrow',
timeZone: 'UTC',
}).format(date));
// "4 mat." (same output in French for both narrow/short dayPeriod)
console.log(new Intl.DateTimeFormat('fr', {
hour: 'numeric',
hourCycle: 'h12',
dayPeriod: 'long',
timeZone: 'UTC',
}).format(date));
// "4 du matin"
```
### Using timeZoneName
Use the `timeZoneName` option to output a string for the timezone ("GMT", "Pacific Time", etc.).
```
const date = Date.UTC(2021, 11, 17, 3, 0, 42);
const timezoneNames = ['short', 'long', 'shortOffset', 'longOffset', 'shortGeneric', 'longGeneric']
for (const zoneName of timezoneNames) {
// Do something with currentValue
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/Los\_Angeles',
timeZoneName: zoneName,
});
console.log(`${zoneName}: ${formatter.format(date)}`);
}
// Logs:
// short: 12/16/2021, PST
// long: 12/16/2021, Pacific Standard Time
// shortOffset: 12/16/2021, GMT-8
// longOffset: 12/16/2021, GMT-08:00
// shortGeneric: 12/16/2021, PT
// longGeneric: 12/16/2021, Pacific Time
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-datetimeformat-constructor](https://tc39.es/ecma402/#sec-intl-datetimeformat-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `IntlLegacyConstructedSymbol` | 91
57
The fallback symbol property has description `IntlFallback`. | 91
79
The fallback symbol property has description `IntlFallback`. | 54 | No | 77
44
The fallback symbol property has description `IntlFallback`. | 14.1 | 91
57
The fallback symbol property has description `IntlFallback`. | 91
57
The fallback symbol property has description `IntlFallback`. | 56 | 64
43
The fallback symbol property has description `IntlFallback`. | 14.5 | 16.0
7.0
The fallback symbol property has description `IntlFallback`. | ? | 16.0.0
8.0.0
The fallback symbol property has description `IntlFallback`. |
| `DateTimeFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `DateTimeFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `locales_parameter` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `DateTimeFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `options_parameter` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0 |
See also
--------
* [`Intl.DateTimeFormat`](../datetimeformat)
* [`Intl.supportedValuesOf()`](../supportedvaluesof)
* [`Intl`](../../intl)
| programming_docs |
javascript Intl.ListFormat.prototype.format() Intl.ListFormat.prototype.format()
==================================
The `format()` method returns a string with a language-specific representation of the list.
Try it
------
Syntax
------
```
format()
format(list)
```
### Parameters
`list` An iterable object, such as an Array.
### Return value
A language-specific formatted string representing the elements of the list
Description
-----------
The `format()` method returns a string that has been formatted based on parameters provided in the `Intl.ListFormat` object. The `locales` and `options` parameters customize the behavior of `format()` and let applications specify the language conventions that should be used to format the list.
Examples
--------
### Using format
The following example shows how to create a List formatter using the English language.
```
const list = ['Motorcycle', 'Bus', 'Car'];
console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list));
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat('en-GB', { style: 'short', type: 'disjunction' }).format(list));
// Motorcycle, Bus or Car
console.log(new Intl.ListFormat('en-GB', { style: 'narrow', type: 'unit' }).format(list));
// Motorcycle Bus Car
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.format](https://tc39.es/ecma402/#sec-Intl.ListFormat.prototype.format) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `format` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
See also
--------
* [`Intl.ListFormat`](../listformat)
javascript Intl.ListFormat() constructor Intl.ListFormat() constructor
=============================
The `Intl.ListFormat()` constructor creates [`Intl.ListFormat`](../listformat) objects that enable language-sensitive list formatting.
Try it
------
Syntax
------
```
new Intl.ListFormat()
new Intl.ListFormat(locales)
new Intl.ListFormat(locales, options)
```
**Note:** `Intl.ListFormat()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object with some or all of the following properties:
`localeMatcher` The locale-matching algorithm to use. Possible values:
* `"best fit"` (default)
* `"lookup"`
For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`type` Indicates the type of grouping. Possible values:
* `"conjunction"`, for "and"-based grouping of the list items: "A, B, and C" (default)
* `"disjunction"`, for "or"-based grouping of the list items: "A, B, or C"
* `"unit"`, for grouping the list items as a unit (neither "and"-based nor "or"-based): "A, B, C"
`style` Indicates the grouping style (for example, whether list separators and conjunctions are included). Possible values:
* `"long"`: "A, B, and C" (default)
* `"short"`: "A, B, C"
* `"narrow"`: "A B C"
Examples
--------
### Using format
The following example shows how to create a List formatter using the English language.
```
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
list
)
);
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat("en-GB", { style: "long" }).format(list));
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat("en-US", { style: "long" }).format(list));
// Motorcycle, Bus, and Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "conjunction" }).format(
list
)
);
// Motorcycle, Bus and Car
console.log(
new Intl.ListFormat("en-US", { style: "short", type: "conjunction" }).format(
list
)
);
// Motorcycle, Bus, & Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "conjunction" }).format(
list
)
);
// Motorcycle, Bus, Car
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "disjunction" }).format(
list
)
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
list
)
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "disjunction" }).format(
list
)
);
// Motorcycle, Bus or Car
console.log(new Intl.ListFormat("en-US", { style: "narrow" }).format(list));
// Motorcycle, Bus, Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list)
);
// Motorcycle Bus Car
console.log(
new Intl.ListFormat("en-US", { style: "long" }).format([
"30 degrees",
"15 minutes",
"50 seconds",
])
);
// 30 degrees, 15 minutes, and 50 seconds
console.log(
new Intl.ListFormat("en-US", { style: "narrow" }).format([
"30 degrees",
"15 minutes",
"50 seconds",
])
);
// 30 degrees, 15 minutes, 50 seconds
console.log(
new Intl.ListFormat("en-US", { style: "narrow", type: "unit" }).format([
"30°",
"15′",
"50″",
])
);
// 30° 15′ 50″
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-listformat-constructor](https://tc39.es/ecma402/#sec-intl-listformat-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `ListFormat` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `ListFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.ListFormat`](../listformat)
* [`Intl`](../../intl)
javascript Intl.ListFormat.prototype.resolvedOptions() Intl.ListFormat.prototype.resolvedOptions()
===========================================
The `Intl.ListFormat.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current [`Intl.ListFormat`](../listformat) object.
Try it
------
Syntax
------
```
listFormat.resolvedOptions()
```
### Return value
An object with properties reflecting the locale and formatting options computed during the construction of the given [`Intl.ListFormat`](../listformat) object.
Description
-----------
The object returned by `resolvedOptions()` has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`style` The value provided for this property in the `options` argument of the constructor or the default value (`"long"`). Its value is either `"long"`, `"short"`, or `"narrow"`.
`type` The value provided for this property in the `options` argument of the constructor or the default value (`"conjunction"`). Its value is either `"conjunction"`, `"disjunction"`, or `"unit"`.
Examples
--------
### Using resolvedOptions
```
const deListFormatter = new Intl.ListFormat("de-DE", { style: "short" });
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "short"
console.log(usedOptions.type); // "conjunction" (the default value)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-Intl.ListFormat.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
See also
--------
* [`Intl.ListFormat`](../listformat)
* [`Intl.NumberFormat.prototype.resolvedOptions()`](../numberformat/resolvedoptions)
* [`Intl.Collator.prototype.resolvedOptions()`](../collator/resolvedoptions)
* [`Intl.DateTimeFormat.prototype.resolvedOptions()`](../datetimeformat/resolvedoptions)
* [`Intl.PluralRules.prototype.resolvedOptions()`](../pluralrules/resolvedoptions)
javascript Intl.ListFormat.supportedLocalesOf() Intl.ListFormat.supportedLocalesOf()
====================================
The `Intl.ListFormat.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in list formatting without having to fall back to the runtime's default locale.
Syntax
------
```
Intl.ListFormat.supportedLocalesOf(locales)
Intl.ListFormat.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in list formatting without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in list formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in list formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to list formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.ListFormat.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.ListFormat.supportedLocalesOf](https://tc39.es/ecma402/#sec-Intl.ListFormat.supportedLocalesOf) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.ListFormat`](../listformat)
javascript Intl.ListFormat.prototype.formatToParts() Intl.ListFormat.prototype.formatToParts()
=========================================
The `Intl.ListFormat.prototype.formatToParts()` method returns an [`Array`](../../array) of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
Try it
------
Syntax
------
```
formatToParts(list)
```
### Parameters
`list` An iterable object, such as an [`Array`](../../array), to be formatted according to a locale.
### Return value
An [`Array`](../../array) of components which contains the formatted parts from the list.
Description
-----------
Whereas [`Intl.ListFormat.prototype.format()`](format) returns a string being the formatted version of the list (according to the given locale and style options), `formatToParts()` returns an array of the different components of the formatted string.
Each element of the resulting array has two properties: `type` and `value`. The `type` property may be either `"element"`, which refers to a value from the list, or `"literal"` which refers to a linguistic construct. The `value` property gives the content, as a string, of the token.
The locale and style options used for formatting are given when constructing the [`Intl.ListFormat`](../listformat) instance.
Examples
--------
### Using formatToParts
```
const fruits = ['Apple', 'Orange', 'Pineapple'];
const myListFormat = new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' });
console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Pineapple" }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts](https://tc39.es/ecma402/#sec-Intl.ListFormat.prototype.formatToParts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatToParts` | 72 | 79 | 78 | No | 60 | 14.1
Only available on macOS Big Sur (11) and above. | 72 | 72 | 79 | 51 | 14.5 | 11.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `ListFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat) for more details. |
See also
--------
* [`Intl.ListFormat`](../listformat)
* [`Intl.ListFormat.prototype.format()`](format)
* [`Intl.RelativeTimeFormat.prototype.formatToParts()`](../relativetimeformat/formattoparts)
* [`Intl.NumberFormat.prototype.formatToParts()`](../numberformat/formattoparts)
* [`Intl.DateTimeFormat.prototype.formatToParts()`](../datetimeformat/formattoparts)
javascript Intl.PluralRules.prototype.select() Intl.PluralRules.prototype.select()
===================================
The `Intl.PluralRules.prototype.select()` method returns a string indicating which plural rule to use for locale-aware formatting.
Try it
------
Syntax
------
```
select(number)
```
### Parameters
`number` The number to get a plural rule for.
### Return value
A string representing the pluralization category of the `number`, can be one of `zero`, `one`, `two`, `few`, `many` or `other`.
Description
-----------
This function selects a pluralization category according to the locale and formatting options of a [`Intl.PluralRules`](../pluralrules) object.
Examples
--------
### Using select()
```
const pr = new Intl.PluralRules("ar-EG");
pr.select(0); // 'zero'
pr.select(1); // 'one'
pr.select(2); // 'two'
pr.select(6); // 'few'
pr.select(18); // 'many'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.pluralrules.prototype.select](https://tc39.es/ecma402/#sec-intl.pluralrules.prototype.select) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `select` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
See also
--------
* [`Intl.PluralRules`](../pluralrules)
javascript Intl.PluralRules.prototype.resolvedOptions() Intl.PluralRules.prototype.resolvedOptions()
============================================
The `Intl.PluralRules.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this [`Intl.PluralRules`](../pluralrules) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Return value
A new object with properties reflecting the locale and plural formatting options computed during the initialization of the given [`Intl.PluralRules`](../pluralrules) object.
Description
-----------
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`pluralCategories` An [`Array`](../../array) of plural categories used by the given locale, selected from the list `"zero"`, `"one"`, `"two"`, `"few"`, `"many"` and `"other"`.
`type` The type used (`cardinal` or `ordinal`).
Only one of the following two groups of properties is included:
`minimumIntegerDigits`, `minimumFractionDigits`, `maximumFractionDigits`
The values provided for these properties in the `options` argument or filled in as defaults. These properties are present only if neither `minimumSignificantDigits` nor `maximumSignificantDigits` was provided in the `options` argument.
`minimumSignificantDigits`, `maximumSignificantDigits`
The values provided for these properties in the `options` argument or filled in as defaults. These properties are present only if at least one of them was provided in the `options` argument.
Examples
--------
### Using the resolvedOptions() method
```
const de = new Intl.PluralRules('de-DE');
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de-DE"
usedOptions.maximumFractionDigits; // 3
usedOptions.minimumFractionDigits; // 0
usedOptions.minimumIntegerDigits; // 1
usedOptions.pluralCategories; // [ "one", "other" ]
usedOptions.type; // "cardinal"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.pluralrules.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.pluralrules.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
See also
--------
* [`Intl.PluralRules`](../pluralrules)
| programming_docs |
javascript Intl.PluralRules.supportedLocalesOf() Intl.PluralRules.supportedLocalesOf()
=====================================
The `Intl.PluralRules.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in plural formatting without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
Intl.PluralRules.supportedLocalesOf(locales)
Intl.PluralRules.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in plural formatting without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in plural formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in plural formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to plural formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.PluralRules.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.pluralrules.supportedlocalesof](https://tc39.es/ecma402/#sec-intl.pluralrules.supportedlocalesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `PluralRules()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) for more details. |
See also
--------
* [`Intl.PluralRules`](../pluralrules)
javascript Intl.PluralRules() constructor Intl.PluralRules() constructor
==============================
The `Intl.PluralRules()` constructor creates [`Intl.PluralRules`](../pluralrules) objects.
Syntax
------
```
new Intl.PluralRules()
new Intl.PluralRules(locales)
new Intl.PluralRules(locales, options)
```
**Note:** `Intl.PluralRules()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object with some or all of the following properties:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`type` The type to use. Possible values are:
* `"cardinal"` for cardinal numbers (referring to the quantity of things). This is the default value.
* `"ordinal"` for ordinal number (referring to the ordering or ranking of things, e.g. "1st", "2nd", "3rd" in English).
The following properties fall into two groups: `minimumIntegerDigits`, `minimumFractionDigits`, and `maximumFractionDigits` in one group, `minimumSignificantDigits` and `maximumSignificantDigits` in the other. If at least one property from the second group is defined, then the first group is ignored.
`minimumIntegerDigits` The minimum number of integer digits to use. Possible values are from 1 to 21; the default is 1.
`minimumFractionDigits` The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information).
`maximumFractionDigits` The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of `minimumFractionDigits` and 3; the default for currency formatting is the larger of `minimumFractionDigits` and the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information); the default for percent formatting is the larger of `minimumFractionDigits` and 0.
`minimumSignificantDigits` The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
`maximumSignificantDigits` The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.
Examples
--------
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. This is useful to distinguish between singular and plural forms, e.g. "dog" and "dogs".
```
const pr = new Intl.PluralRules();
pr.select(0); // 'other' if in US English locale
pr.select(1); // 'one' if in US English locale
pr.select(2); // 'other' if in US English locale
```
### Using options
The results can be customized using the `options` argument, which has one property called `type` which you can set to `ordinal`. This is useful to figure out the ordinal indicator, e.g. "1st", "2nd", "3rd", "4th", "42nd" and so forth.
```
const pr = new Intl.PluralRules('en-US', { type: 'ordinal' });
const suffixes = new Map([
['one', 'st'],
['two', 'nd'],
['few', 'rd'],
['other', 'th'],
]);
const formatOrdinals = (n) => {
const rule = pr.select(n);
const suffix = suffixes.get(rule);
return `${n}${suffix}`;
};
formatOrdinals(0); // '0th'
formatOrdinals(1); // '1st'
formatOrdinals(2); // '2nd'
formatOrdinals(3); // '3rd'
formatOrdinals(4); // '4th'
formatOrdinals(11); // '11th'
formatOrdinals(21); // '21st'
formatOrdinals(42); // '42nd'
formatOrdinals(103); // '103rd'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-pluralrules-constructor](https://tc39.es/ecma402/#sec-intl-pluralrules-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `PluralRules` | 63 | 18 | 58 | No | 50 | 13 | 63 | 63 | 58 | 46 | 13 | 8.0 | 1.8 | 13.0.0
10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `PluralRules` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.PluralRules`](../pluralrules)
* [`Intl`](../../intl)
javascript Intl.PluralRules.prototype.selectRange() Intl.PluralRules.prototype.selectRange()
========================================
The `Intl.PluralRules.prototype.selectRange()` method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.
Syntax
------
```
selectRange(startRange, endRange)
```
### Return value
A string representing the pluralization category of the `number`. This can be one of `zero`, `one`, `two`, `few`, `many` or `other`, that are relevant for the locale whose localization is specified in [LDML Language Plural Rules](https://unicode-org.github.io/cldr-staging/charts/37/supplemental/language_plural_rules.html#rules).
Description
-----------
This function selects a pluralization category according to the locale and formatting options of an [`Intl.PluralRules`](../pluralrules) object.
Examples
--------
### Using selectRange()
```
new Intl.PluralRules('sl').selectRange(102, 201); // 'few'
new Intl.PluralRules('pt').selectRange(102, 102); // 'other'
```
Specifications
--------------
| Specification |
| --- |
| [Intl.PluralRules # sec-intl.pluralrules.prototype.selectrange](https://tc39.es/proposal-intl-numberformat-v3/out/pluralrules/proposed.html#sec-intl.pluralrules.prototype.selectrange) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `selectRange` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
See also
--------
* [`Intl.PluralRules`](../pluralrules)
javascript Intl.NumberFormat.prototype.format() Intl.NumberFormat.prototype.format()
====================================
The `Intl.NumberFormat.prototype.format()` method formats a number according to the [locale and formatting options](numberformat#parameters) of this [`Intl.NumberFormat`](../numberformat) object.
Try it
------
Syntax
------
```
format(number)
```
### Parameters
`number` A [`Number`](../../number), [`BigInt`](../../bigint), or string, to format. Strings are parsed in the same way as in [number conversion](../../number#number_coercion), except that `format()` will use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number.
**Note:** Older versions of the specification parsed strings as a [`Number`](../../number). Check the compatibility table for your browser.
Description
-----------
The `format()` method formats a number into a string according to the locale and formatting options of this [`Intl.NumberFormat`](../numberformat) object.
[`Number`](../../number) values in JavaScript suffer from loss of precision if they are too big or too small, making the text representation inaccurate. If you are performing calculations with integers larger than [`Number.MAX_SAFE_INTEGER`](../../number/max_safe_integer) you should use a [`BigInt`](../../bigint) instead, which will format correctly:
```
new Intl.NumberFormat('en-US').format(1234567891234567891) // 1,234,567,891,234,568,000
new Intl.NumberFormat('en-US').format(1234567891234567891n) // 1,234,567,891,234,567,891
```
You can also pass through very large strings to be formatted as an arbitrary-precision decimal string (if you're performing calculations on the data you will still need to work with `BigInt`):
```
new Intl.NumberFormat('en-US').format("1234567891234567891") // 1,234,567,891,234,567,891
```
Examples
--------
### Using format
Use the `format` getter function for formatting a single currency value. The code below shows how to format the roubles currency for a Russian locale:
```
const options = { style: 'currency', currency: 'RUB' };
const numberFormat = new Intl.NumberFormat('ru-RU', options);
console.log(numberFormat.format(654321.987));
// "654 321,99 ₽"
```
### Using format with map
Use the `format` getter function for formatting all numbers in an array. Note that the function is bound to the [`Intl.NumberFormat`](../numberformat) from which it was obtained, so it can be passed directly to [`Array.prototype.map`](../../array/map). This is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs.
```
const a = [123456.789, 987654.321, 456789.123];
const numberFormat = new Intl.NumberFormat('es-ES');
const formatted = a.map((n) => numberFormat.format(n));
console.log(formatted.join('; '));
// "123.456,789; 987.654,321; 456.789,123"
```
### Using format with a string
Using a string we can specify very numbers that are larger than [`Number.MAX_SAFE_INTEGER`](../../number/max_safe_integer) without losing precision.
```
const numberFormat = new Intl.NumberFormat("en-US");
// Here the value is converted to a Number
console.log(numberFormat.format(987654321987654321))
// 987,654,321,987,654,300
// Here we use a string and don't lose precision
console.log(numberFormat.format("987654321987654321"));
// 987,654,321,987,654,321
```
We can also use the general "E" exponent syntax for decimal strings: `#.#E#`. The code below creates a [`BigInt`](../../bigint), coerces it to a string with the suffix `E-6`, and then formats it.
```
const numberFormat = new Intl.NumberFormat("en-US");
const bigNum = 1000000000000000110000n;
console.log(numberFormat.format(bigNum));
// "1,000,000,000,000,000,110,000"
// Format as a string using the `E` syntax:
console.log(numberFormat.format(`${bigNum}E-6`));
// "1,000,000,000,000,000.11"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.format](https://tc39.es/ecma402/#sec-intl.numberformat.prototype.format) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `format` | 24 | 12
Before Edge 18, numbers are rounded to 15 decimal digits. For example, `new Intl.NumberFormat('en-US').format(1000000000000005)` returns `"1,000,000,000,000,010"`. | 29 | 11
In Internet Explorer 11, numbers are rounded to 15 decimal digits. For example, `new Intl.NumberFormat('en-US').format(1000000000000005)` returns `"1,000,000,000,000,010"`. | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `number_parameter-string_decimal` | No | No | No | No | No | No | No | No | No | No | No | No | No | No |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
* [`Number.prototype.toLocaleString()`](../../number/tolocalestring)
javascript Intl.NumberFormat.prototype.formatRangeToParts() Intl.NumberFormat.prototype.formatRangeToParts()
================================================
The `Intl.Numberformat.prototype.formatRangeToParts()` method enables locale-aware formatting of strings produced by `NumberFormat` formatters.
It returns an [`Array`](../../array) of objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.
Syntax
------
```
formatRangeToParts(startRange, endRange)
```
### Parameters
`startRange` A [`Number`](../../number) or [`BigInt`](../../bigint).
`endRange` A [`Number`](../../number) or [`BigInt`](../../bigint).
### Return value
An [`Array`](../../array) of objects containing the formatted range of numbers in parts.
The structure of the returned looks like this:
```
[
{ type: "integer", value: "3", source: "startRange" },
{ type: "literal", value: "-", source: "shared" },
{ type: "integer", value: "5", source: "endRange" },
{ type: "literal", value: " ", source: "shared" },
{ type: "currency", value: "€", source: "shared" }
]
```
Possible values for the `type` property include:
`currency` The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.
`decimal` The decimal separator string (".").
`fraction` The fraction number.
`group` The group separator string (",").
`infinity` The [`Infinity`](../../infinity) string ("∞").
`integer` The integer number.
`literal` Any literal strings or whitespace in the formatted number.
`minusSign` The minus sign string ("-").
`nan` The [`NaN`](../../nan) string ("NaN").
`plusSign` The plus sign string ("+").
`percentSign` The percent sign string ("%").
`unit` The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.
Possible values for the `source` property include:
`startRange` The object is the start part of the range.
`endRange` The object is the end part of the range.
`shared` The object is a "shared" part of the range, such as a separator or currency.
### Exceptions
[`RangeError`](../../rangeerror) Thrown if `startRange` is less than `endRange`, or either value is `NaN`.
[`TypeError`](../../typeerror) Thrown if either `startRange` or `endRange` is undefined.
Examples
--------
### Comparing formatRange and formatRangeToParts
`NumberFormat` outputs localized, opaque strings that cannot be manipulated directly:
```
const startRange = 3500;
const endRange = 9500;
const formatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
});
console.log(formatter.formatRange(startRange, endRange));
// "3.500,00–9.500,00 €"
```
However, for many user interfaces there is a need to customize the formatting of this string. The `formatRangeToParts` method enables locale-aware formatting of strings produced by `NumberFormat` formatters by providing you the string in parts:
```
console.log(formatter.formatRangeToParts(startRange, endRange));
// return value:
[
{ type: "integer", value: "3", source: "startRange" },
{ type: "group", value: ".", source: "startRange" },
{ type: "integer", value: "500", source: "startRange" },
{ type: "decimal", value: ",", source: "startRange" },
{ type: "fraction", value: "00", source: "startRange" },
{ type: "literal", value: "–", source: "shared" },
{ type: "integer", value: "9", source: "endRange" },
{ type: "group", value: ".", source: "endRange" },
{ type: "integer", value: "500", source: "endRange" },
{ type: "decimal", value: ",", source: "endRange" },
{ type: "fraction", value: "00", source: "endRange" },
{ type: "literal", value: " ", source: "shared" },
{ type: "currency", value: "€", source: "shared" },
]
```
Specifications
--------------
| Specification |
| --- |
| [Intl.NumberFormat # sec-intl.numberformat.prototype.formatrangetoparts](https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-intl.numberformat.prototype.formatrangetoparts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatRangeToParts` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
* [`Intl.NumberFormat.prototype.format`](format)
* Formatting dates: [`Intl.DateTimeFormat.prototype.formatRangeToParts()`](../datetimeformat/formatrangetoparts)
| programming_docs |
javascript Intl.NumberFormat.prototype.resolvedOptions() Intl.NumberFormat.prototype.resolvedOptions()
=============================================
The `Intl.NumberFormat.prototype.resolvedOptions()` method returns a new object with properties reflecting the [locale and number formatting options](numberformat#parameters) computed during initialization of this [`Intl.NumberFormat`](../numberformat) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Return value
A new object with properties reflecting the [locale and number formatting options](numberformat#parameters) computed during the construction of the given [`Intl.NumberFormat`](../numberformat) object.
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`numberingSystem` The value provided for this properties in the `options` argument, if present, or the value requested using the Unicode extension key `"nu"` or filled in as a default.
`notation` The value provided for this property in the `options` argument, if present, or `"standard"` filled in as a default.
`compactDisplay` The value provided for this property in the `options` argument, or `"short"` filled in as a default. This property is only present if the `notation` is set to "compact".
`signDisplay` The value provided for this property in the `options` argument, or `"auto"` filled in as a default.
`useGrouping` The value provided for the [useGrouping](numberformat#usegrouping) property in the constructor `options` argument or the default value (`"auto"`).
`currency`, `currencyDisplay`
The values provided for these properties in the `options` argument or filled in as defaults. These properties are only present if `style` is `"currency"`.
Only one of the following two groups of properties is included:
`minimumIntegerDigits`, `minimumFractionDigits`, `maximumFractionDigits`
The values provided for these properties in the `options` argument or filled in as defaults. These properties are present only if neither `minimumSignificantDigits` nor `maximumSignificantDigits` was provided in the `options` argument.
`minimumSignificantDigits`, `maximumSignificantDigits`
The values provided for these properties in the `options` argument or filled in as defaults. These properties are present only if at least one of them was provided in the `options` argument.
Examples
--------
### Using the `resolvedOptions` method
```
const de = new Intl.NumberFormat('de-DE');
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de-DE"
usedOptions.numberingSystem; // "latn"
usedOptions.notation; // "standard"
usedOptions.signDisplay; // "auto"
usedOptions.style; // "decimal"
usedOptions.minimumIntegerDigits; // 1
usedOptions.minimumFractionDigits; // 0
usedOptions.maximumFractionDigits; // 3
usedOptions.useGrouping; // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.numberformat.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
| `result_useGrouping_property` | No | No | No | No | No | No | No | No | No | No | No | No | No | No |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
javascript Intl.NumberFormat.supportedLocalesOf() Intl.NumberFormat.supportedLocalesOf()
======================================
The `Intl.NumberFormat.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
Intl.NumberFormat.supportedLocalesOf(locales)
Intl.NumberFormat.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in number formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.NumberFormat.supportedLocalesOf(locales, options).join(', '));
// → "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.numberformat.supportedlocalesof](https://tc39.es/ecma402/#sec-intl.numberformat.supportedlocalesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
javascript Intl.NumberFormat.prototype.formatToParts() Intl.NumberFormat.prototype.formatToParts()
===========================================
The `Intl.NumberFormat.prototype.formatToParts()` method allows locale-aware formatting of strings produced by `NumberFormat` formatters.
Try it
------
Syntax
------
```
formatToParts()
formatToParts(number)
```
### Parameters
`number` Optional
A [`Number`](../../number) or [`BigInt`](../../bigint) to format.
### Return value
An [`Array`](../../array) of objects containing the formatted number in parts.
Description
-----------
The `formatToParts()` method is useful for custom formatting of number strings. It returns an [`Array`](../../array) of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the `formatToParts()` method returns, looks like this:
```
[
{ type: "integer", value: "3" },
{ type: "group", value: "." },
{ type: "integer", value: "500" }
]
```
Possible types are the following:
`compact` The exponent in `"long"` or `"short"` form, depending on how `compactDisplay` (which defaults to `short`) is specified when `notation` is set to `compact`.
`currency` The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.
`decimal` The decimal separator string (".").
`exponentInteger` The exponent integer value, when `notation` is set to `scientific` or `engineering`.
`exponentMinusSign` The exponent minus sign string ("-").
`exponentSeparator` The exponent separator, when `notation` is set to `scientific` or `engineering`.
`fraction` The fraction number.
`group` The group separator string (",").
`infinity` The [`Infinity`](../../infinity) string ("∞").
`integer` The integer number.
`literal` Any literal strings or whitespace in the formatted number.
`minusSign` The minus sign string ("-").
`nan` The [`NaN`](../../nan) string ("NaN").
`plusSign` The plus sign string ("+").
`percentSign` The percent sign string ("%").
`unit` The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.
`unknown` The string for `unknown` type results.
Examples
--------
### Comparing format and formatToParts
`NumberFormat` outputs localized, opaque strings that cannot be manipulated directly:
```
const number = 3500;
const formatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
});
formatter.format(number);
// "3.500,00 €"
```
However, in many User Interfaces there is a desire to customize the formatting of this string. The `formatToParts` method enables locale-aware formatting of strings produced by `NumberFormat` formatters by providing you the string in parts:
```
formatter.formatToParts(number);
// return value:
[
{ type: "integer", value: "3" },
{ type: "group", value: "." },
{ type: "integer", value: "500" },
{ type: "decimal", value: "," },
{ type: "fraction", value: "00" },
{ type: "literal", value: " " },
{ type: "currency", value: "€" }
]
```
Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`](../../array/map), [arrow functions](../../../functions/arrow_functions), a [switch statement](../../../statements/switch), [template literals](../../../template_literals), and [`Array.prototype.reduce()`](../../array/reduce).
```
const numberString = formatter.formatToParts(number).map(({type, value}) => {
switch (type) {
case 'currency': return `<strong>${value}</strong>`;
default : return value;
}
}).reduce((string, part) => string + part);
```
This will make the currency bold, when using the `formatToParts()` method.
```
console.log(numberString);
// "3.500,00 <strong>€</strong>"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.formattoparts](https://tc39.es/ecma402/#sec-intl.numberformat.prototype.formattoparts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatToParts` | 64 | 12 | 58 | No | 51 | 13 | 64 | 64 | 58 | 47 | 13 | 9.0 | 1.8 | 10.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `NumberFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for more details. |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
* [`Intl.NumberFormat.prototype.format`](format)
* Formatting dates: [`Intl.DateTimeFormat.prototype.formatToParts()`](../datetimeformat/formattoparts)
javascript Intl.NumberFormat.prototype.formatRange() Intl.NumberFormat.prototype.formatRange()
=========================================
The `Intl.NumberFormat.prototype.formatRange()` method formats a range of numbers according to the locale and formatting options of the [`Intl.NumberFormat`](../numberformat) object from which the method is called.
Syntax
------
```
formatRange(startRange, endRange)
```
### Parameters
`startRange` A [`Number`](../../number) or [`BigInt`](../../bigint).
`endRange` A [`Number`](../../number) or [`BigInt`](../../bigint).
### Exceptions
[`RangeError`](../../rangeerror) Thrown if `startRange` is less than `endRange`, or either value is `NaN`.
[`TypeError`](../../typeerror) Thrown if either `startRange` or `endRange` is undefined.
Description
-----------
The `formatRange` getter function formats a range of numbers into a string according to the locale and formatting options of this [`Intl.NumberFormat`](../numberformat) object from which it is called.
Examples
--------
### Using formatRange
Use the `formatRange` getter function for formatting a range of currency values:
```
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
console.log(nf.formatRange(3, 5)); // "$3 – $5"
// Note: the "approximately equals" symbol is added if
// startRange and endRange round to the same values.
console.log(nf.formatRange(2.9, 3.1)); // "~$3"
```
```
const nf = new Intl.NumberFormat("es-ES", {
style: "currency",
currency: "EUR",
maximumFractionDigits: 0,
});
console.log(nf.formatRange(3, 5)); // "3-5 €"
console.log(nf.formatRange(2.9, 3.1)); // "~3 €"
```
Specifications
--------------
| Specification |
| --- |
| [Intl.NumberFormat # sec-intl.numberformat.prototype.formatrange](https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-intl.numberformat.prototype.formatrange) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatRange` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
* [`Number.prototype.toLocaleString()`](../../number/tolocalestring)
javascript Intl.NumberFormat() constructor Intl.NumberFormat() constructor
===============================
The `Intl.NumberFormat()` constructor creates [`Intl.NumberFormat`](../numberformat) objects that enable language-sensitive number formatting.
Try it
------
Syntax
------
```
new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)
Intl.NumberFormat()
Intl.NumberFormat(locales)
Intl.NumberFormat(locales, options)
```
**Note:** `Intl.NumberFormat()` can be called with or without [`new`](../../../operators/new). Both create a new `Intl.NumberFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.NumberFormat` instance; see [Return value](#return_value).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation). The following Unicode extension key is allowed:
`nu` The numbering system to be used. Possible values include: `"adlm"`, `"ahom"`, `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"bhks"`, `"brah"`, `"cakm"`, `"cham"`, `"deva"`, `"diak"`, `"fullwide"`, `"gong"`, `"gonm"`, `"gujr"`, `"guru"`, `"hanidec"`, `"hmng"`, `"hmnp"`, `"java"`, `"kali"`, `"khmr"`, `"knda"`, `"lana"`, `"lanatham"`, `"laoo"`, `"latn"`, `"lepc"`, `"limb"`, `"mathbold"`, `"mathdbl"`, `"mathmono"`, `"mathsanb"`, `"mathsans"`, `"mlym"`, `"modi"`, `"mong"`, `"mroo"`, `"mtei"`, `"mymr"`, `"mymrshan"`, `"mymrtlng"`, `"newa"`, `"nkoo"`, `"olck"`, `"orya"`, `"osma"`, `"rohg"`, `"saur"`, `"segment"`, `"shrd"`, `"sind"`, `"sinh"`, `"sora"`, `"sund"`, `"takr"`, `"talu"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`, `"tirh"`, `"vaii"`, `"wara"`, `"wcho"` — see the [standard Unicode numeral systems list](../locale/numberingsystem).
`options` Optional
An object with some or all of the following properties:
`compactDisplay` Only used when `notation` is `"compact"`. Takes either `"short"` (default) or `"long"`.
`currency` The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as `"USD"` for the US dollar, `"EUR"` for the euro, or `"CNY"` for the Chinese RMB — see the [Current currency & funds code list](https://www.six-group.com/en/products-services/financial-information/data-standards.html#scrollTo=currency-codes). There is no default value; if the `style` is `"currency"`, the `currency` property must be provided.
`currencyDisplay` How to display the currency in currency formatting. The default is `"symbol"`.
* `"symbol"`: use a localized currency symbol such as €.
* `"narrowSymbol"`: use a narrow format symbol ("$100" rather than "US$100").
* `"code"`: use the ISO currency code.
* `"name"`: use a localized currency name such as `"dollar"`.
`currencySign` In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. You can enable this formatting by setting the `currencySign` option to `"accounting"`. The default value is `"standard"`.
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`notation` The formatting that should be displayed for the number. The default is `"standard"`.
* `"standard"`: plain number formatting.
* `"scientific"`: return the order-of-magnitude for formatted number.
* `"engineering"`: return the exponent of ten when divisible by three.
* `"compact"`: string representing exponent; defaults to using the "short" form.
`numberingSystem` Numbering System. Possible values include: `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"deva"`, `"fullwide"`, `"gujr"`, `"guru"`, `"hanidec"`, `"khmr"`, `"knda"`, `"laoo"`, `"latn"`, `"limb"`, `"mlym"`, `"mong"`, `"mymr"`, `"orya"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`.
`signDisplay` When to display the sign for the number. The default is `"auto"`.
* `"auto"`: sign display for negative numbers only, including negative zero.
* `"always"`: always display sign.
* `"exceptZero"`: sign display for positive and negative numbers, but not zero.
* `"negative"`: sign display for negative numbers only, excluding negative zero. Experimental
* `"never"`: never display sign.
`style` The formatting style to use. The default is `"decimal"`.
* `"decimal"` for plain number formatting.
* `"currency"` for currency formatting.
* `"percent"` for percent formatting.
* `"unit"` for unit formatting.
`unit` The unit to use in `unit` formatting, Possible values are core unit identifiers, defined in [UTS #35, Part 2, Section 6](https://unicode.org/reports/tr35/tr35-general.html#Unit_Elements). A [subset](https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier) of units from the [full list](https://github.com/unicode-org/cldr/blob/main/common/validity/unit.xml) was selected for use in ECMAScript. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if the `style` is `"unit"`, the `unit` property must be provided.
`unitDisplay` The unit formatting style to use in `unit` formatting. The default is `"short"`.
* `"long"` (e.g., `16 litres`).
* `"short"` (e.g., `16 l`).
* `"narrow"` (e.g., `16l`).
`useGrouping` Experimental
Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. The default is `auto`.
* `"always"`: display grouping separators even if the locale prefers otherwise.
* `"auto"`: display grouping separators based on the locale preference, which may also be dependent on the currency.
* `false`: do not display grouping separators.
* `"min2"`: display grouping separators when there are at least 2 digits in a group.
* `true`: alias for `always`.
`roundingMode` Experimental
Options for rounding modes. The default is `halfExpand`.
* `"ceil"`: round toward +∞. Positive values round up. Negative values round "more positive".
* `"floor"` round toward -∞. Positive values round down. Negative values round "more negative".
* `"expand"`: round away from 0. The *magnitude* of the value is always increased by rounding. Positive values round up. Negative values round "more negative".
* `"trunc"`: round toward 0. This *magnitude* of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".
* `"halfCeil"`: ties toward +∞. Values above the half-increment round like `ceil` (towards +∞), and below like `floor` (towards -∞). On the half-increment, values round like `ceil`.
* `"halfFloor"`: ties toward -∞. Values above the half-increment round like `ceil` (towards +∞), and below like `floor` (towards -∞). On the half-increment, values round like `floor`.
* `"halfExpand"`: ties away from 0. Values above the half-increment round like `expand` (away from zero), and below like `trunc` (towards 0). On the half-increment, values round like `expand`.
* `"halfTrunc"`: ties toward 0. Values above the half-increment round like `expand` (away from zero), and below like `trunc` (towards 0). On the half-increment, values round like `trunc`.
* `"halfEven"`: ties towards the nearest even integer. Values above the half-increment round like `expand` (away from zero), and below like `trunc` (towards 0). On the half-increment values round towards the nearest even digit.
These options reflect the [ICU user guide](https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes.html), where "expand" and "trunc" map to ICU "UP" and "DOWN", respectively. The [rounding modes](#rounding_modes) example below demonstrates how each mode works.
`roundingPriority` Experimental
Specify how rounding conflicts will be resolved if both "FractionDigits" ([`minimumFractionDigits`](#minimumfractiondigits)/[`maximumFractionDigits`](#maximumfractiondigits)) and "SignificantDigits" ([`minimumSignificantDigits`](#minimumsignificantdigits)/[`maximumSignificantDigits`](#maximumsignificantdigits)) are specified:
* `"auto"`: the result from the significant digits property is used (default).
* `"morePrecision"`: the result from the property that results in more precision is used.
* `"lessPrecision"`: the result from the property that results in less precision is used.
Note that for values other than `auto` the result with more precision is calculated from the [`maximumSignificantDigits`](#minimumsignificantdigits) and [`maximumFractionDigits`](#maximumfractiondigits) (minimum fractional and significant digit settings are ignored).
`roundingIncrement` Experimental
Specifies the rounding-increment precision. Must be one of the following integers: `1`, `2`, `5`, `10`, `20`, `25`, `50`, `100`, `200`, `250`, `500`, `1000`, `2000`, `2500`, `5000`.
**Note:** The `roundingIncrement` option controls the rounding increment to be used when formatting numbers:
* It indicates the increment at which rounding should take place relative to the calculated rounding magnitude.
* It cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.
For example, if `maximumFractionDigits` is 2 and `roundingIncrement` is 5, then the number is rounded to the nearest 0.05 ("nickel rounding").
```
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```
If you set `minimumFractionDigits` and `maximumFractionDigits`, they must set them to the same value; otherwise a `RangeError` is thrown.
`trailingZeroDisplay` Experimental
A string expressing the strategy for displaying trailing zeros on whole numbers. The default is `"auto"`.
* `"auto"`: keep trailing zeros according to `minimumFractionDigits` and `minimumSignificantDigits`.
* `"stripIfInteger"`: remove the fraction digits *if* they are all zero. This is the same as `auto` if any of the fraction digits is non-zero.
The following properties fall into two groups: `minimumIntegerDigits`, `minimumFractionDigits`, and `maximumFractionDigits` in one group, `minimumSignificantDigits` and `maximumSignificantDigits` in the other. If properties from both groups are specified, conflicts in the resulting display format are resolved based on the value of the [`roundingPriority`](#roundingpriority) property.
`minimumIntegerDigits` The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from 1 to 21; the default is 1.
`minimumFractionDigits` The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information).
`maximumFractionDigits` The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of `minimumFractionDigits` and 3; the default for currency formatting is the larger of `minimumFractionDigits` and the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information); the default for percent formatting is the larger of `minimumFractionDigits` and 0.
`minimumSignificantDigits` The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
`maximumSignificantDigits` The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.
### Return value
A new `Intl.NumberFormat` object.
**Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the [browser compatibility table](#browser_compatibility).
Normally, `Intl.NumberFormat()` can be called with or without [`new`](../../../operators/new), and a new `Intl.NumberFormat` instance is returned in both cases. However, if the [`this`](../../../operators/this) value is an object that is [`instanceof`](../../../operators/instanceof) `Intl.NumberFormat` (doesn't necessarily mean it's created via `new Intl.NumberFormat`; just that it has `Intl.NumberFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.NumberFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).
```
const formatter = Intl.NumberFormat.call(
{ \_\_proto\_\_: Intl.NumberFormat.prototype },
"en-US",
{ notation: "scientific" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: NumberFormat [Intl.NumberFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```
Note that there's only one actual `Intl.NumberFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the [`format()`](format) and [`resolvedOptions()`](resolvedoptions) methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. [`formatRange()`](formatrange)) would fail with "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called `ChainNumberFormat`, does not happen when `Intl.NumberFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.NumberFormat`. If you call it directly as `Intl.NumberFormat()`, the `this` value is [`Intl`](../../intl), and a new `Intl.NumberFormat` instance is created normally.
Examples
--------
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
const amount = 3500;
console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
```
### Decimal and percent formatting
```
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "decimal",
}).format(amount); // '3,500'
new Intl.NumberFormat("en-US", {
style: "percent",
}).format(amount); // '350,000%'
```
### Unit formatting
If the `style` is `'unit'`, a `unit` property must be provided. Optionally, `unitDisplay` controls the unit formatting.
```
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
}).format(amount); // '3,500 L'
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}).format(amount); // '3,500 liters'
```
### Currency formatting
If the `style` is `'currency'`, a `currency` property must be provided. Optionally, `currencyDisplay` and `currencySign` control the unit formatting.
```
const amount = -3500;
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(amount); // '-$3,500.00'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencyDisplay: "name",
}).format(amount); // '-3,500.00 US dollars'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
}).format(amount); // '($3,500.00)'
```
### Scientific, engineering or compact notations
Scientific and compact notation are represented by the `notation` option and can be formatted like this:
```
new Intl.NumberFormat("en-US", {
notation: "scientific",
}).format(987654321);
// 9.877E8
new Intl.NumberFormat("pt-PT", {
notation: "scientific",
}).format(987654321);
// 9,877E8
new Intl.NumberFormat("en-GB", {
notation: "engineering",
}).format(987654321);
// 987.654E6
new Intl.NumberFormat("de", {
notation: "engineering",
}).format(987654321);
// 987,654E6
new Intl.NumberFormat("zh-CN", {
notation: "compact",
}).format(987654321);
// 9.9亿
new Intl.NumberFormat("fr", {
notation: "compact",
compactDisplay: "long",
}).format(987654321);
// 988 millions
new Intl.NumberFormat("en-GB", {
notation: "compact",
compactDisplay: "short",
}).format(987654321);
// 988M
```
### Displaying signs
Display a sign for positive and negative numbers, but not zero:
```
new Intl.NumberFormat("en-US", {
style: "percent",
signDisplay: "exceptZero",
}).format(0.55);
// '+55%'
```
Note that when the currency sign is "accounting", parentheses might be used instead of a minus sign:
```
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
signDisplay: "always",
}).format(-3500);
// '($3,500.00)'
```
### FractionDigits, SignificantDigits and IntegerDigits
You can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.
**Note:** If both significant and fractional digit limits are specified, then the actual formatting depends on the [`roundingPriority`](#roundingpriority).
#### Using FractionDigits and IntegerDigits
The integer and fraction digit properties indicate the number of digits to display before and after the decimal point, respectively. If the value to display has fewer integer digits than specified, it will be left-padded with zeros to the expected number. If it has fewer fractional digits, it will be right-padded with zeros. Both cases are shown below:
```
// Formatting adds zeros to display minimum integers and fractions
console.log(
new Intl.NumberFormat("en", {
minimumIntegerDigits: 3,
minimumFractionDigits: 4,
}).format(4.33)
);
// "004.3300"
```
If a value has more fractional digits than the specified maximum number, it will be rounded. The *way* that it is rounded depends on the [`roundingMode`](#roundingmode) property (more details are provided in the [rounding modes](#rounding_modes) section). Below the value is rounded from five fractional digits (`4.33145`) to two (`4.33`):
```
// Display value shortened to maximum number of digits
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).format(4.33145)
);
// "4.33"
```
The minimum factional digits have no effect if the value already has more than 2 fractional digits:
```
// Minimum fractions have no effect if value is higher precision.
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).format(4.33145)
);
// "4.331"
```
**Warning:** Watch out for default values as they may affect formatting even if not specified in your code. The default maximum digit value is `3` for plain values, `2` for currency, and may have different values for other predefined types.
The formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits! This is because a default value of `maximumFractionDigits` is set when we specify `minimumFractionDigits`, and visa versa. The default values of `maximumFractionDigits` and `minimumFractionDigits` are `3` and `0`, respectively.
You can use [`resolvedOptions()`](resolvedoptions) to inspect the formatter.
```
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).resolvedOptions()
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 0,
// maximumFractionDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).resolvedOptions()
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 2,
// maximumFractionDigits: 3,
// …
// }
```
#### Using SignificantDigits
The number of *significant digits* is the total number of digits including both integer and factional parts. The `maximumSignificantDigits` is used to indicate the total number of digits from the original value to display.
The examples below show how this works. Note in particular the last case: only the first digit is retained and the others are discarded/set to zero.
```
// Display 5 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 5,
}).format(54.33145)
);
// "54.331"
// Max 2 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(54.33145)
);
// "54"
// Max 1 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 1,
}).format(54.33145)
);
// "50"
```
The `minimumSignificantDigits` ensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.
```
// Minimum 10 significant digits
console.log(
new Intl.NumberFormat("en", {
minimumSignificantDigits: 10,
}).format(54.33145)
);
// "54.33145000"
```
**Warning:** Watch out for default values as they may affect formatting. If only one `SignificantDigits` property is used, then its counterpart will automatically be applied with the default value. The default maximum and minimum significant digit values are 20 and 1, respectively.
#### Specifying significant and fractional digits at the same time
The fraction digits ([`minimumFractionDigits`](#minimumfractiondigits)/[`maximumFractionDigits`](#maximumfractiondigits)) and significant digits ([`minimumSignificantDigits`](#minimumsignificantdigits)/[`maximumSignificantDigits`](#maximumsignificantdigits)) are both ways of controlling how many fractional and leading digits should be formatted. If both are used at the same time, it is possible for them to conflict.
These conflicts are resolved using the [`roundingPriority`](#roundingpriority) property. By default, this has a value of `"auto"`, which means that if either [`minimumSignificantDigits`](#minimumsignificantdigits) or [`maximumSignificantDigits`](#minimumsignificantdigits) is specified, the fractional and integer digit properties will be ignored.
For example, the code below formats the value of `4.33145` with `maximumFractionDigits: 3`, and then `maximumSignificantDigits: 2`, and then both. The value with both is the one set with `maximumSignificantDigits`.
```
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
}).format(4.33145)
);
// "4.331"
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(4.33145)
);
// "4.3"
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).format(4.33145)
);
// "4.3"
```
Using [`resolvedOptions()`](resolvedoptions) to inspect the formatter, we can see that the returned object does not include `maximumFractionDigits` when `maximumSignificantDigits` or `minimumSignificantDigits` are specified.
```
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).resolvedOptions()
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 1,
// maximumSignificantDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
minimumSignificantDigits: 2,
}).resolvedOptions()
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 2,
// maximumSignificantDigits: 21,
// …
// }
```
In addition to `"auto"`, you can resolve conflicts by specifying [`roundingPriority`](#roundingpriority) as `"morePrecision"` or `"lessPrecision"`. The formatter calculates the precision using the values of `maximumSignificantDigits` and `maximumFractionDigits`.
The code below shows the format being selected for the three different rounding priorities:
```
const maxFracNF = new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
});
console.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);
// "maximumFractionDigits:2 - 1.235"
const maxSigNS = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
});
console.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);
// "maximumSignificantDigits:3 - 1.23"
const bothAuto = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`auto - ${bothAuto.format(1.23456)}`);
// "auto - 1.23"
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`lessPrecision - ${bothLess.format(1.23456)}`);
// "lessPrecision - 1.23"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`morePrecision - ${bothMore.format(1.23456)}`);
// "morePrecision - 1.235"
```
Note that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value. The example below formats the value `1` specifying `minimumFractionDigits: 2` (formatting to `1.00`) and `minimumSignificantDigits: 2` (formatting to `1.0`). Since `1.00` has more digits than `1.0`, this should be the result when prioritizing `morePrecision`, but in fact the opposite is true:
```
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`lessPrecision - ${bothLess.format(1)}`);
// "lessPrecision - 1.00"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`morePrecision - ${bothMore.format(1)}`);
// "morePrecision - 1.0"
```
The reason for this is that only the "maximum precision" values are used for the calculation, and the default value of `maximumSignificantDigits` is much higher than `maximumFractionDigits`.
**Note:** The working group have proposed a modification of the algorithm where the formatter should evaluate the result of using the specified fractional and significant digits independently (taking account of both minimum and maximum values). It will then select the option that displays more fractional digits if `morePrecision` is set, and fewer if `lessPrecision` is set. This will result in more intuitive behavior for this case.
### Rounding modes
If a value has more fractional digits than allowed by the constructor options, the formatted value will be *rounded* to the specified number of fractional digits. The *way* in which the value is rounded depends on the [`roundingMode`](#roundingmode) property.
Number formatters use `halfExpand` rounding by default, which rounds values "away from zero" at the half-increment (in other words, the *magnitude* of the value is rounded up).
For a positive number, if the fractional digits to be removed are closer to the next increment (or on the half way point) then the remaining fractional digits will be rounded up, otherwise they are rounded down. This is shown below: 2.23 rounded to two significant digits is truncated to 2.2 because 2.23 is less than the half increment 2.25, while values of 2.25 and greater are rounded up to 2.3:
```
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.23)
);
// "2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.25)
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.28)
);
// "2.3"
// "2.3"
```
A negative number on or below the half-increment point is also rounded away from zero (becomes more negative):
```
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.23)
);
// "-2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.25)
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.28)
);
// "-2.3"
// "-2.3"
```
The table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.
| rounding mode | 2.23 | 2.25 | 2.28 | -2.23 | -2.25 | -2.28 |
| --- | --- | --- | --- | --- | --- | --- |
| `ceil` | 2.3 | 2.3 | 2.3 | -2.2 | -2.2 | -2.2 |
| `floor` | 2.2 | 2.2 | 2.2 | -2.3 | -2.3 | -2.3 |
| `expand` | 2.3 | 2.3 | 2.3 | -2.3 | -2.3 | -2.3 |
| `trunc` | 2.2 | 2.2 | 2.2 | -2.2 | -2.2 | -2.2 |
| `halfCeil` | 2.2 | 2.3 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfFloor` | 2.2 | 2.2 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfExpand` | 2.2 | 2.3 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfTrunc` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfEven` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
When using `halfEven`, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of `halfEven` in the table above is the same as `halfTrunc`, because the magnitudes of all numbers are between a smaller "even" number (2.2) and a larger "odd" number (2.3). If the numbers are between ±2.3 and ±2.4, `halfEven` will behave like `halfExpand` instead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.
### Using roundingIncrement
Sometimes we want to round the remaining fractional digits to some other increment than the next integer. For example, currencies for which the smallest coin is 5 cents might want to round the value to increments of 5, reflecting amounts that can actually be paid in cash.
This kind of rounding can be achieved with the [`roundingIncrement`](#roundingincrement) property.
For example, if `maximumFractionDigits` is 2 and `roundingIncrement` is 5, then the number is rounded to the nearest 0.05:
```
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```
This particular pattern is referred to as "nickel rounding", where nickel is the colloquial name for a USA 5 cent coin. To round to the nearest 10 cents ("dime rounding"), you could change `roundingIncrement` to `10`.
```
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```
You can also use [`roundingMode`](#roundingmode) to change the rounding algorithm. The example below shows how `halfCeil` rounding can be used to round the value "less positive" below the half-rounding increment and "more positive" if above or on the half-increment. The incremented digit is "0.05" so the half-increment is at .025 (below, this is shown at 11.225).
```
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
roundingMode: "halfCeil",
});
console.log(nf.format(11.21)); // "$11.20"
console.log(nf.format(11.22)); // "$11.20"
console.log(nf.format(11.224)); // "$11.20"
console.log(nf.format(11.225)); // "$11.25"
console.log(nf.format(11.23)); // "$11.25"
```
If you need to change the number of digits, remember that `minimumFractionDigits` and `maximumFractionDigits` must both be set to the same value, or a `RangeError` is thrown.
`roundingIncrement` cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-numberformat-constructor](https://tc39.es/ecma402/#sec-intl-numberformat-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `IntlLegacyConstructedSymbol` | 91
57
The fallback symbol property has description `IntlFallback`. | 91
79
The fallback symbol property has description `IntlFallback`. | 54 | No | 77
44
The fallback symbol property has description `IntlFallback`. | 14.1 | 91
57
The fallback symbol property has description `IntlFallback`. | 91
57
The fallback symbol property has description `IntlFallback`. | 56 | 64
43
The fallback symbol property has description `IntlFallback`. | 14.5 | 16.0
7.0
The fallback symbol property has description `IntlFallback`. | ? | 16.0.0
8.0.0
The fallback symbol property has description `IntlFallback`. |
| `NumberFormat` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `NumberFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `options_compactDisplay_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_currencyDisplay_parameter` | 77 | 79 | 78 | No | 64 | 14.1
10-14.1
Doesn't support `currencyDisplay: 'narrowSymbol'`. | 77 | 77 | 79 | 55 | 14.5
10-14.5
Doesn't support `currencyDisplay: 'narrowSymbol'`. | 12.0 | 1.8 | 12.11.0 |
| `options_currencySign_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_notation_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_roundingIncrement_parameter` | No | No | No | No | No | No | No | No | No | No | No | No | No | No |
| `options_roundingMode_parameter` | No | No | No | No | No | No | No | No | No | No | No | No | No | No |
| `options_roundingPriority_parameter` | No | No | No | No | No | No | No | No | No | No | No | No | No | No |
| `options_signDisplay_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_trailingZeroDisplay_parameter` | 106 | 106 | No | No | 92 | 15.4 | 106 | 106 | No | 72 | 15.4 | No | No | No |
| `options_unitDisplay_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_unit_parameter` | 77 | 79 | 78 | No | 64 | 14.1 | 77 | 77 | 79 | 55 | 14.5 | 12.0 | 1.8 | 12.11.0 |
| `options_useGrouping_parameter` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `NumberFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.NumberFormat`](../numberformat)
* [`Intl.supportedValuesOf()`](../supportedvaluesof)
* [`Intl`](../../intl)
| programming_docs |
javascript Intl.DisplayNames.prototype.resolvedOptions() Intl.DisplayNames.prototype.resolvedOptions()
=============================================
The `Intl.DisplayNames.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current [`Intl.DisplayNames`](../displaynames) object.
Syntax
------
```
resolvedOptions()
```
### Return value
An object with properties reflecting the locale and formatting options computed during the construction of the given [`Intl.DisplayNames`](../displaynames) object.
Description
-----------
The object returned by `resolvedOptions()` has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`style` The value provided for this property in the `options` argument of the constructor or the default value (`"long"`). Its value is either `"long"`, `"short"`, or `"narrow"`.
`type` The value provided for this property in the `options` argument of the constructor or the default value (`"language"`). Its value is either `"language"`, `"region"`, `"script"`, or `"currency"`.
`fallback` The value provided for this property in the options argument of the constructor or the default value (`"code"`). Its value is either `"code"` or `"none"`.
Examples
--------
### Using resolvedOptions
```
const displayNames = new Intl.DisplayNames(['de-DE'], {type: 'region'});
const usedOptions = displayNames.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "long"
console.log(usedOptions.type); // "region"
console.log(usedOptions.fallback); // "code"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.prototype.resolvedOptions](https://tc39.es/ecma402/#sec-Intl.DisplayNames.prototype.resolvedOptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
See also
--------
* [`Intl.DisplayNames`](../displaynames)
javascript Intl.DisplayNames.supportedLocalesOf() Intl.DisplayNames.supportedLocalesOf()
======================================
The `Intl.DisplayNames.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.
Syntax
------
```
Intl.DisplayNames.supportedLocalesOf(locales)
Intl.DisplayNames.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in display names that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in display names, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to display names nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.DisplayNames.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.supportedLocalesOf](https://tc39.es/ecma402/#sec-Intl.DisplayNames.supportedLocalesOf) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
See also
--------
* [`Intl.DisplayNames`](../displaynames)
javascript Intl.DisplayNames() constructor Intl.DisplayNames() constructor
===============================
The `Intl.DisplayNames()` constructor creates [`Intl.DisplayNames`](../displaynames) objects that enable the consistent translation of language, region and script display names.
Try it
------
Syntax
------
```
new Intl.DisplayNames(locales, options)
```
**Note:** `Intl.DisplayNames()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation). The following Unicode extension key is allowed:
`nu` The numbering system to be used. Possible values include: `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"deva"`, `"fullwide"`, `"gujr"`, `"guru"`, `"hanidec"`, `"khmr"`, `"knda"`, `"laoo"`, `"latn"`, `"limb"`, `"mlym"`, `"mong"`, `"mymr"`, `"orya"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`.
`options` An object with some or all of the following properties:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`style` The formatting style to use, the default is `"long"`.
* `"narrow"`
* `"short"`
* `"long"`
`type` The type to use.
* `"calendar"`
* `"currency"`
* `"dateTimeField"`
* `"language"`
* `"region"`
* `"script"`
`languageDisplay` The `languageDisplay` it's only usable along with type `language`, defaults to `dialect`.
* `"dialect"`
* `"standard"`
`fallback` The fallback to use, the default is `"code"`.
* `"code"`
* `"none"`
Examples
--------
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```
console.log((new Intl.DisplayNames([], { type: 'language' })).of('US'));
// 'us'
```
### Using type `dateTimeField`
Example using `dateTimeField` as a type option, will return the localized date time names strings.
```
const dn = new Intl.DisplayNames('pt', {type: 'dateTimeField'});
console.log(dn.of('era')); // 'era'
console.log(dn.of('year')); // 'ano'
console.log(dn.of('month')); // 'mês'
console.log(dn.of('quarter')); // 'trimestre'
console.log(dn.of('weekOfYear')); // 'semana'
console.log(dn.of('weekday')); // 'dia da semana'
console.log(dn.of('dayPeriod')); // 'AM/PM'
console.log(dn.of('day')); // 'dia'
console.log(dn.of('hour')); // 'hora'
console.log(dn.of('minute')); // 'minuto'
console.log(dn.of('second')); // 'segundo'
```
### Using type `calendar`
Example using `calendar` as a type option, will return the localized calendar names strings.
```
const dn = new Intl.DisplayNames('en', {type: 'calendar'});
console.log(dn.of('roc')); // 'Minguo Calendar'
console.log(dn.of('gregory')); // 'Gregorian Calendar'
console.log(dn.of('chinese')); // 'Chinese Calendar'
```
### Using type `language` with `languageDisplay`
Example using `language` as a type with `languageDisplay` options.
```
// Using `dialect` option
const dnDialect = new Intl.DisplayNames('en', {type: 'language', languageDisplay: 'dialect'});
console.log(dnDialect.of('en-GB')); // 'British English'
// Using `standard` option
const dnStd = new Intl.DisplayNames('en', {type: 'language', languageDisplay: 'standard'});
console.log(dnStd.of('en-GB')); // 'English (United Kingdom)'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-displaynames-constructor](https://tc39.es/ecma402/#sec-intl-displaynames-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `DisplayNames` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
See also
--------
* [`Intl.DisplayNames`](../displaynames)
* [`Intl.supportedValuesOf()`](../supportedvaluesof)
* [`Intl`](../../intl)
javascript Intl.DisplayNames.prototype.of() Intl.DisplayNames.prototype.of()
================================
The `Intl.DisplayNames.prototype.of()` method receives a code and returns a string based on the locale and options provided when instantiating `Intl.DisplayNames`.
Try it
------
Syntax
------
```
of(code)
```
### Parameters
`code` The `code` to provide depends on the `type`:
* If the type is "region", `code` should be either an [two-letter ISO 3166 region code](https://www.iso.org/iso-3166-country-codes.html), or a [three-digit UN M49 geographic region](https://unstats.un.org/unsd/methodology/m49/). It is required to follow the [`unicode_region_subtag`](https://unicode.org/reports/tr35/#unicode_region_subtag) grammar.
* If the type is "script", `code` should be an [four-letter ISO 15924 script code](https://unicode.org/iso15924/iso15924-codes.html). It is required to follow the [`unicode_script_subtag`](https://unicode.org/reports/tr35/#unicode_script_subtag) grammar.
* If the type is "language", `code` should be a *languageCode* ["-" *scriptCode*] ["-" *regionCode* ] \*("-" *variant* ) subsequence of the [`unicode_language_id`](https://unicode.org/reports/tr35/#Unicode_language_identifier) grammar. *languageCode* is either a two-letter ISO 639-1 language code or a three-letter ISO 639-2 language code.
* If the type is "currency", `code` should be a [three-letter ISO 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html). It is required to have exactly three alphabetic characters.
* If the type is "dateTimeField", `code` should be one of: `"era"`, `"year"`, `"quarter"`, `"month"`, `"weekOfYear"`, `"weekday"`, `"day"`, `"dayPeriod"`, `"hour"`, `"minute"`, `"second"`, `"timeZoneName"`.
* If the type is "calendar", `code` should be a [calendar key](../locale/calendar). It is required to follow the `type` grammar of a [Unicode locale identifier](https://unicode.org/reports/tr35/#32-unicode-locale-identifier).
### Return value
A language-specific formatted string, or `undefined` if there's no data for the input and `fallback` is `"none"`.
**Note:** `fallback` is only used if `code` is structurally valid. See [using fallback](#using_fallback).
### Exceptions
[`RangeError`](../../rangeerror) Thrown if `code` is not structurally valid for the given `type`.
Examples
--------
### Using the of method
```
const regionNames = new Intl.DisplayNames("en", { type: "region" });
regionNames.of("419"); // "Latin America"
const languageNames = new Intl.DisplayNames("en", { type: "language" });
languageNames.of("fr"); // "French"
const currencyNames = new Intl.DisplayNames("en", { type: "currency" });
currencyNames.of("EUR"); // "Euro"
```
### Using fallback
When the `Intl.DisplayNames` is constructed with `fallback: "code"`, the `of()` method will return the `code` if the input looks structurally valid but there's no data for the input. If `fallback` is `"none"`, `undefined` is returned.
```
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZL")
); // "ZL"
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "none" }).of("ZL")
); // undefined
```
However, this only applies if the `code` is structurally valid. For example, if `type` is `"region"` but `code` does not follow the `unicode_region_subtag` grammar (2 alphabetic characters or 3 numeric characters), a [`RangeError`](../../rangeerror) is directly thrown instead of using the fallback.
```
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC")
); // throws RangeError: invalid value "ZLC" for option region
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.prototype.of](https://tc39.es/ecma402/#sec-Intl.DisplayNames.prototype.of) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `of` | 81 | 81 | 86 | No | 68 | 14.1 | 81 | 81 | 86 | 58 | 14.5 | 13.0 | 1.8 | 14.0.0 |
See also
--------
* [`Intl.DisplayNames`](../displaynames)
javascript Intl.Collator.prototype.compare() Intl.Collator.prototype.compare()
=================================
The `Intl.Collator.prototype.compare()` method compares two strings according to the sort order of this [`Intl.Collator`](../collator) object.
Try it
------
Syntax
------
```
compare(string1, string2)
```
### Parameters
`string1`, `string2`
The strings to compare against each other.
Description
-----------
The `compare` getter function returns a number indicating how `string1` and `string2` compare to each other according to the sort order of this [`Intl.Collator`](../collator) object: a negative value if `string1` comes before `string2`; a positive value if `string1` comes after `string2`; 0 if they are considered equal.
Examples
--------
### Using compare for array sort
Use the `compare` getter function for sorting arrays. Note that the function is bound to the collator from which it was obtained, so it can be passed directly to [`Array.prototype.sort()`](../../array/sort).
```
const a = ["Offenbach", "Österreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", ")); // "Odenwald, Österreich, Offenbach"
```
### Using compare for array search
Use the `compare` getter function for finding matching strings in arrays:
```
const a = ["Congrès", "congres", "Assemblée", "poisson"];
const collator = new Intl.Collator("fr", {
usage: "search",
sensitivity: "base",
});
const s = "congres";
const matches = a.filter((v) => collator.compare(v, s) === 0);
console.log(matches.join(", ")); // "Congrès, congres"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.collator.prototype.compare](https://tc39.es/ecma402/#sec-intl.collator.prototype.compare) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `compare` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
See also
--------
* [`Intl.Collator`](../collator)
* [`String.prototype.localeCompare()`](../../string/localecompare)
javascript Intl.Collator.prototype.resolvedOptions() Intl.Collator.prototype.resolvedOptions()
=========================================
The `Intl.Collator.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and collation options computed during initialization of this [`Intl.Collator`](../collator) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Return value
A new object with properties reflecting the locale and collation options computed during the initialization of the given [`Intl.Collator`](../collator) object.
Description
-----------
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`usage`, `sensitivity`, `ignorePunctuation`
The values provided for these properties in the `options` argument or filled in as defaults.
`collation` The value requested using the Unicode extension key `"co"`, if it is supported for `locale`, or `"default"`.
`numeric`, `caseFirst`
The values requested for these properties in the `options` argument or using the Unicode extension keys `"kn"` and `"kf"` or filled in as defaults. If the implementation does not support these properties, they are omitted.
Examples
--------
### Using the resolvedOptions method
```
const de = new Intl.Collator("de", { sensitivity: "base" });
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de"
usedOptions.usage; // "sort"
usedOptions.sensitivity; // "base"
usedOptions.ignorePunctuation; // false
usedOptions.collation; // "default"
usedOptions.numeric; // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.collator.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.collator.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `Collator()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for more details. |
See also
--------
* [`Intl.Collator`](../collator)
javascript Intl.Collator.supportedLocalesOf() Intl.Collator.supportedLocalesOf()
==================================
The `Intl.Collator.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
Intl.Collator.supportedLocalesOf(locales)
Intl.Collator.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in collation, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is not used with Indonesian and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.Collator.supportedLocalesOf(locales, options).join(", "));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.collator.supportedlocalesof](https://tc39.es/ecma402/#sec-intl.collator.supportedlocalesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.Collator`](../collator)
| programming_docs |
javascript Intl.Collator() constructor Intl.Collator() constructor
===========================
The `Intl.Collator()` constructor creates [`Intl.Collator`](../collator) objects that enable language-sensitive string comparison.
Try it
------
Syntax
------
```
new Intl.Collator()
new Intl.Collator(locales)
new Intl.Collator(locales, options)
Intl.Collator()
Intl.Collator(locales)
Intl.Collator(locales, options)
```
**Note:** `Intl.Collator()` can be called with or without [`new`](../../../operators/new). Both create a new `Intl.Collator` instance.
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
The following Unicode extension keys are allowed:
**Note:** These keys can usually also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
`co` Variant collations for certain locales. Possible values include:
* `big5han` (Chinese; not available in Chrome or Edge)
* `compat` (Arabic)
* `dict` (Sinhala)
* `direct` (deprecated, do not use)
* `ducet` (not available, do not use)
* `emoji` (root)
* `eor` (root)
* `gb2312` (Chinese; not available in Chrome or Edge)
* `phonebk` (German)
* `phonetic` (Lingala)
* `pinyin` (Chinese)
* `reformed` (Swedish; do not specify explicitly as this is the default for Swedish)
* `searchjl` (Korean; do not use for sorting)
* `stroke` (Chinese)
* `trad`
* `unihan` (Chinese, Japanese, and Korean; not available in Chrome or Edge)
* `zhuyin` (Chinese)
This option can be also be set through the `options` property `collation`.
`kn` Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are `"true"` and `"false"`. This option can be also be set through the `options` property `numeric`.
`kf` Whether upper case or lower case should sort first. Possible values are `"upper"`, `"lower"`, or `"false"` (use the locale's default). This option can be also be set through the `options` property `caseFirst`.
`options` Optional
An object with some or all of the following properties:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`usage` Whether the comparison is for sorting or for searching for matching strings. Possible values are `"sort"` and `"search"`; the default is `"sort"`.
`sensitivity` Which differences in the strings should lead to non-zero result values. Possible values are:
* `"base"`: Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
* `"accent"`: Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
* `"case"`: Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
* `"variant"`: Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.
The default is `"variant"` for usage `"sort"`; it's locale dependent for usage `"search"`.
`ignorePunctuation` Whether punctuation should be ignored. Possible values are `true` and `false`; the default is `false`.
`numeric` Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are `true` and `false`; the default is `false`. This option can also be set through the `kn` Unicode extension key; if both are provided, this `options` property takes precedence.
`caseFirst` Whether upper case or lower case should sort first. Possible values are `"upper"`, `"lower"`, or `"false"` (use the locale's default). This option can also be set through the `kf` Unicode extension key; if both are provided, this `options` property takes precedence.
`collation` Variant collations for certain locales. Possible values include:
* `big5han` (Chinese; not available in Chrome or Edge)
* `compat` (Arabic)
* `dict` (Sinhala)
* `direct` (deprecated, do not use)
* `ducet` (not available, do not use)
* `emoji` (root)
* `eor` (root)
* `gb2312` (Chinese; not available in Chrome or Edge)
* `phonebk` (German)
* `phonetic` (Lingala)
* `pinyin` (Chinese)
* `reformed` (Swedish; do not specify explicitly as this is the default for Swedish)
* `searchjl` (Korean; do not use for sorting)
* `stroke` (Chinese)
* `trad`
* `unihan` (Chinese, Japanese, and Korean; not available in Chrome or Edge)
* `zhuyin` (Chinese)
This option can also be set through the `co` Unicode extension key; if both are provided, this `options` property takes precedence.
Examples
--------
### Using Collator
The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:
```
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```
Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-the-intl-collator-constructor](https://tc39.es/ecma402/#sec-the-intl-collator-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Collator` | 24 | 12 | 29 | 11 | 15 | 10 | 4.4 | 25 | 56 | 14 | 10 | 1.5 | 1.8 | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `Collator` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `options_caseFirst_parameter` | 24 | 18 | 55 | No | 15 | 11 | 4.4 | 25 | 56 | 14 | 11 | 1.5 | 1.8 | 0.12.0 |
| `options_collation_parameter` | 87 | 87 | 85 | No | 73 | 14.1 | 87 | 87 | 85 | No | 14.5 | 14.0 | 1.8 | 15.0.0 |
See also
--------
* [`Intl.Collator`](../collator)
* [`Intl`](../../intl)
javascript Intl.Segmenter() constructor Intl.Segmenter() constructor
============================
The `Intl.Segmenter()` constructor creates [`Intl.Segmenter`](../segmenter) objects that enable locale-sensitive text segmentation.
Try it
------
Syntax
------
```
new Intl.Segmenter()
new Intl.Segmenter(locales)
new Intl.Segmenter(locales, options)
```
**Note:** `Intl.Segmenter()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object with some or all of the following properties:
`granularity` Optional
A string. Possible values are:
`"grapheme"` (default) Split the input into segments at grapheme cluster (user-perceived character) boundaries, as determined by the locale.
`"word"` Split the input into segments at word boundaries, as determined by the locale.
`"sentence"` Split the input into segments at sentence boundaries, as determined by the locale.
`localeMatcher` Optional
The locale matching algorithm to use. Possible values are:
`"best fit"` (default) The runtime may choose a possibly more suited locale than the result of the lookup algorithm.
`"lookup"` Use the [BCP 47 Lookup algorithm](https://datatracker.ietf.org/doc/html/rfc4647#section-3.4) to choose the locale from `locales`. For each locale in `locales`, the runtime returns the first supported locale (possibly removing restricting subtags of the provided locale tag to find such a supported locale. In other words providing `"de-CH"` as `locales` may result in using `"de"` if `"de"` is supported but `"de-CH"` is not).
### Return value
A new [`Intl.Segmenter`](../segmenter) instance.
Examples
--------
### Basic usage
The following example shows how to count words in a string using the Japanese language (where splitting the string using `String` methods would have given an incorrect result).
```
const text = "吾輩は猫である。名前はたぬき。";
const japaneseSegmenter = new Intl.Segmenter("ja-JP", {granularity: "word"});
console.log([...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike).length);
// 8, as the text is segmented as '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-segmenter-constructor](https://tc39.es/ecma402/#sec-intl-segmenter-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Segmenter` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
javascript Intl.Segmenter.prototype.segment() Intl.Segmenter.prototype.segment()
==================================
The `Intl.Segmenter.prototype.segment()` method segments a string according to the locale and granularity of this [`Intl.Segmenter`](../segmenter) object.
Try it
------
Syntax
------
```
segment(input)
```
### Parameters
`input` The text to be segmented as a string.
### Return value
A new iterable [`Segments`](segment/segments) object containing the segments of the input string, using the segmenter's locale and granularity.
Examples
--------
```
// Create a locale-specific word segmenter
const segmenter = new Intl.Segmenter("fr", {granularity: "word"});
// Use it to get an iterator over the segments of a string
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);
// Use that for segmentation
for (const {segment, index, isWordLike} of segments) {
console.log("segment at code units [%d, %d]: «%s»%s",
index, index + segment.length,
segment,
isWordLike ? " (word-like)" : ""
);
}
// segment at code units [0, 3]: «Moi» (word-like)
// segment at code units [3, 4]: « »
// segment at code units [4, 5]: «?»
// segment at code units [5, 6]: « »
// segment at code units [6, 11]: «N'est» (word-like)
// segment at code units [11, 12]: «-»
// segment at code units [12, 14]: «ce» (word-like)
// segment at code units [14, 15]: « »
// segment at code units [15, 18]: «pas» (word-like)
// segment at code units [18, 19]: « »
// segment at code units [19, 20]: «?»
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.segmenter.prototype.segment](https://tc39.es/ecma402/#sec-intl.segmenter.prototype.segment) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `segment` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
javascript Intl.Segmenter.prototype.resolvedOptions() Intl.Segmenter.prototype.resolvedOptions()
==========================================
The `Intl.Segmenter.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and granularity options computed during the initialization of this [`Intl.Segmenter`](../segmenter) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and collation options computed during the initialization of the given [`Intl.Segmenter`](../segmenter) object.
Description
-----------
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`granularity` The value provided for this property in the `options` argument or filled in as the default.
Examples
--------
### Basic usage
```
const spanishSegmenter = new Intl.Segmenter("es", {granularity: "sentence"});
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "sentence"
```
### Default granularity
```
const spanishSegmenter = new Intl.Segmenter("es");
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "grapheme"
```
### Fallback locale
```
const banSegmenter = new Intl.Segmenter("ban");
const options = banSegmenter.resolvedOptions();
console.log(options.locale);
// "fr" on a runtime where the Balinese locale
// is not supported and French is the default locale
console.log(options.granularity); // "grapheme"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.segmenter.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.segmenter.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
javascript Intl.Segmenter.supportedLocalesOf() Intl.Segmenter.supportedLocalesOf()
===================================
The `Intl.Segmenter.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
Intl.Segmenter.supportedLocalesOf(locales)
Intl.Segmenter.supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [`Intl`](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in segmentation without having to fall back to the runtime's default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in list formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to segmentation nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.Segmenter.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.segmenter.supportedlocalesof](https://tc39.es/ecma402/#sec-intl.segmenter.supportedlocalesof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
javascript Segments Segments
========
A `Segments` object is an iterable collection of the segments of a text string. It is returned by a call to the [`segment()`](../segment) method of an [`Intl.Segmenter`](../../segmenter) object.
Try it
------
Instance methods
----------------
[`Segments.prototype.containing()`](segments/containing) Returns an object describing the segment in the original string that includes the code unit at a specified index.
[`Segments.prototype[@@iterator]()`](segments/@@iterator) Returns an iterator to iterate over the segments.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-segments-objects](https://tc39.es/ecma402/#sec-segments-objects) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `Segments` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
| `containing` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
See also
--------
* [`Intl.Segmenter`](../../segmenter)
* [`Intl.Segmenter.prototype.segment()`](../segment)
javascript Segments.prototype[@@iterator]() Segments.prototype[@@iterator]()
================================
The `@@iterator` method of a `Segments` object implements the [iterable protocol](../../../../../iteration_protocols) and allows `Segments` objects to be consumed by most syntaxes expecting iterables, such as the [spread syntax](../../../../../operators/spread_syntax) and [`for...of`](../../../../../statements/for...of) loops. It returns an iterator that yields data about each segment.
Try it
------
Syntax
------
```
segments[Symbol.iterator]()
```
### Return value
A new iterable iterator object that yields data about each segment. Each yielded object has the same properties as the object returned by the [`containing()`](containing) method.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Segments` objects [iterable](../../../../../iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically calls this method to obtain the iterator to loop over.
```
const segmenter = new Intl.Segmenter("zh-CN", { granularity: "word" });
const input = "你好,世界!我爱编程。";
for (const value of segmenter.segment(input)) {
console.log(value);
}
/\*
{segment: '你好', index: 0, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: ',', index: 2, input: '你好,世界!我爱编程。', isWordLike: false}
{segment: '世界', index: 3, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '!', index: 5, input: '你好,世界!我爱编程。', isWordLike: false}
{segment: '我', index: 6, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '爱', index: 7, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '编', index: 8, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '程', index: 9, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '。', index: 10, input: '你好,世界!我爱编程。', isWordLike: false}
\*/
```
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);
const iterator = segments[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
/\*
{segment: 'Moi', index: 0, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 3, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 4, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: ' ', index: 5, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: "N'est", index: 6, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: '-', index: 11, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'ce', index: 12, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 14, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'pas', index: 15, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 18, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 19, input: "Moi ? N'est-ce pas ?", isWordLike: false}
\*/
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-%segmentsprototype%-@@iterator](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
See also
--------
* [Iteration protocols](../../../../../iteration_protocols)
* [`Array.prototype[@@iterator]()`](../../../../array/@@iterator)
* [`Intl.Segmenter`](../../../segmenter)
* [`Intl.Segmenter.prototype.segment()`](../../segment)
| programming_docs |
javascript Segments.prototype.containing() Segments.prototype.containing()
===============================
The `containing()` method of a `Segments` object returns an object describing the segment in the string that includes the code unit at the specified index.
Try it
------
Syntax
------
```
containing(codeUnitIndex)
```
### Parameters
`codeUnitIndex` Optional
A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to `0`.
### Return Value
An object describing the segment of the original string with the following properties, or `undefined` if the supplied index value is out of bounds.
`segment` A string containing the segment extracted from the original input string.
`index` The code unit index in the original input string at which the segment begins.
`input` The complete input string that was segmented.
`isWordLike` A boolean value only if `granularity` is `"word"`; otherwise, `undefined`. If `granularity` is `"word"`, then `isWordLike` is `true` when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, `false`.
Examples
--------
```
// ┃0 1 2 3 4 5┃6┃7┃8┃9 ← code unit index
// ┃A l l o n s┃-┃y┃!┃ ← code unit
const input = "Allons-y!";
const segmenter = new Intl.Segmenter("fr", {granularity: "word"});
const segments = segmenter.segment(input);
let current = segments.containing();
// { index: 0, segment: "Allons", isWordLike: true }
current = segments.containing(4);
// { index: 0, segment: "Allons", isWordLike: true }
current = segments.containing(6);
// { index: 6, segment: "-", isWordLike: false }
current = segments.containing(current.index + current.segment.length);
// { index: 7, segment: "y", isWordLike: true }
current = segments.containing(current.index + current.segment.length);
// { index: 8, segment: "!", isWordLike: false }
current = segments.containing(current.index + current.segment.length);
// undefined
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-%segmentsprototype%.containing](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `containing` | 87 | 87 | No | No | 73 | 14.1 | 87 | 87 | No | 62 | 14.5 | 14.0 | 1.8 | 16.0.0 |
See also
--------
* [`Intl.Segmenter`](../../../segmenter)
* [`Intl.Segmenter.prototype.segment()`](../../segment)
javascript Intl.RelativeTimeFormat.prototype.format() Intl.RelativeTimeFormat.prototype.format()
==========================================
The `Intl.RelativeTimeFormat.prototype.format()` method formats a `value` and `unit` according to the locale and formatting options of this [`Intl.RelativeTimeFormat`](../relativetimeformat) object.
Try it
------
Syntax
------
```
format(value, unit)
```
### Parameters
`value` Numeric value to use in the internationalized relative time message.
`unit` Unit to use in the relative time internationalized message. Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`. Plural forms are also permitted.
Description
-----------
The function returned by the `format` getter formats a value and a unit into a string according to the locale and formatting options of this [`Intl.RelativeTimeFormat`](../relativetimeformat) object.
Examples
--------
### Basic format usage
The following example shows how to create a relative time formatter using the English language.
```
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using the auto option
If `numeric:auto` option is passed, it will produce the string `yesterday`, `today`, or `tomorrow` instead of `1 day ago`, `in 0 days`, or `in 1 day`. This allows to not always have to use numeric values in the output.
```
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "yesterday"
rtf.format(0, "day"); // "today"
// Format relative time using positive day unit (1).
rtf.format(1, "day"); // "tomorrow"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.RelativeTimeFormat.prototype.format](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.format) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `format` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
See also
--------
* [`Intl.RelativeTimeFormat`](../relativetimeformat)
javascript Intl.RelativeTimeFormat() constructor Intl.RelativeTimeFormat() constructor
=====================================
The `Intl.RelativeTimeFormat()` constructor creates [`Intl.RelativeTimeFormat`](../relativetimeformat) objects.
Syntax
------
```
new Intl.RelativeTimeFormat()
new Intl.RelativeTimeFormat(locales)
new Intl.RelativeTimeFormat(locales, options)
```
**Note:** `Intl.RelativeTimeFormat()` can only be constructed with [`new`](../../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../../typeerror).
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object with some or all of the following properties:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
`numeric` The format of output message. Possible values are:
* `"always"` (default, e.g., `1 day ago`),
* or `"auto"` (e.g., `yesterday`). The `"auto"` value allows to not always have to use numeric values in the output.
`style` The length of the internationalized message. Possible values are:
* `"long"` (default, e.g., `in 1 month`)
* `"short"` (e.g., `in 1 mo.`),
* or `"narrow"` (e.g., `in 1 mo.`). The narrow style could be similar to the short style for some locales.
Examples
--------
### Basic format usage
The following example shows how to create a relative time formatter using the English language.
```
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using the auto option
If `numeric:auto` option is passed, it will produce the string `yesterday` or `tomorrow` instead of `1 day ago` or `in 1 day`. This allows to not always have to use numeric values in the output.
```
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "yesterday"
// Format relative time using positive day unit (1).
rtf.format(1, "day"); // "tomorrow"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl-relativetimeformat-constructor](https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `RelativeTimeFormat` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the `RelativeTimeFormat` instance silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.RelativeTimeFormat`](../relativetimeformat)
* [`Intl`](../../intl)
* [The Intl.RelativeTimeFormat API](https://v8.dev/features/intl-relativetimeformat)
javascript Intl.RelativeTimeFormat.prototype.resolvedOptions() Intl.RelativeTimeFormat.prototype.resolvedOptions()
===================================================
The `Intl.RelativeTimeFormat.prototype.resolvedOptions()` method returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this [`Intl.RelativeTimeFormat`](../relativetimeformat) object.
Try it
------
Syntax
------
```
resolvedOptions()
```
### Return value
A new object with properties reflecting the locale and number formatting options computed during the initialization of the given [`Intl.RelativeTimeFormat`](../relativetimeformat) object.
Description
-----------
The resulting object has the following properties:
`locale` The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
`style` The length of the internationalized message. Possible values are:
* `"long"` (default, e.g., `in 1 month`)
* `"short"` (e.g., `in 1 mo.`),
* or `"narrow"` (e.g., `in 1 mo.`). The narrow style could be similar to the short style for some locales.
`numeric` The format of output message. Possible values are:
* `"always"` (default, e.g., `1 day ago`),
* or `"auto"` (e.g., `yesterday`). The `"auto"` value allows to not always have to use numeric values in the output.
`numberingSystem` The value requested using the Unicode extension key `"nu"` or filled in as a default.
Examples
--------
### Using the resolvedOptions() method
```
const de = new Intl.RelativeTimeFormat('de-DE');
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de-DE"
usedOptions.style; // "long"
usedOptions.numeric; // "always"
usedOptions.numberingSystem; // "latn"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-intl.relativetimeformat.prototype.resolvedoptions](https://tc39.es/ecma402/#sec-intl.relativetimeformat.prototype.resolvedoptions) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `resolvedOptions` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
| `numberingSystem` | 73 | 79 | 70 | No | 60 | 14 | 73 | 73 | 79 | 52 | 14 | 11.0 | 1.8 | 12.0.0 |
See also
--------
* [`Intl.RelativeTimeFormat`](../relativetimeformat)
javascript Intl.RelativeTimeFormat.supportedLocalesOf() Intl.RelativeTimeFormat.supportedLocalesOf()
============================================
The `Intl.RelativeTimeFormat.supportedLocalesOf()` static method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
Try it
------
Syntax
------
```
supportedLocalesOf(locales)
supportedLocalesOf(locales, options)
```
### Parameters
`locales` A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../../intl#locale_identification_and_negotiation).
`options` Optional
An object that may have the following property:
`localeMatcher` The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the [Intl](../../intl#locale_identification_and_negotiation) page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
Description
-----------
Returns an array with a subset of the language tags provided in `locales`. The language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale.
Examples
--------
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```
const locales = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options = { localeMatcher: 'lookup' };
console.log(Intl.RelativeTimeFormat.supportedLocalesOf(locales, options).join(', '));
// "id-u-co-pinyin, de-ID"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.RelativeTimeFormat.supportedLocalesOf](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `supportedLocalesOf` | 71 | 79 | 65 | No | 58 | 14 | 71 | 71 | 65 | 50 | 14 | 10.0 | 1.8 | 13.0.0
12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
See also
--------
* [`Intl.RelativeTimeFormat`](../relativetimeformat)
javascript Intl.RelativeTimeFormat.prototype.formatToParts() Intl.RelativeTimeFormat.prototype.formatToParts()
=================================================
The `Intl.RelativeTimeFormat.prototype.formatToParts()` method returns an [`Array`](../../array) of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
Try it
------
Syntax
------
```
formatToParts(value, unit)
```
### Parameters
`value` Numeric value to use in the internationalized relative time message.
`unit` Unit to use in the relative time internationalized message. Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`. Plural forms are also permitted.
### Return value
An [`Array`](../../array) of objects containing the formatted relative time in parts.
Description
-----------
The `Intl.RelativeTimeFormat.prototype.formatToParts` method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its constituent parts and separating it from other surrounding text. These objects have two properties: type a `NumberFormat` formatToParts type, and value, which is the String which is the component of the output. If a "part" came from `NumberFormat`, it will have a unit property which indicates the unit being formatted; literals which are part of the larger frame will not have this property.
Examples
--------
### Using formatToParts
```
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using the day unit
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]
rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Internationalization API Specification # sec-Intl.RelativeTimeFormat.prototype.formatToParts](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.formatToParts) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `formatToParts` | 71 | 79 | 70 | No | 58 | 14 | 71 | 71 | 79 | 50 | 14 | 10.0 | 1.8 | 12.0.0
Before version 13.0.0, only the locale data for `en-US` is available by default. See [the `RelativeTimeFormat()` constructor](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat) for more details. |
See also
--------
* [`Intl.RelativeTimeFormat`](../relativetimeformat)
javascript Array.prototype.sort() Array.prototype.sort()
======================
The `sort()` method sorts the elements of an array *[in place](https://en.wikipedia.org/wiki/In-place_algorithm)* and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
Try it
------
Syntax
------
```
// Functionless
sort()
// Arrow function
sort((a, b) => { /\* … \*/ } )
// Compare function
sort(compareFn)
// Inline compare function
sort(function compareFn(a, b) { /\* … \*/ })
```
### Parameters
`compareFn` Optional
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
`a` The first element for comparison.
`b` The second element for comparison.
### Return value
The reference to the original array, now sorted. Note that the array is sorted *[in place](https://en.wikipedia.org/wiki/In-place_algorithm)*, and no copy is made.
Description
-----------
If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array.
The `sort()` method preserves empty slots. If the source array is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots are moved to the end of the array, and always come after all the `undefined`.
**Note:** In UTF-16, Unicode characters above `\uFFFF` are encoded as two surrogate code units, of the range `\uD800` - `\uDFFF`. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair `\uD855\uDE51` will be sorted before the character `\uFF3A`.
If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`).
| `compareFn(a, b)` return value | sort order |
| --- | --- |
| > 0 | sort `a` after `b` |
| < 0 | sort `a` before `b` |
| === 0 | keep original order of `a` and `b` |
So, the compare function has the following form:
```
function compareFn(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
```
More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior:
* *Pure*: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee *when* and *how* the comparator will be called, so any particular call should not produce visible effects to the outside.)
* *Stable*: The comparator returns the same result with the same pair of input.
* *Reflexive*: `compareFn(a, a) === 0`.
* *Anti-symmetric*: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs.
* *Transitive*: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two.
A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because *anti-symmetry* is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless.
The default lexicographic comparator satisfies all constraints above.
To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`):
```
function compareNumbers(a, b) {
return a - b;
}
```
The `sort()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Creating, displaying, and sorting an array
The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.
```
const stringArray = ["Blue", "Humpback", "Beluga"];
const numberArray = [40, 1, 5, 200];
const numericStringArray = ["80", "9", "700"];
const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];
function compareNumbers(a, b) {
return a - b;
}
stringArray.join(); // 'Blue,Humpback,Beluga'
stringArray.sort(); // ['Beluga', 'Blue', 'Humpback']
numberArray.join(); // '40,1,5,200'
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]
numericStringArray.join(); // '80,9,700'
numericStringArray.sort(); // ['700', '80', '9']
numericStringArray.sort(compareNumbers); // ['9', '80', '700']
mixedNumericArray.join(); // '80,9,700,40,1,5,200'
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']
```
### Sorting array of objects
Arrays of objects can be sorted by comparing the value of one of their properties.
```
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
// sort by value
items.sort((a, b) => a.value - b.value);
// sort by name
items.sort((a, b) => {
const nameA = a.name.toUpperCase(); // ignore upper and lowercase
const nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
```
### Sorting non-ASCII characters
For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English, use [`String.prototype.localeCompare()`](../string/localecompare). This function can compare those characters so they appear in the right order.
```
const items = ["réservé", "premier", "communiqué", "café", "adieu", "éclair"];
items.sort((a, b) => a.localeCompare(b));
// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
```
### Sorting with map
The `compareFn` can be invoked multiple times per element within the array. Depending on the `compareFn`'s nature, this may yield a high overhead. The more work a `compareFn` does and the more elements there are to sort, it may be more efficient to use [`map()`](map) for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order.
```
// the array to be sorted
const data = ["delta", "alpha", "charlie", "bravo"];
// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
return { i, value: someSlowOperation(v) };
});
// sorting the mapped array containing the reduced values
mapped.sort((a, b) => {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
return 0;
});
const result = mapped.map((v) => data[v.i]);
```
There is an open source library available called [mapsort](https://github.com/Pimm/mapsort) which applies this approach.
### sort() returns the reference to the same array
The `sort()` method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
```
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
```
In case you want `sort()` to not mutate the original array, but return a [shallow-copied](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) array like other array methods (e.g. [`map()`](map)) do, you can do a shallow copy before calling `sort()`, using the [spread syntax](../../operators/spread_syntax) or [`Array.from()`](from).
```
const numbers = [3, 1, 4, 1, 5];
// [...numbers] creates a shallow copy, so sort() does not mutate the original
const sorted = [...numbers].sort((a, b) => a - b);
sorted[0] = 10;
console.log(numbers[0]); // 3
```
### Sort stability
Since version 10 (or ECMAScript 2019), the [specification](https://tc39.es/ecma262/#sec-array.prototype.sort) dictates that `Array.prototype.sort` is stable.
For example, say you had a list of students alongside their grades. Note that the list of students is already pre-sorted by name in alphabetical order:
```
const students = [
{ name: "Alex", grade: 15 },
{ name: "Devlin", grade: 15 },
{ name: "Eagle", grade: 13 },
{ name: "Sam", grade: 14 },
];
```
After sorting this array by `grade` in ascending order:
```
students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade);
```
The `students` variable will then have the following value:
```
[
{ name: "Eagle", grade: 13 },
{ name: "Sam", grade: 14 },
{ name: "Alex", grade: 15 }, // original maintained for similar grade (stable sorting)
{ name: "Devlin", grade: 15 }, // original maintained for similar grade (stable sorting)
];
```
It's important to note that students that have the same grade (for example, Alex and Devlin), will remain in the same order as before calling the sort. This is what a stable sorting algorithm guarantees.
Before version 10 (or ECMAScript 2019), sort stability was not guaranteed, meaning that you could end up with the following:
```
[
{ name: "Eagle", grade: 13 },
{ name: "Sam", grade: 14 },
{ name: "Devlin", grade: 15 }, // original order not maintained
{ name: "Alex", grade: 15 }, // original order not maintained
];
```
### Sorting with non-well-formed comparator
If a comparing function does not satisfy all of purity, stability, reflexivity, anti-symmetry, and transitivity rules, as explained in the [description](#description), the program's behavior is not well-defined.
For example, consider this code:
```
const arr = [3, 1, 4, 1, 5, 9];
const compareFn = (a, b) => (a > b ? 1 : 0);
arr.sort(compareFn);
```
The `compareFn` function here is not well-formed, because it does not satisfy anti-symmetry: if `a > b`, it returns `1`; but by swapping `a` and `b`, it returns `0` instead of a negative value. Therefore, the resulting array will be different across engines. For example, V8 (used by Chrome, Node.js, etc.) and JavaScriptCore (used by Safari) would not sort the array at all and return `[3, 1, 4, 1, 5, 9]`, while SpiderMonkey (used by Firefox) will return the array sorted ascendingly, as `[1, 1, 3, 4, 5, 9]`.
However, if the `compareFn` function is changed slightly so that it returns `-1` or `0`:
```
const arr = [3, 1, 4, 1, 5, 9];
const compareFn = (a, b) => (a > b ? -1 : 0);
arr.sort(compareFn);
```
Then V8 and JavaScriptCore sorts it descendingly, as `[9, 5, 4, 3, 1, 1]`, while SpiderMonkey returns it as-is: `[3, 1, 4, 1, 5, 9]`.
Due to this implementation inconsistency, you are always advised to make your comparator well-formed by following the five constraints.
### Using sort() on sparse arrays
Empty slots are moved to the end of the array.
```
console.log(["a", "c", , "b"].sort()); // ['a', 'b', 'c', empty]
console.log([, undefined, "a", "b"].sort()); // ["a", "b", undefined, empty]
```
### Calling sort() on non-array objects
The `sort()` method reads the `length` property of `this`. It then collects all existing integer-keyed properties in the range of `0` to `length - 1`, sorts them, and writes them back. If there are missing properties in the range, the corresponding trailing properties are [deleted](../../operators/delete), as if the non-existent properties are sorted towards the end.
```
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
};
console.log(Array.prototype.sort.call(arrayLike));
// { '0': 4, '1': 5, length: 3, unrelated: 'foo' }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.sort](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.sort) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sort` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `stable` | 70 | 79 | 3 | No | 57 | 10.1 | 70 | 70 | 4 | 49 | 10.3 | 10.0 | 1.0 | 12.0.0 |
See also
--------
* [Polyfill of `Array.prototype.sort` with modern behavior like stable sort in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.reverse()`](reverse)
* [`String.prototype.localeCompare()`](../string/localecompare)
* [About the stability of the algorithm used by V8 engine](https://v8.dev/blog/array-sort)
* [V8 sort stability](https://v8.dev/features/stable-sort)
* [Mathias Bynens' sort stability demo](https://mathiasbynens.be/demo/sort-stability)
| programming_docs |
javascript Array.prototype.join() Array.prototype.join()
======================
The `join()` method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Try it
------
Syntax
------
```
join()
join(separator)
```
### Parameters
`separator` Optional
Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them.
### Return value
A string with all array elements joined. If `arr.length` is `0`, the empty string is returned.
Description
-----------
The string conversions of all array elements are joined into one string. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`.
The `join` method is accessed internally by [`Array.prototype.toString()`](tostring) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well.
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `join()` method iterates empty slots as if they have the value `undefined`.
The `join()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Joining an array four different ways
The following example creates an array, `a`, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
```
const a = ["Wind", "Water", "Fire"];
a.join(); // 'Wind,Water,Fire'
a.join(", "); // 'Wind, Water, Fire'
a.join(" + "); // 'Wind + Water + Fire'
a.join(""); // 'WindWaterFire'
```
### Using join() on sparse arrays
`join()` treats empty slots the same as `undefined` and produces an extra separator:
```
console.log([1, , 3].join()); // '1,,3'
console.log([1, undefined, 3].join()); // '1,,3'
```
### Calling join() on non-array objects
The `join()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.join.call(arrayLike));
// 2,3,4
console.log(Array.prototype.join.call(arrayLike, "."));
// 2.3.4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.join](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.join) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `join` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`String.prototype.split()`](../string/split)
* [`Array.prototype.toString()`](tostring)
* [`TypedArray.prototype.join()`](../typedarray/join)
javascript Array.prototype.pop() Array.prototype.pop()
=====================
The `pop()` method removes the **last** element from an array and returns that element. This method changes the length of the array.
Try it
------
Syntax
------
```
pop()
```
### Return value
The removed element from the array; [`undefined`](../undefined) if the array is empty.
Description
-----------
The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns [`undefined`](../undefined).
[`Array.prototype.shift()`](shift) has similar behavior to `pop()`, but applied to the first element in an array.
The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](slice) instead.
The `pop()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Removing the last element of an array
The following code creates the `myFish` array containing four elements, then removes its last element.
```
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const popped = myFish.pop();
console.log(myFish); // ['angel', 'clown', 'mandarin' ]
console.log(popped); // 'sturgeon'
```
### Calling pop() on non-array objects
The `pop()` method reads the `length` property of `this`. If the [normalized length](../array#normalization_of_the_length_property) is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `length - 1` is returned and [deleted](../../operators/delete).
```
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.pop.call(arrayLike));
// 4
console.log(arrayLike);
// { length: 2, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.pop.call(plainObj);
console.log(plainObj);
// { length: 0 }
```
### Using an object in an array-like fashion
`push` and `pop` are intentionally generic, and we can use that to our advantage — as the following example shows.
Note that in this example, we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use `call` on `Array.prototype.push` and `Array.prototype.pop` to trick those methods into thinking we're dealing with an array.
```
const collection = {
length: 0,
addElements(...elements) {
// obj.length will be incremented automatically
// every time an element is added.
// Returning what push returns; that is
// the new value of length property.
return [].push.call(this, ...elements);
},
removeElement() {
// obj.length will be decremented automatically
// every time an element is removed.
// Returning what pop returns; that is
// the removed element.
return [].pop.call(this);
},
};
collection.addElements(10, 20, 30);
console.log(collection.length); // 3
collection.removeElement();
console.log(collection.length); // 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.pop](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.pop) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `pop` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.push()`](push)
* [`Array.prototype.shift()`](shift)
* [`Array.prototype.unshift()`](unshift)
* [`Array.prototype.concat()`](concat)
* [`Array.prototype.splice()`](splice)
javascript Array.prototype.fill() Array.prototype.fill()
======================
The `fill()` method changes all elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). It returns the modified array.
Try it
------
Syntax
------
```
fill(value)
fill(value, start)
fill(value, start, end)
```
### Parameters
`value` Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object.
`start` Optional
Zero-based index at which to start filling, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, no index is filled.
`end` Optional
Zero-based index at which to end filling, [converted to an integer](../number#integer_conversion). `fill()` fills up to but not including `end`.
* Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used.
* If `end < -array.length`, `0` is used.
* If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled.
* If `end` is positioned before or at `start` after normalization, no index is filled.
### Return value
The modified array, filled with `value`.
Description
-----------
The `fill()` method is a [mutating method](../array#copying_methods_and_mutating_methods). It does not alter the length of `this`, but it will change the content of `this`.
The `fill()` method fills empty slots in [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) arrays with `value` as well.
The `fill()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
**Note:** Using `Array.prototype.fill()` on an empty array (`length = 0`) would not modify it as the array has nothing to be modified. To use `Array.prototype.fill()` when declaring an array, make sure the array has non-zero `length`. [See example](#using_fill_to_populate_an_empty_array).
Examples
--------
### Using fill
```
console.log([1, 2, 3].fill(4)); // [4, 4, 4]
console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]
console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]
console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]
console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]
console.log(Array(3).fill(4)); // [4, 4, 4]
// A single object, referenced by each slot of the array:
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
```
### Using fill() to create a matrix of all 1
This example shows how to create a matrix of all 1, like the `ones()` function of Octave or MATLAB.
```
const arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(4).fill(1); // Creating an array of size 4 and filled of 1
}
arr[0][0] = 10;
console.log(arr[0][0]); // 10
console.log(arr[1][0]); // 1
console.log(arr[2][0]); // 1
```
### Using fill() to populate an empty array
This example shows how to populate an array, setting all elements to a specific value. The `end` parameter does not have to be specified.
```
const tempGirls = Array(5).fill("girl", 0);
```
Note that the array was initially a [sparse array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) with no assigned indices. `fill()` is still able to fill this array.
### Calling fill() on non-array objects
The `fill()` method reads the `length` property of `this` and sets the value of each integer property from `start` to `end`.
```
const arrayLike = { length: 2 };
console.log(Array.prototype.fill.call(arrayLike, 1));
// { '0': 1, '1': 1, length: 2 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.fill](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.fill) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fill` | 45 | 12 | 31 | No | 32 | 8 | 45 | 45 | 31 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `Array.prototype.fill` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array`](../array)
* [`TypedArray.prototype.fill()`](../typedarray/fill)
javascript Array.prototype.map() Array.prototype.map()
=====================
The `map()` method **creates a new array** populated with the results of calling a provided function on every element in the calling array.
Try it
------
Syntax
------
```
// Arrow function
map((element) => { /\* … \*/ })
map((element, index) => { /\* … \*/ })
map((element, index, array) => { /\* … \*/ })
// Callback function
map(callbackFn)
map(callbackFn, thisArg)
// Inline callback function
map(function (element) { /\* … \*/ })
map(function (element, index) { /\* … \*/ })
map(function (element, index, array) { /\* … \*/ })
map(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. Its return value is added as a single element in the new array.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `map()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
A new array with each element being the result of the callback function.
Description
-----------
The `map()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `map()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this`. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `map()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `map()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use [`forEach`](foreach) or [`for...of`](../../statements/for...of) instead.
Examples
--------
### Mapping an array of numbers to an array of square roots
The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
```
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
```
### Using map to reformat objects in an array
The following code takes an array of objects and creates a new array containing the newly reformatted objects.
```
const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
];
const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));
console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
// { key: 1, value: 10 },
// { key: 2, value: 20 },
// { key: 3, value: 30 }
// ]
```
### Mapping an array of numbers using a function containing an argument
The following code shows how `map` works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as `map` loops through the original array.
```
const numbers = [1, 4, 9];
const doubles = numbers.map((num) => num \* 2);
console.log(doubles); // [2, 8, 18]
console.log(numbers); // [1, 4, 9]
```
### Calling map() on non-array objects
The `map()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.map.call(arrayLike, (x) => x \*\* 2));
// [ 4, 9, 16 ]
```
### Using map() generically on a NodeList
This example shows how to iterate through a collection of objects collected by `querySelectorAll`. This is because `querySelectorAll` returns a `NodeList` (which is a collection of objects).
In this case, we return all the selected `option`s' values on the screen:
```
const elems = document.querySelectorAll("select option:checked");
const values = Array.prototype.map.call(elems, ({ value }) => value);
```
An easier way would be the [`Array.from()`](from) method.
### Using map() on sparse arrays
A sparse array remains sparse after `map()`. The indices of empty slots are still empty in the returned array, and the callback function won't be called on them.
```
console.log(
[1, , 3].map((x, index) => {
console.log(`Visit ${index}`);
return x \* 2;
}),
);
// Visit 0
// Visit 2
// [2, empty, 6]
```
### Using parseInt() with map()
([inspired by this blog post](https://wirfs-brock.com/allen/posts/166))
It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.
Consider:
```
["1", "2", "3"].map(parseInt);
```
While one might expect `[1, 2, 3]`, the actual result is `[1, NaN, NaN]`.
[`parseInt`](../parseint) is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, `Array.prototype.map` passes 3 arguments:
* the element
* the index
* the array
The third argument is ignored by [`parseInt`](../parseint)—but *not* the second one! This is the source of possible confusion.
Here is a concise example of the iteration steps:
```
// parseInt(string, radix) -> map(parseInt(value, index))
/\* first iteration (index is 0): \*/ parseInt("1", 0); // 1
/\* second iteration (index is 1): \*/ parseInt("2", 1); // NaN
/\* third iteration (index is 2): \*/ parseInt("3", 2); // NaN
```
Then let's talk about solutions.
```
const returnInt = (element) => parseInt(element, 10);
["1", "2", "3"].map(returnInt); // [1, 2, 3]
// Actual result is an array of numbers (as expected)
// Same as above, but using the concise arrow function syntax
["1", "2", "3"].map((str) => parseInt(str)); // [1, 2, 3]
// A simpler way to achieve the above, while avoiding the "gotcha":
["1", "2", "3"].map(Number); // [1, 2, 3]
// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300]
// For comparison, if we use parseInt() on the array above:
["1.1", "2.2e2", "3e300"].map((str) => parseInt(str)); // [1, 2, 3]
```
One alternative output of the map method being called with [`parseInt`](../parseint) as a parameter runs as follows:
```
const strings = ["10", "10", "10"];
const numbers = strings.map(parseInt);
console.log(numbers);
// Actual result of [10, NaN, 2] may be unexpected based on the above description.
```
### Mapped array contains undefined
When [`undefined`](../undefined) or nothing is returned:
```
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
if (index < 3) {
return num;
}
});
// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.map](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.map) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `map` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.map` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.forEach()`](foreach)
* [`Map`](../map) object
* [`Array.from()`](from)
| programming_docs |
javascript Array.prototype.toLocaleString() Array.prototype.toLocaleString()
================================
The `toLocaleString()` method returns a string representing the elements of the array. The elements are converted to Strings using their `toLocaleString` methods and these Strings are separated by a locale-specific String (such as a comma ",").
Try it
------
Syntax
------
```
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```
### Parameters
`locales` Optional
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [Locale identification and negotiation](../intl#locale_identification_and_negotiation).
`options` Optional
An object with configuration properties. For numbers, see [`Number.prototype.toLocaleString()`](../number/tolocalestring); for dates, see [`Date.prototype.toLocaleString()`](../date/tolocalestring).
### Return value
A string representing the elements of the array.
Description
-----------
The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters — it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter.
If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`.
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `toLocaleString()` method iterates empty slots as if they have the value `undefined`.
The `toLocaleString()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using locales and options
The elements of the array are converted to strings using their `toLocaleString` methods.
* `Object`: [`Object.prototype.toLocaleString()`](../object/tolocalestring)
* `Number`: [`Number.prototype.toLocaleString()`](../number/tolocalestring)
* `Date`: [`Date.prototype.toLocaleString()`](../date/tolocalestring)
Always display the currency for the strings and numbers in the `prices` array:
```
const prices = ["¥7", 500, 8123, 12];
prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });
// "¥7,¥500,¥8,123,¥12"
```
For more examples, see also the [`Intl.NumberFormat`](../intl/numberformat) and [`Intl.DateTimeFormat`](../intl/datetimeformat) pages.
### Using toLocaleString() on sparse arrays
`toLocaleString()` treats empty slots the same as `undefined` and produces an extra separator:
```
console.log([1, , 3].toLocaleString()); // '1,,3'
```
### Calling toLocaleString() on non-array objects
The `toLocaleString()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 1,
1: 2,
2: 3,
};
console.log(Array.prototype.toLocaleString.call(arrayLike));
// 1,2,3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.tolocalestring](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.tolocalestring) |
| [ECMAScript Internationalization API Specification # sup-array.prototype.tolocalestring](https://tc39.es/ecma402/#sup-array.prototype.tolocalestring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleString` | 1 | 12 | 1 | 5.5 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
| `locales_parameter` | 24 | 79 | 52 | No | 15 | 7 | 4.4 | 25 | 56 | 14 | 7 | 2.0 | 1.8
1.0-1.8
Only the locale data for `en-US` is available. | 13.0.0
0.12.0
Before version 13.0.0, only the locale data for `en-US` is available by default. When other locales are specified, the function silently falls back to `en-US`. To make full ICU (locale) data available before version 13, see [Node.js documentation on the `--with-intl` option](https://nodejs.org/docs/latest/api/intl.html#intl_options_for_building_node_js) and how to provide the data. |
| `options_parameter` | 24 | 79 | 52 | No | 15 | 7 | 4.4 | 25 | 56 | 14 | 7 | 2.0 | 1.0 | 0.12.0 |
See also
--------
* [`Array.prototype.toString()`](tostring)
* [`Intl`](../intl)
* [`Object.prototype.toLocaleString()`](../object/tolocalestring)
* [`Number.prototype.toLocaleString()`](../number/tolocalestring)
* [`Date.prototype.toLocaleString()`](../date/tolocalestring)
javascript Array.prototype.values() Array.prototype.values()
========================
The `values()` method returns a new *array [iterator](../../iteration_protocols#the_iterator_protocol)* object that iterates the value of each index in the array.
Try it
------
Syntax
------
```
values()
```
### Return value
A new iterable iterator object.
Description
-----------
`Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](@@iterator).
```
Array.prototype.values === Array.prototype[Symbol.iterator]; // true
```
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `values()` method iterates empty slots as if they have the value `undefined`.
The `values()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Iteration using for...of loop
Because `values()` returns an iterable iterator, you can use a [`for...of`](../../statements/for...of) loop to iterate it.
```
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
for (const letter of iterator) {
console.log(letter);
} // "a" "b" "c" "d" "e"
```
### Iteration using next()
Because the return value is also an iterator, you can directly call its `next()` method.
```
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
iterator.next(); // { value: "a", done: false }
iterator.next(); // { value: "b", done: false }
iterator.next(); // { value: "c", done: false }
iterator.next(); // { value: "d", done: false }
iterator.next(); // { value: "e", done: false }
iterator.next(); // { value: undefined, done: true }
console.log(iterator.next().value); // undefined
```
### Reusing the iterable
**Warning:** The array iterator object should be a one-time use object. Do not reuse it.
The iterable returned from `values()` is not reusable. When `next().done = true` or `currentIndex > length`, [the `for...of` loop ends](../../iteration_protocols#interactions_between_the_language_and_iteration_protocols), and further iterating it has no effect.
```
const arr = ["a", "b", "c", "d", "e"];
const values = arr.values();
for (const letter of values) {
console.log(letter);
}
// "a" "b" "c" "d" "e"
for (const letter of values) {
console.log(letter);
}
// undefined
```
If you use a [`break`](../../statements/break) statement to end the iteration early, the iterator can resume from the current position when continuing to iterate it.
```
const arr = ["a", "b", "c", "d", "e"];
const values = arr.values();
for (const letter of values) {
console.log(letter);
if (letter === "b") {
break;
}
}
// "a" "b"
for (const letter of values) {
console.log(letter);
}
// "c" "d" "e"
```
### Mutations during iteration
There are no values stored in the array iterator object returned from `values()`; instead, it stores the address of the array used in its creation, and reads the currently visited index on each iteration. Therefore, its iteration output depends on the value stored in that index at the time of stepping. If the values in the array changed, the array iterator object's values change too.
```
const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
console.log(iterator); // Array Iterator { }
console.log(iterator.next().value); // "a"
arr[1] = "n";
console.log(iterator.next().value); // "n"
```
### Iterating sparse arrays
`values()` will visit empty slots as if they are `undefined`.
```
for (const element of [, "a"].values()) {
console.log(element);
}
// undefined
// 'a'
```
### Calling values() on non-array objects
The `values()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
};
for (const entry of Array.prototype.values.call(arrayLike)) {
console.log(entry);
}
// a
// b
// c
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.values](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.values) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `values` | 66 | 14 | 60 | No | 53 | 9 | 66 | 66 | 60 | 47 | 9 | 9.0 | 1.0 | 10.9.0
6.5.0
The `--harmony-array-prototype-values` flag is required; the `--harmony` flag is not sufficient in this case.
0.12.0-4.0.0 |
See also
--------
* [Polyfill of `Array.prototype.values` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.keys()`](keys)
* [`Array.prototype.entries()`](entries)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.every()`](every)
* [`Array.prototype.some()`](some)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
javascript Array.prototype.lastIndexOf() Array.prototype.lastIndexOf()
=============================
The `lastIndexOf()` method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`.
Try it
------
Syntax
------
```
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
```
### Parameters
`searchElement` Element to locate in the array.
`fromIndex` Optional
Zero-based index at which to start searching backwards, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used.
* If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found.
* If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.
### Return value
The last index of the element in the array; **-1** if not found.
Description
-----------
The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](../../operators/strict_equality) (the same algorithm used by the `===` operator).
The `lastIndexOf()` method skips empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `lastIndexOf()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using lastIndexOf()
The following example uses `lastIndexOf` to locate values in an array.
```
const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1
numbers.lastIndexOf(2, 3); // 3
numbers.lastIndexOf(2, 2); // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3
```
### Finding all the occurrences of an element
The following example uses `lastIndexOf` to find all the indices of an element in a given array, using [`push`](push) to add them to another array as they are found.
```
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.lastIndexOf(element);
while (idx !== -1) {
indices.push(idx);
idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
}
console.log(indices);
// [4, 2, 0]
```
Note that we have to handle the case `idx === 0` separately here because the element will always be found regardless of the `fromIndex` parameter if it is the first element of the array. This is different from the [`indexOf`](indexof) method.
### Using lastIndexOf() on sparse arrays
You cannot use `lastIndexOf()` to search for empty slots in sparse arrays.
```
console.log([1, , 3].lastIndexOf(undefined)); // -1
```
### Calling lastIndexOf() on non-array objects
The `lastIndexOf()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 2,
};
console.log(Array.prototype.lastIndexOf.call(arrayLike, 2));
// 2
console.log(Array.prototype.lastIndexOf.call(arrayLike, 5));
// -1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.lastindexof](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.lastindexof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `lastIndexOf` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.lastIndexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.indexOf()`](indexof)
* [`TypedArray.prototype.lastIndexOf()`](../typedarray/lastindexof)
javascript Array.prototype.findIndex() Array.prototype.findIndex()
===========================
The `findIndex()` method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
Try it
------
See also the [`find()`](find) method, which returns the first element that satisfies the testing function (rather than its index).
Syntax
------
```
// Arrow function
findIndex((element) => { /\* … \*/ })
findIndex((element, index) => { /\* … \*/ })
findIndex((element, index, array) => { /\* … \*/ })
// Callback function
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
// Inline callback function
findIndex(function (element) { /\* … \*/ })
findIndex(function (element, index) { /\* … \*/ })
findIndex(function (element, index, array) { /\* … \*/ })
findIndex(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `findIndex()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
The index of the first element in the array that passes the test. Otherwise, `-1`.
Description
-----------
The `findIndex()` is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`.
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
`findIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findIndex()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `findIndex()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Find the index of a prime number in an array
The following example returns the index of the first element in the array that is a prime number, or `-1` if there is no prime number.
```
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)
```
### Using findIndex() on sparse arrays
You can search for `undefined` in a sparse array and get the index of an empty slot.
```
console.log([1, , 3].findIndex((x) => x === undefined)); // 1
```
### Calling findIndex() on non-array objects
The `findIndex()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
};
console.log(
Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),
); // 1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.findindex](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.findindex) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findIndex` | 45 | 12 | 25 | No | 32 | 8 | 45 | 45 | 4 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `Array.prototype.findIndex` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.find()`](find)
* [`Array.prototype.indexOf()`](indexof)
| programming_docs |
javascript Array.prototype.groupToMap() Array.prototype.groupToMap()
============================
**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.
The `groupToMap()` method groups the elements of the calling array using the values returned by a provided testing function. The final returned [`Map`](../map) uses the unique values from the test function as keys, which can be used to get the array of elements in each group.
The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with [`Array.prototype.group()`](group).
Syntax
------
```
// Arrow function
groupToMap((element) => { /\* … \*/ })
groupToMap((element, index) => { /\* … \*/ })
groupToMap((element, index, array) => { /\* … \*/ })
// Callback function
groupToMap(callbackFn)
groupToMap(callbackFn, thisArg)
// Inline callback function
groupToMap(function (element) { /\* … \*/ })
groupToMap(function (element, index) { /\* … \*/ })
groupToMap(function (element, index, array) { /\* … \*/ })
groupToMap(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a value ([object](https://developer.mozilla.org/en-US/docs/Glossary/Object) or [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)) indicating the group of the current element.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `groupToMap()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
A [`Map`](../map) object with keys for each group, each assigned to an array containing the elements of the associated group.
### Exceptions
`TypeError` The specified callback function is not callable.
Description
-----------
The `groupToMap()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array. The callback function returns a value indicating the group of the associated element. The values returned by `callbackFn` are used as keys for the [`Map`](../map) returned by `groupToMap()`. Each key has an associated array containing all the elements for which the callback returned the same value.
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
The `groupToMap()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a map of arrays that contains the same elements as the ones from the original array. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `groupToMap()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The elements in the returned [`Map`](../map) and the original array are the same (not [deep copies](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy)). Changing the internal structure of the elements will be reflected in both the original array and the returned [`Map`](../map).
The `groupToMap()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
This method is useful when you need to group information that is related to a particular object that might potentially change over time. This is because even if the object is modified, it will continue to work as a key to the returned `Map`. If you instead create a string representation for the object and use that as a grouping key in [`Array.prototype.group()`](group), you must maintain the mapping between the original object and its representation as the object changes.
**Note:** To access the groups in the returned `Map`, you must use the same object that was originally used as a key in the `Map` (although you may modify its properties). You can't use another object that just happens to have the same name and properties.
Examples
--------
### Using groupToMap()
First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.
```
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];
```
The code below uses `groupToMap()` with an arrow function that returns the object keys named `restock` or `sufficient`, depending on whether the element has `quantity < 6`. The returned `result` object is a `Map` so we need to call `get()` with the key to obtain the array.
```
const restock = { restock: true };
const sufficient = { restock: false };
const result = inventory.groupToMap(({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
```
Note that the function argument `{ quantity }` is a basic example of [object destructuring syntax for function arguments](../../operators/destructuring_assignment#unpacking_properties_from_objects_passed_as_a_function_parameter). This unpacks the `quantity` property of an object passed as a parameter, and assigns it to a variable named `quantity` in the body of the function. This is a very succinct way to access the relevant values of elements within a function.
The key to a `Map` can be modified and still used. However you can't recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.
```
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined
```
### Using groupToMap() on sparse arrays
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `groupToMap()` method iterates empty slots as if they have the value `undefined`.
```
console.log([1, , 3].groupToMap((x) => x));
// Map { 1 => [1], undefined => [undefined], 3 => [3] }
```
### Calling groupToMap() on non-array objects
The `groupToMap()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.groupToMap.call(arrayLike, (x) => x % 2));
// Map { 0 => [2, 4], 1 => [3] }
```
Specifications
--------------
| Specification |
| --- |
| [Array Grouping # sec-array.prototype.grouptomap](https://tc39.es/proposal-array-grouping/#sec-array.prototype.grouptomap) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `groupToMap` | No | No | 98 | No | No | No | No | No | No | No | No | No | No | No |
See also
--------
* [`Array.prototype.group()`](group)
* [Polyfill of `Array.prototype.group` in `core-js`](https://github.com/zloirock/core-js#array-grouping)
javascript Array.prototype.group() Array.prototype.group()
=======================
**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.
The `group()` method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group.
This method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use [`Array.prototype.groupToMap()`](grouptomap) instead.
Syntax
------
```
// Arrow function
group((element) => { /\* … \*/ })
group((element, index) => { /\* … \*/ })
group((element, index, array) => { /\* … \*/ })
// Callback function
group(callbackFn)
group(callbackFn, thisArg)
// Inline callback function
group(function (element) { /\* … \*/ })
group(function (element, index) { /\* … \*/ })
group(function (element, index, array) { /\* … \*/ })
group(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a value that can get coerced into a property key (string or [symbol](../symbol)) indicating the group of the current element.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `group()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
A [`null`-prototype object](../object#null-prototype_objects) with properties for all groups, each assigned to an array containing the elements of the associated group.
### Exceptions
`TypeError` The specified callback function is not callable.
Description
-----------
The `group()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, returning a string or symbol (values that are neither type are [coerced to strings](../string#string_coercion)) indicating the group of the element. A new property and array is created in the result object for each unique group name that is returned by the callback. Each element is added to the array in the property that corresponds to its group.
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
The `group()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns an object of arrays that contains the same elements as the ones from the original array. However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `group()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The returned object references the *same* elements as the original array (not [deep copies](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy)). Changing the internal structure of these elements will be reflected in both the original array and the returned object.
The `group()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using group()
First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.
```
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
```
The code below groups the elements by the value of their `type` property.
```
const result = inventory.group(({ type }) => type);
/\* Result is:
{
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
meat: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
\*/
```
The arrow function just returns the `type` of each array element each time it is called. Note that the function argument `{ type }` is a basic example of [object destructuring syntax for function arguments](../../operators/destructuring_assignment#unpacking_properties_from_objects_passed_as_a_function_parameter). This unpacks the `type` property of an object passed as a parameter, and assigns it to a variable named `type` in the body of the function. This is a very succinct way to access the relevant values of elements within a function.
We can also create groups inferred from values in one or more properties of the elements. Below is a very similar example that puts the items into `ok` or `restock` groups based on the value of the `quantity` field.
```
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = inventory.group(myCallback);
/\* Result is:
{
restock: [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
ok: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
\*/
```
### Using group() on sparse arrays
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `group()` method iterates empty slots as if they have the value `undefined`.
```
console.log([1, , 3].group((x) => x)); // { 1: [1], undefined: [undefined], 3: [3] }
```
### Calling group() on non-array objects
The `group()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.group.call(arrayLike, (x) => x % 2));
// { 0: [2, 4], 1: [3] }
```
Specifications
--------------
| Specification |
| --- |
| [Array Grouping # sec-array.prototype.group](https://tc39.es/proposal-array-grouping/#sec-array.prototype.group) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `group` | No | No | 98 | No | No | No | No | No | No | No | No | No | No | No |
See also
--------
* [`Array.prototype.groupToMap()`](grouptomap) – Group an array into a map, using any kind of object as a key or value.
* [Polyfill of `Array.prototype.group` in `core-js`](https://github.com/zloirock/core-js#array-grouping)
javascript Array.prototype.copyWithin() Array.prototype.copyWithin()
============================
The `copyWithin()` method shallow copies part of an array to another location in the same array and returns it without modifying its length.
Try it
------
Syntax
------
```
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
```
### Parameters
`target` Zero-based index at which to copy the sequence to, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `target < 0`, `target + array.length` is used.
* If `target < -array.length`, `0` is used.
* If `target >= array.length`, nothing is copied.
* If `target` is positioned after `start` after normalization, copying only happens until the end of `array.length` (in other words, `copyWithin()` never extends the array).
`start` Optional
Zero-based index at which to start copying elements from, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, nothing is copied.
`end` Optional
Zero-based index at which to end copying elements from, [converted to an integer](../number#integer_conversion). `copyWithin()` copies up to but not including `end`.
* Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used.
* If `end < -array.length`, `0` is used.
* If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be copied.
* If `end` is positioned before or at `start` after normalization, nothing is copied.
### Return value
The modified array.
Description
-----------
The `copyWithin()` method works like C and C++'s `memmove`, and is a high-performance method to shift the data of an [`Array`](../array). This especially applies to the [`TypedArray`](../typedarray/copywithin) method of the same name. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap.
The `copyWithin()` method is a [mutating method](../array#copying_methods_and_mutating_methods). It does not alter the length of `this`, but it will change the content of `this` and create new properties or delete existing properties, if necessary.
The `copyWithin()` method preserves empty slots. If the region to be copied from is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots' corresponding new indices are [deleted](../../operators/delete) and also become empty slots.
The `copyWithin()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Using copyWithin()
```
console.log([1, 2, 3, 4, 5].copyWithin(-2));
// [1, 2, 3, 1, 2]
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
// [4, 5, 3, 4, 5]
console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
// [4, 2, 3, 4, 5]
console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
// [1, 2, 3, 3, 4]
```
### Using copyWithin() on sparse arrays
`copyWithin()` will propagate empty slots.
```
console.log([1, , 3].copyWithin(2, 1, 2)); // [1, empty, empty]
```
### Calling copyWithin() on non-array objects
The `copyWithin()` method reads the `length` property of `this` and then manipulates the integer indices involved.
```
const arrayLike = {
length: 5,
3: 1,
};
console.log(Array.prototype.copyWithin.call(arrayLike, 0, 3));
// { '0': 1, '3': 1, length: 5 }
console.log(Array.prototype.copyWithin.call(arrayLike, 3, 1));
// { '0': 1, length: 5 }
// The '3' property is deleted because the copied source is an empty slot
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.copywithin](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.copywithin) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `copyWithin` | 45 | 12 | 32 | No | 32 | 9 | 45 | 45 | 32 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `Array.prototype.copyWithin` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
* [`Array`](../array)
| programming_docs |
javascript Array.prototype.at() Array.prototype.at()
====================
The `at()` method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
Try it
------
Syntax
------
```
at(index)
```
### Parameters
`index` Zero-based index of the array element to be returned, [converted to an integer](../number#integer_conversion). Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed.
### Return value
The element in the array matching the given index. Always returns [`undefined`](../undefined) if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property.
Description
-----------
The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index.
The usual practice is to access [`length`](length) and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`.
The `at()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Return the last value of an array
The following example provides a function which returns the last element found in a specified array.
```
// Our array with items
const cart = ["apple", "banana", "pear"];
// A function which returns the last item of a given array
function returnLast(arr) {
return arr.at(-1);
}
// Get the last item of our array 'cart'
const item1 = returnLast(cart);
console.log(item1); // 'pear'
// Add an item to our 'cart' array
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // 'orange'
```
### Comparing methods
This example compares different ways to select the penultimate (last but one) item of an [`Array`](../array). While all the methods shown below are valid, this example highlights the succinctness and readability of the `at()` method.
```
// Our array with items
const colors = ["red", "green", "blue"];
// Using length property
const lengthWay = colors[colors.length - 2];
console.log(lengthWay); // 'green'
// Using slice() method. Note an array is returned
const sliceWay = colors.slice(-2, -1);
console.log(sliceWay[0]); // 'green'
// Using at() method
const atWay = colors.at(-2);
console.log(atWay); // 'green'
```
### Calling at() on non-array objects
The `at()` method reads the `length` property of `this` and calculates the index to access.
```
const arrayLike = {
length: 2,
0: "a",
1: "b",
};
console.log(Array.prototype.at.call(arrayLike, -1)); // "b"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.at](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.at) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `at` | 92 | 92 | 90 | No | 78 | 15.4 | 92 | 92 | 90 | 65 | 15.4 | 16.0 | 1.12 | 16.6.0 |
See also
--------
* [Polyfill of `Array.prototype.at` in `core-js`](https://github.com/zloirock/core-js#relative-indexing-method)
* [A polyfill for the at() method](https://github.com/tc39/proposal-relative-indexing-method#polyfill).
* [`Array.prototype.find()`](find) – return a value based on a given test.
* [`Array.prototype.includes()`](includes) – test whether a value exists in the array.
* [`Array.prototype.indexOf()`](indexof) – return the index of a given element.
javascript Array.prototype.reduceRight() Array.prototype.reduceRight()
=============================
The `reduceRight()` method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
Try it
------
See also [`Array.prototype.reduce()`](reduce) for left-to-right.
Syntax
------
```
// Arrow function
reduceRight((accumulator, currentValue) => { /\* … \*/ })
reduceRight((accumulator, currentValue, index) => { /\* … \*/ })
reduceRight((accumulator, currentValue, index, array) => { /\* … \*/ })
reduceRight((accumulator, currentValue, index, array) => { /\* … \*/ }, initialValue)
// Callback function
reduceRight(callbackFn)
reduceRight(callbackFn, initialValue)
// Callback reducer function
reduceRight(function (accumulator, currentValue) { /\* … \*/ })
reduceRight(function (accumulator, currentValue, index) { /\* … \*/ })
reduceRight(function (accumulator, currentValue, index, array) { /\* … \*/ })
reduceRight(function (accumulator, currentValue, index, array) { /\* … \*/ }, initialValue)
```
### Parameters
`callbackFn` A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`.
The function is called with the following arguments:
`accumulator` The value previously returned in the last invocation of the callback, or `initialValue`, if supplied. (See below.)
`currentValue` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `reduceRight()` was called upon.
`initialValue` Optional
Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a `TypeError`.
### Return value
The value that results from the reduction.
Description
-----------
The `reduceRight()` method is an [iterative method](../array#iterative_methods). It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
Unlike other [iterative methods](../array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict.
`reduceRight()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduceRight()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `reduceRight()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### How reduceRight() works without an initial value
The call to the reduceRight `callbackFn` would look something like this:
```
arr.reduceRight((accumulator, currentValue, index, array) => {
// …
});
```
The first time the function is called, the `accumulator` and `currentValue` can be one of two values. If an `initialValue` was provided in the call to `reduceRight`, then `accumulator` will be equal to `initialValue` and `currentValue` will be equal to the last value in the array. If no `initialValue` was provided, then `accumulator` will be equal to the last value in the array and `currentValue` will be equal to the second-to-last value.
If the array is empty and no `initialValue` was provided, [`TypeError`](../typeerror) would be thrown. If the array has only one element (regardless of position) and no `initialValue` was provided, or if `initialValue` is provided but the array is empty, the solo value would be returned without calling `callbackFn`.
Some example run-throughs of the function would look like this:
```
[0, 1, 2, 3, 4].reduceRight(
(accumulator, currentValue, index, array) => accumulator + currentValue,
);
```
The callback would be invoked four times, with the arguments and return values in each call being as follows:
| | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `4` | `3` | `3` | `7` |
| Second call | `7` | `2` | `2` | `9` |
| Third call | `9` | `1` | `1` | `10` |
| Fourth call | `10` | `0` | `0` | `10` |
The `array` parameter never changes through the process — it's always `[0, 1, 2, 3, 4]`. The value returned by `reduceRight` would be that of the last callback invocation (`10`).
### How reduceRight() works with an initial value
Here we reduce the same array using the same algorithm, but with an `initialValue` of `10` passed as the second argument to `reduceRight()`:
```
[0, 1, 2, 3, 4].reduceRight(
(accumulator, currentValue, index, array) => accumulator + currentValue,
10,
);
```
| | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `10` | `4` | `4` | `14` |
| Second call | `14` | `3` | `3` | `17` |
| Third call | `17` | `2` | `2` | `19` |
| Fourth call | `19` | `1` | `1` | `20` |
| Fifth call | `20` | `0` | `0` | `20` |
The value returned by `reduceRight` this time would be, of course, `20`.
### Sum up all values within an array
```
const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b);
// sum is 6
```
### Flatten an array of arrays
```
const arrays = [
[0, 1],
[2, 3],
[4, 5],
];
const flattened = arrays.reduceRight((a, b) => a.concat(b), []);
// flattened is [4, 5, 2, 3, 0, 1]
```
### Run a list of asynchronous functions with callbacks in series each passing their results to the next
```
const waterfall =
(...functions) =>
(callback, ...args) =>
functions.reduceRight(
(composition, fn) =>
(...results) =>
fn(composition, ...results),
callback,
)(...args);
const randInt = (max) => Math.floor(Math.random() \* max);
const add5 = (callback, x) => {
setTimeout(callback, randInt(1000), x + 5);
};
const mult3 = (callback, x) => {
setTimeout(callback, randInt(1000), x \* 3);
};
const sub2 = (callback, x) => {
setTimeout(callback, randInt(1000), x - 2);
};
const split = (callback, x) => {
setTimeout(callback, randInt(1000), x, x);
};
const add = (callback, x, y) => {
setTimeout(callback, randInt(1000), x + y);
};
const div4 = (callback, x) => {
setTimeout(callback, randInt(1000), x / 4);
};
const computation = waterfall(add5, mult3, sub2, split, add, div4);
computation(console.log, 5); // Logs 14
// same as:
const computation2 = (input, callback) => {
const f6 = (x) => div4(callback, x);
const f5 = (x, y) => add(f6, x, y);
const f4 = (x) => split(f5, x);
const f3 = (x) => sub2(f4, x);
const f2 = (x) => mult3(f3, x);
add5(f2, input);
};
```
### Difference between reduce and reduceRight
```
const a = ["1", "2", "3", "4", "5"];
const left = a.reduce((prev, cur) => prev + cur);
const right = a.reduceRight((prev, cur) => prev + cur);
console.log(left); // "12345"
console.log(right); // "54321"
```
### Defining composable functions
Function composition is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. In this example we use `reduceRight()` to implement function composition.
See also [Function composition](https://en.wikipedia.org/wiki/Function_composition_(computer_science)) on Wikipedia.
```
const compose =
(...args) =>
(value) =>
args.reduceRight((acc, fn) => fn(acc), value);
// Increment passed number
const inc = (n) => n + 1;
// Doubles the passed value
const double = (n) => n \* 2;
// using composition function
console.log(compose(double, inc)(2)); // 6
// using composition function
console.log(compose(inc, double)(2)); // 5
```
### Using reduceRight() with sparse arrays
`reduceRight()` skips missing elements in sparse arrays, but it does not skip `undefined` values.
```
console.log([1, 2, , 4].reduceRight((a, b) => a + b)); // 7
console.log([1, 2, undefined, 4].reduceRight((a, b) => a + b)); // NaN
```
### Calling reduceRight() on non-array objects
The `reduceRight()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.reduceRight.call(arrayLike, (x, y) => x - y));
// -1, which is 4 - 3 - 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.reduceright](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.reduceright) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reduceRight` | 3 | 12 | 3 | 9 | 10.5 | 4 | ≤37 | 18 | 4 | 14 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.reduceRight` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.reduce()`](reduce)
javascript Array.prototype.reverse() Array.prototype.reverse()
=========================
The `reverse()` method reverses an array *[in place](https://en.wikipedia.org/wiki/In-place_algorithm)* and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
Try it
------
Syntax
------
```
reverse()
```
### Return value
The reference to the original array, now reversed. Note that the array is reversed *[in place](https://en.wikipedia.org/wiki/In-place_algorithm)*, and no copy is made.
Description
-----------
The `reverse()` method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
The `reverse()` method preserves empty slots. If the source array is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots' corresponding new indices are [deleted](../../operators/delete) and also become empty slots.
The `reverse()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Reversing the elements in an array
The following example creates an array `items`, containing three elements, then reverses the array. The call to `reverse()` returns a reference to the reversed array `items`.
```
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
items.reverse();
console.log(items); // [3, 2, 1]
```
### The reverse() method returns the reference to the same array
The `reverse()` method returns reference to the original array, so mutating the returned array will mutate the original array as well.
```
const numbers = [3, 2, 4, 1, 5];
const reversed = numbers.reverse();
// numbers and reversed are both in reversed order [5, 1, 4, 2, 3]
reversed[0] = 5;
console.log(numbers[0]); // 5
```
In case you want `reverse()` to not mutate the original array, but return a [shallow-copied](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) array like other array methods (e.g. [`map()`](map)) do, you can do a shallow copy before calling `reverse()`, using the [spread syntax](../../operators/spread_syntax) or [`Array.from()`](from).
```
const numbers = [3, 2, 4, 1, 5];
// [...numbers] creates a shallow copy, so reverse() does not mutate the original
const reverted = [...numbers].reverse();
reverted[0] = 5;
console.log(numbers[0]); // 3
```
### Using reverse() on sparse arrays
Sparse arrays remain sparse after calling `reverse()`. Empty slots are copied over to their respective new indices as empty slots.
```
console.log([1, , 3].reverse()); // [3, empty, 1]
console.log([1, , 3, 4].reverse()); // [4, 3, empty, 1]
```
### Calling reverse() on non-array objects
The `reverse()` method reads the `length` property of `this`. It then visits each index between `0` and `length / 2`, and swaps the two corresponding indices on both ends, [deleting](../../operators/delete) properties if needed.
```
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.reverse.call(arrayLike));
// { '0': 4, length: 3, unrelated: 'foo' }
// The '2' index is deleted because the '0' index was not present originally
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.reverse](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.reverse) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reverse` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.join()`](join)
* [`Array.prototype.sort()`](sort)
* [`TypedArray.prototype.reverse()`](../typedarray/reverse)
javascript Array.prototype.findLastIndex() Array.prototype.findLastIndex()
===============================
The `findLastIndex()` method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
Try it
------
See also the [`findLast()`](findlast) method, which returns the value of last element that satisfies the testing function (rather than its index).
Syntax
------
```
// Arrow function
findLastIndex((element) => { /\* … \*/ })
findLastIndex((element, index) => { /\* … \*/ })
findLastIndex((element, index, array) => { /\* … \*/ })
// Callback function
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
// Inline callback function
findLastIndex(function (element) { /\* … \*/ })
findLastIndex(function (element, index) { /\* … \*/ })
findLastIndex(function (element, index, array) { /\* … \*/ })
findLastIndex(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `findLastIndex()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
The index of the last (highest-index) element in the array that passes the test. Otherwise -1 if no matching element is found.
Description
-----------
The `findLastIndex()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `findLastIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLastIndex()` returns `-1`.
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
`findLastIndex()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findLastIndex()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `findLastIndex()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Find the index of the last prime number in an array
The following example returns the index of the last element in the array that is a prime number, or `-1` if there is no prime number.
```
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5
```
### Using findLastIndex() on sparse arrays
You can search for `undefined` in a sparse array and get the index of an empty slot.
```
console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1
```
### Calling findLastIndex() on non-array objects
The `findLastIndex()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
};
console.log(
Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)),
); // 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.findlastindex](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.findlastindex) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findLastIndex` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | 18.0.0 |
See also
--------
* [Polyfill of `Array.prototype.findIndex` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.findLast()`](findlast)
* [`Array.prototype.find()`](find)
* [`Array.prototype.indexOf()`](indexof)
| programming_docs |
javascript Array.prototype.length Array.prototype.length
======================
The `length` data property of an [`Array`](../array) instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Try it
------
Value
-----
A non-negative integer less than 232.
| Property attributes of `Array.prototype.length` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | no |
Description
-----------
The value of the `length` property is a non-negative integer with a value less than 232.
```
const listA = [1, 2, 3];
const listB = new Array(6);
console.log(listA.length);
// 3
console.log(listB.length);
// 6
listB.length = 2 \*\* 32; // 4294967296
// RangeError: Invalid array length
const listC = new Array(-100); // Negative numbers are not allowed
// RangeError: Invalid array length
```
The array object observes the `length` property, and automatically syncs the `length` value with the array's content. This means:
* Setting `length` to a value smaller than the current length truncates the array — elements beyond the new `length` are deleted.
* Setting any array index (a non-negative integer smaller than 232) beyond the current `length` extends the array — the `length` property is increased to reflect the new highest index.
* Setting `length` to an invalid value (e.g. a negative number or a non-integer) throws a `RangeError` exception.
When `length` is set to a bigger value than the current length, the array is extended by adding [empty slots](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), not actual `undefined` values. Empty slots have some special interactions with array methods; see [array methods and empty slots](../array#array_methods_and_empty_slots).
```
const arr = [1, 2];
console.log(arr);
// [ 1, 2 ]
arr.length = 5; // set array length to 5 while currently 2.
console.log(arr);
// [ 1, 2, <3 empty items> ]
arr.forEach((element) => console.log(element));
// 1
// 2
```
See also [Relationship between `length` and numerical properties](../array#relationship_between_length_and_numerical_properties).
Examples
--------
### Iterating over an array
In the following example, the array `numbers` is iterated through by looking at the `length` property. The value in each element is then doubled.
```
const numbers = [1, 2, 3, 4, 5];
const length = numbers.length;
for (let i = 0; i < length; i++) {
numbers[i] \*= 2;
}
// numbers is now [2, 4, 6, 8, 10]
```
### Shortening an array
The following example shortens the array `numbers` to a length of 3 if the current length is greater than 3.
```
const numbers = [1, 2, 3, 4, 5];
if (numbers.length > 3) {
numbers.length = 3;
}
console.log(numbers); // [1, 2, 3]
console.log(numbers.length); // 3
console.log(numbers[3]); // undefined; the extra elements are deleted
```
### Create empty array of fixed length
Setting `length` to a value greater than the current length creates a [sparse array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
```
const numbers = [];
numbers.length = 3;
console.log(numbers); // [empty x 3]
```
### Array with non-writable length
The `length` property is automatically updated by the array when elements are added beyond the current length. If the `length` property is made non-writable, the array will not be able to update it. This causes an error in [strict mode](../../strict_mode).
```
"use strict";
const numbers = [1, 2, 3, 4, 5];
Object.defineProperty(numbers, "length", { writable: false });
numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-properties-of-array-instances-length](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-properties-of-array-instances-length) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `length` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array`](../array)
* [RangeError: invalid array length](../../errors/invalid_array_length)
javascript Array.prototype.keys() Array.prototype.keys()
======================
The `keys()` method returns a new **Array Iterator** object that contains the keys for each index in the array.
Try it
------
Syntax
------
```
keys()
```
### Return value
A new [`Array`](../array) iterator object.
Description
-----------
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `keys()` method iterates empty slots as if they have the value `undefined`.
The `keys()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using keys() on sparse arrays
Unlike [`Object.keys()`](../object/keys), which only includes keys that actually exist in the array, the `keys()` iterator doesn't ignore holes representing missing properties.
```
const arr = ["a", , "c"];
const sparseKeys = Object.keys(arr);
const denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]
```
### Calling keys() on non-array objects
The `keys()` method reads the `length` property of `this` and then yields all integer indices between 0 and `length - 1`. No index access actually happens.
```
const arrayLike = {
length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
console.log(entry);
}
// 0
// 1
// 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.keys](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.keys) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `keys` | 38 | 12 | 28 | No | 25 | 8 | 38 | 38 | 28 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Array.prototype.keys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.values()`](values)
* [`Array.prototype.entries()`](entries)
* [Iteration protocols](../../iteration_protocols)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
javascript Array.prototype.flat() Array.prototype.flat()
======================
The `flat()` method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Try it
------
Syntax
------
```
flat()
flat(depth)
```
### Parameters
`depth` Optional
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
### Return value
A new array with the sub-array elements concatenated into it.
Description
-----------
The `flat()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array.
The `flat()` method ignores empty slots if the array being flattened is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves.
The `flat()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened.
Examples
--------
### Flattening nested arrays
```
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### Using flat() on sparse arrays
The `flat()` method removes empty slots in arrays:
```
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // [1, 2, 4, 5]
const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]
const array2 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(array2.flat()); // [ 1, 3, "a", ["d", empty, "e"] ]
console.log(array2.flat(2)); // [ 1, 3, "a", "d", "e"]
```
### Calling flat() on non-array objects
The `flat()` method reads the `length` property of `this` and then accesses each integer index. If the element is not an array, it's directly appended to the result. If the element is an array, it's flattened according to the `depth` parameter.
```
const arrayLike = {
length: 3,
0: [1, 2],
// Array-like objects aren't flattened
1: { length: 2, 0: 3, 1: 4 },
2: 5,
};
console.log(Array.prototype.flat.call(arrayLike));
// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.flat](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.flat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `flat` | 69 | 79 | 62 | No | 56 | 12 | 69 | 69 | 62 | 48 | 12 | 10.0 | 1.0 | 11.0.0 |
See also
--------
* [Polyfill of `Array.prototype.flat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.flatMap()`](flatmap)
* [`Array.prototype.map()`](map)
* [`Array.prototype.reduce()`](reduce)
* [`Array.prototype.concat()`](concat)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
javascript Array.isArray() Array.isArray()
===============
The `Array.isArray()` static method determines whether the passed value is an [`Array`](../array).
Syntax
------
```
Array.isArray(value)
```
### Parameters
`value` The value to be checked.
### Return value
`true` if `value` is an [`Array`](../array); otherwise, `false`. `false` is always returned if `value` is a [`TypedArray`](../typedarray) instance.
Description
-----------
`Array.isArray()` checks if the passed value is an [`Array`](../array). It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause [`instanceof Array`](../../operators/instanceof) to fail.
See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details.
`Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept.
Examples
--------
### Using Array.isArray()
```
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
// This is not an array, because it was not created using the
// array literal syntax or the Array constructor
Array.isArray({ \_\_proto\_\_: Array.prototype });
```
### instanceof vs Array.isArray()
When checking for `Array` instance, `Array.isArray()` is preferred over `instanceof` because it works across realms.
```
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xArray = window.frames[window.frames.length - 1].Array;
const arr = new xArray(1, 2, 3); // [1, 2, 3]
// Correctly checking for Array
Array.isArray(arr); // true
// The prototype of arr is xArray.prototype, which is a
// different object from Array.prototype
arr instanceof Array; // false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.isarray](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.isarray) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `isArray` | 4 | 12 | 4 | 9 | 10.5 | 5 | 4.4 | 18 | 4 | 14 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.isArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
* [`Array`](../array)
javascript Array.prototype.find() Array.prototype.find()
======================
The `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../undefined) is returned.
Try it
------
* If you need the **index** of the found element in the array, use [`findIndex()`](findindex).
* If you need to find the **index of a value**, use [`indexOf()`](indexof). (It's similar to [`findIndex()`](findindex), but checks each element for equality with the value instead of using a testing function.)
* If you need to find if a value **exists** in an array, use [`includes()`](includes). Again, it checks each element for equality with the value instead of using a testing function.
* If you need to find if any element satisfies the provided testing function, use [`some()`](some).
Syntax
------
```
// Arrow function
find((element) => { /\* … \*/ })
find((element, index) => { /\* … \*/ })
find((element, index, array) => { /\* … \*/ })
// Callback function
find(callbackFn)
find(callbackFn, thisArg)
// Inline callback function
find(function (element) { /\* … \*/ })
find(function (element, index) { /\* … \*/ })
find(function (element, index, array) { /\* … \*/ })
find(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `find()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
The first element in the array that satisfies the provided testing function. Otherwise, [`undefined`](../undefined) is returned.
Description
-----------
The `find()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns [`undefined`](../undefined).
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
`find()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `find()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `find()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Find an object in an array by one of its properties
```
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
```
#### Using arrow function and destructuring
```
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
const result = inventory.find(({ name }) => name === "cherries");
console.log(result); // { name: 'cherries', quantity: 5 }
```
### Find a prime number in an array
The following example finds an element in the array that is a prime number (or returns [`undefined`](../undefined) if there is no prime number):
```
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
```
### Using find() on sparse arrays
Empty slots in sparse arrays *are* visited, and are treated the same as `undefined`.
```
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];
// Shows all indexes, not just those with assigned values
array.find((value, index) => {
console.log("Visited index ", index, " with value ", value);
});
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value 5
// Visited index 6 with value 6
// Shows all indexes, including deleted
array.find((value, index) => {
// Delete element 5 on first iteration
if (index === 0) {
console.log("Deleting array[5] with value ", array[5]);
delete array[5];
}
// Element 5 is still visited even though deleted
console.log("Visited index ", index, " with value ", value);
});
// Deleting array[5] with value 5
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value undefined
// Visited index 6 with value 6
```
### Calling find() on non-array objects
The `find()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
};
console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)));
// 7.3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.find](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `find` | 45 | 12 | 25 | No | 32 | 8 | 45 | 45 | 4 | 32 | 8 | 5.0 | 1.0 | 4.0.0
0.12.0 |
See also
--------
* [Polyfill of `Array.prototype.find` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.findIndex()`](findindex) – find and return an index
* [`Array.prototype.includes()`](includes) – test whether a value exists in the array
* [`Array.prototype.filter()`](filter) – remove all non-matching elements
* [`Array.prototype.every()`](every) – test all elements
* [`Array.prototype.some()`](some) – test until one element matches
| programming_docs |
javascript Array.prototype.flatMap() Array.prototype.flatMap()
=========================
The `flatMap()` method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [`map()`](map) followed by a [`flat()`](flat) of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately.
Try it
------
Syntax
------
```
// Arrow function
flatMap((element) => { /\* … \*/ })
flatMap((element, index) => { /\* … \*/ })
flatMap((element, index, array) => { /\* … \*/ })
// Callback function
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
// Inline callback function
flatMap(function (element) { /\* … \*/ })
flatMap(function (element, index) { /\* … \*/ })
flatMap(function (element, index, array) { /\* … \*/ })
flatMap(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `flatMap()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
A new array with each element being the result of the callback function and flattened by a depth of 1.
Description
-----------
The `flatMap()` method is an [iterative method](../array#iterative_methods). See [`Array.prototype.map()`](map) for a detailed description of the callback function. The `flatMap()` method is identical to [`map(callbackFn, thisArg)`](map) followed by [`flat(1)`](flat) — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array.
The `flatMap()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened.
### Alternative
#### Pre-allocate and explicitly iterate
```
const arr = [1, 2, 3, 4];
arr.flatMap((x) => [x, x \* 2]);
// is equivalent to
const n = arr.length;
const acc = new Array(n \* 2);
for (let i = 0; i < n; i++) {
const x = arr[i];
acc[i \* 2] = x;
acc[i \* 2 + 1] = x \* 2;
}
// [1, 2, 2, 4, 3, 6, 4, 8]
```
Note that in this particular case the `flatMap` approach is slower than the for-loop approach — due to the creation of temporary arrays that must be garbage collected, as well as the return array not needing to be frequently resized. However, `flatMap` may still be the correct solution in cases where its flexibility and readability are desired.
Examples
--------
### map() and flatMap()
```
const arr1 = [1, 2, 3, 4];
arr1.map((x) => [x \* 2]);
// [[2], [4], [6], [8]]
arr1.flatMap((x) => [x \* 2]);
// [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap((x) => [[x \* 2]]);
// [[2], [4], [6], [8]]
```
While the above could have been achieved by using map itself, here is an example that better showcases the use of `flatMap()`.
Let's generate a list of words from a list of sentences.
```
const arr1 = ["it's Sunny in", "", "California"];
arr1.map((x) => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]
arr1.flatMap((x) => x.split(" "));
// ["it's","Sunny","in", "", "California"]
```
Notice, the output list length can be different from the input list length.
### For adding and removing items during a map()
`flatMap` can be used as a way to add and remove items (modify the number of items) during a `map`. In other words, it allows you to map *many items to many items* (by handling each input item separately), rather than always *one-to-one*. In this sense, it works like the opposite of <filter>. Return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.
```
// Let's say we want to remove all the negative numbers
// and split the odd numbers into an even number and a 1
const a = [5, 4, -3, 20, 17, -33, -4, 18];
// |\ \ x | | \ x x |
// [4,1, 4, 20, 16, 1, 18]
const result = a.flatMap((n) => {
if (n < 0) {
return [];
}
return n % 2 === 0 ? [n] : [n - 1, 1];
});
console.log(result); // [4, 1, 4, 20, 16, 1, 18]
```
### Using flatMap() on sparse arrays
The `callbackFn` won't be called for empty slots in the source array because `map()` doesn't, while `flat()` ignores empty slots in the returned arrays.
```
console.log([1, 2, , 4, 5].flatMap((x) => [x, x \* 2])); // [1, 2, 2, 4, 4, 8, 5, 10]
console.log([1, 2, 3, 4].flatMap((x) => [, x \* 2])); // [2, 4, 6, 8]
```
### Calling flatMap() on non-array objects
The `flatMap()` method reads the `length` property of `this` and then accesses each integer index. If the return value of the callback function is not an array, it is always directly appended to the result array.
```
const arrayLike = {
length: 3,
0: 1,
1: 2,
2: 3,
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x \* 2]));
// [1, 2, 2, 4, 3, 6]
// Array-like objects returned from the callback won't be flattened
console.log(
Array.prototype.flatMap.call(arrayLike, (x) => ({
length: 1,
0: x,
})),
);
// [ { '0': 1, length: 1 }, { '0': 2, length: 1 }, { '0': 3, length: 1 } ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.flatmap](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.flatmap) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `flatMap` | 69 | 79 | 62 | No | 56 | 12 | 69 | 69 | 62 | 48 | 12 | 10.0 | 1.0 | 11.0.0 |
See also
--------
* [Polyfill of `Array.prototype.flatMap` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.flat()`](flat)
* [`Array.prototype.map()`](map)
* [`Array.prototype.reduce()`](reduce)
* [`Array.prototype.concat()`](concat)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
javascript Array.prototype.push() Array.prototype.push()
======================
The `push()` method adds one or more elements to the end of an array and returns the new length of the array.
Try it
------
Syntax
------
```
push(element0)
push(element0, element1)
push(element0, element1, /\* … ,\*/ elementN)
```
### Parameters
`elementN` The element(s) to add to the end of the array.
### Return value
The new [`length`](length) property of the object upon which the method was called.
Description
-----------
The `push()` method appends values to an array.
[`Array.prototype.unshift()`](unshift) has similar behavior to `push()`, but applied to the start of an array.
The `push()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](concat) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`.
The `push()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Adding elements to an array
The following code creates the `sports` array containing two elements, then appends two elements to it. The `total` variable contains the new length of the array.
```
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
```
### Merging two arrays
This example uses [spread syntax](../../operators/spread_syntax) to push all elements from a second array into the first one.
```
const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];
// Merge the second array into the first one
vegetables.push(...moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
```
Merging two arrays can also be done with the [`concat()`](concat) method.
### Calling push() on non-array objects
The `push()` method reads the `length` property of `this`. It then sets each index of `this` starting at `length` with the arguments passed to `push()`. Finally, it sets the `length` to the previous length plus the number of pushed elements.
```
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```
### Using an object in an array-like fashion
As mentioned above, `push` is intentionally generic, and we can use that to our advantage. `Array.prototype.push` can work on an object just fine, as this example shows.
Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use `call` on `Array.prototype.push` to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.
```
const obj = {
length: 0,
addElem(elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
},
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2
```
Note that although `obj` is not an array, the method `push` successfully incremented `obj`'s `length` property just like if we were dealing with an actual array.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.push](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.push) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `push` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.push` in `core-js` with fixes of this method](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.pop()`](pop)
* [`Array.prototype.shift()`](shift)
* [`Array.prototype.unshift()`](unshift)
* [`Array.prototype.concat()`](concat)
javascript Array.prototype.reduce() Array.prototype.reduce()
========================
The `reduce()` method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array:
Try it
------
The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.
Syntax
------
```
// Arrow function
reduce((accumulator, currentValue) => { /\* … \*/ })
reduce((accumulator, currentValue, currentIndex) => { /\* … \*/ })
reduce((accumulator, currentValue, currentIndex, array) => { /\* … \*/ })
reduce((accumulator, currentValue) => { /\* … \*/ }, initialValue)
reduce((accumulator, currentValue, currentIndex) => { /\* … \*/ }, initialValue)
reduce((accumulator, currentValue, currentIndex, array) => { /\* … \*/ }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function (accumulator, currentValue) { /\* … \*/ })
reduce(function (accumulator, currentValue, currentIndex) { /\* … \*/ })
reduce(function (accumulator, currentValue, currentIndex, array) { /\* … \*/ })
reduce(function (accumulator, currentValue) { /\* … \*/ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex) { /\* … \*/ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex, array) { /\* … \*/ }, initialValue)
```
### Parameters
`callbackFn` A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`.
The function is called with the following arguments:
`accumulator` The value resulting from the previous call to `callbackFn`. On first call, `initialValue` if specified, otherwise the value of `array[0]`.
`currentValue` The value of the current element. On first call, the value of `array[0]` if an `initialValue` was specified, otherwise the value of `array[1]`.
`currentIndex` The index position of `currentValue` in the array. On first call, `0` if `initialValue` was specified, otherwise `1`.
`array` The array `reduce()` was called upon.
`initialValue` Optional
A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`. If `initialValue` is *not* specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown.
### Return value
The value that results from running the "reducer" callback function to completion over the entire array.
### Exceptions
[`TypeError`](../typeerror) The array contains no elements and `initialValue` is not provided.
Description
-----------
The `reduce()` method is an [iterative method](../array#iterative_methods). It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
Unlike other [iterative methods](../array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict.
`reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](../../operators/spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined.
`reduce()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `reduce()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `reduce()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
### When to not use reduce()
Recursive functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.
### Edge cases
If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned *without* calling `callbackFn`.
If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.
If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:
```
const getMax = (a, b) => Math.max(a, b);
// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100
[50].reduce(getMax, 10); // 50
// callback is invoked once for element at index 1
[1, 100].reduce(getMax); // 100
// callback is not invoked
[50].reduce(getMax); // 50
[].reduce(getMax, 1); // 1
[].reduce(getMax); // TypeError
```
Examples
--------
### How reduce() works without an initial value
The code below shows what happens if we call `reduce()` with an array and no initial value.
```
const array = [15, 16, 17, 18, 19];
function reducer(accumulator, currentValue, index) {
const returns = accumulator + currentValue;
console.log(
`accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
);
return returns;
}
array.reduce(reducer);
```
The callback would be invoked four times, with the arguments and return values in each call being as follows:
| | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `15` | `16` | `1` | `31` |
| Second call | `31` | `17` | `2` | `48` |
| Third call | `48` | `18` | `3` | `66` |
| Fourth call | `66` | `19` | `4` | `85` |
The `array` parameter never changes through the process — it's always `[15, 16, 17, 18, 19]`. The value returned by `reduce()` would be that of the last callback invocation (`85`).
### How reduce() works with an initial value
Here we reduce the same array using the same algorithm, but with an `initialValue` of `10` passed as the second argument to `reduce()`:
```
[15, 16, 17, 18, 19].reduce(
(accumulator, currentValue) => accumulator + currentValue,
10,
);
```
The callback would be invoked five times, with the arguments and return values in each call being as follows:
| | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `10` | `15` | `0` | `25` |
| Second call | `25` | `16` | `1` | `41` |
| Third call | `41` | `17` | `2` | `58` |
| Fourth call | `58` | `18` | `3` | `76` |
| Fifth call | `76` | `19` | `4` | `95` |
The value returned by `reduce()` in this case would be `95`.
### Sum of values in an object array
To sum up the values contained in an array of objects, you **must** supply an `initialValue`, so that each item passes through your function.
```
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sum = objects.reduce(
(accumulator, currentValue) => accumulator + currentValue.x,
0,
);
console.log(sum); // 6
```
### Flatten an array of arrays
```
const flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
// flattened is [0, 1, 2, 3, 4, 5]
```
### Counting instances of values in an object
```
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = names.reduce((allNames, name) => {
const currCount = allNames[name] ?? 0;
return {
...allNames,
[name]: currCount + 1,
};
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
```
### Grouping objects by a property
```
const people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
const curGroup = acc[key] ?? [];
return { ...acc, [key]: [...curGroup, obj] };
}, {});
}
const groupedPeople = groupBy(people, "age");
console.log(groupedPeople);
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
```
### Concatenating arrays contained in an array of objects using the spread syntax and initialValue
```
// friends - an array of objects
// where object field "books" is a list of favorite books
const friends = [
{
name: "Anna",
books: ["Bible", "Harry Potter"],
age: 21,
},
{
name: "Bob",
books: ["War and peace", "Romeo and Juliet"],
age: 26,
},
{
name: "Alice",
books: ["The Lord of the Rings", "The Shining"],
age: 18,
},
];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
const allbooks = friends.reduce(
(accumulator, currentValue) => [...accumulator, ...currentValue.books],
["Alphabet"],
);
console.log(allbooks);
// [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
```
### Remove duplicate items in an array
**Note:** The same effect can be achieved with [`Set`](../set) and [`Array.from()`](from) as `const arrayWithNoDuplicates = Array.from(new Set(myArray))` with better performance.
```
const myArray = ["a", "b", "a", "b", "c", "e", "e", "c", "d", "d", "d", "d"];
const myArrayWithNoDuplicates = myArray.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
return [...accumulator, currentValue];
}
return accumulator;
}, []);
console.log(myArrayWithNoDuplicates);
```
### Replace .filter().map() with .reduce()
Using [`filter()`](filter) then [`map()`](map) traverses the array twice, but you can achieve the same effect while traversing only once with [`reduce()`](reduce), thereby being more efficient. (If you like `for` loops, you can filter and map while traversing once with [`forEach()`](foreach).)
```
const numbers = [-5, 6, 2, 0];
const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => {
if (currentValue > 0) {
const doubled = currentValue \* 2;
return [...accumulator, doubled];
}
return accumulator;
}, []);
console.log(doubledPositiveNumbers); // [12, 4]
```
### Running Promises in Sequence
```
/\*\*
\* Chain a series of promise handlers.
\*
\* @param {array} arr - A list of promise handlers, each one receiving the
\* resolved result of the previous handler and returning another promise.
\* @param {\*} input The initial value to start the promise chain
\* @return {Object} Final promise with a chain of handlers attached
\*/
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input),
);
}
// promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a \* 5);
});
}
// promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a \* 2);
});
}
// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a \* 3;
}
// promise function 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a \* 4);
});
}
const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10).then(console.log); // 1200
```
### Function composition enabling piping
```
// Building-blocks to use for composition
const double = (x) => 2 \* x;
const triple = (x) => 3 \* x;
const quadruple = (x) => 4 \* x;
// Function composition enabling pipe functionality
const pipe =
(...functions) =>
(initialValue) =>
functions.reduce((acc, fn) => fn(acc), initialValue);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
```
### Using reduce() with sparse arrays
`reduce()` skips missing elements in sparse arrays, but it does not skip `undefined` values.
```
console.log([1, 2, , 4].reduce((a, b) => a + b)); // 7
console.log([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN
```
### Calling reduce() on non-array objects
The `reduce()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));
// 9
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.reduce](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.reduce) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reduce` | 3 | 12 | 3 | 9 | 10.5 | 4 | ≤37 | 18 | 4 | 14 | 3.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.reduce` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.reduceRight()`](reduceright)
| programming_docs |
javascript Array.prototype[@@iterator]() Array.prototype[@@iterator]()
=============================
The `@@iterator` method of an `Array` object implements the [iterable protocol](../../iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](../../operators/spread_syntax) and [`for...of`](../../statements/for...of) loops. It returns an iterator that yields the value of each index in the array.
The initial value of this property is the same function object as the initial value of the [`Array.prototype.values`](values) property.
Syntax
------
```
array[Symbol.iterator]()
```
### Return value
The same return value as [`Array.prototype.values()`](values): a new iterable iterator object that yields the value of each index in the array.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes arrays [iterable](../../iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically calls this method to obtain the iterator to loop over.
#### HTML
```
<ul id="letterResult"></ul>
```
#### JavaScript
```
const arr = ["a", "b", "c"];
const letterResult = document.getElementById("letterResult");
for (const letter of arr) {
const li = document.createElement("li");
li.textContent = letter;
letterResult.appendChild(li);
}
```
#### Result
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```
const arr = ["a", "b", "c", "d", "e"];
const arrIter = arr[Symbol.iterator]();
console.log(arrIter.next().value); // a
console.log(arrIter.next().value); // b
console.log(arrIter.next().value); // c
console.log(arrIter.next().value); // d
console.log(arrIter.next().value); // e
```
### Handling strings and string arrays with the same function
Because both [strings](../string/@@iterator) and arrays implement the iterable protocol, a generic function can be designed to handle both inputs in the same fashion. This is better than calling [`Array.prototype.values()`](values) directly, which requires the input to be an array, or at least an object with such a method.
```
function logIterable(it) {
if (typeof it[Symbol.iterator] !== "function") {
console.log(it, "is not iterable.");
return;
}
for (const letter of it) {
console.log(letter);
}
}
// Array
logIterable(["a", "b", "c"]);
// a
// b
// c
// String
logIterable("abc");
// a
// b
// c
// Number
logIterable(123);
// 123 is not iterable.
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype-@@iterator](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype-@@iterator) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 10 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Array.prototype[@@iterator]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.keys()`](keys)
* [`Array.prototype.entries()`](entries)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.every()`](every)
* [`Array.prototype.some()`](some)
* [`Array.prototype.values()`](values)
javascript Array.prototype.slice() Array.prototype.slice()
=======================
The `slice()` method returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of a portion of an array into a new array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that array. The original array will not be modified.
Try it
------
Syntax
------
```
slice()
slice(start)
slice(start, end)
```
### Parameters
`start` Optional
Zero-based index at which to start extraction, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, nothing is extracted.
`end` Optional
Zero-based index at which to end extraction, [converted to an integer](../number#integer_conversion). `slice()` extracts up to but not including `end`.
* Negative index counts back from the end of the array — if `end < 0`, `end + array.length` is used.
* If `end < -array.length`, `0` is used.
* If `end >= array.length` or `end` is omitted, `array.length` is used, causing all elements until the end to be extracted.
* If `end` is positioned before or at `start` after normalization, nothing is extracted.
### Return value
A new array containing the extracted elements.
Description
-----------
The `slice()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) that contains some of the same elements as the ones from the original array.
The `slice()` method preserves empty slots. If the sliced portion is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the returned array is sparse as well.
The `slice()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Return a portion of an existing array
```
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
```
### Using slice
In the following example, `slice` creates a new array, `newCar`, from `myCar`. Both include a reference to the object `myHonda`. When the color of `myHonda` is changed to purple, both arrays reflect the change.
```
// Using slice, create newCar from myCar.
const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
const newCar = myCar.slice(0, 2);
console.log("myCar =", myCar);
console.log("newCar =", newCar);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is", myHonda.color);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
```
This script writes:
```
myCar = [
{ color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } },
2,
'cherry condition',
'purchased 1997'
]
newCar = [ { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }, 2 ]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
```
### Calling slice() on non-array objects
The `slice()` method reads the `length` property of `this`. It then reads the integer-keyed properties from `start` to `end` and defines them on a newly created array.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.slice.call(arrayLike, 1, 3));
// [ 3, 4 ]
```
### Using slice() to convert array-like objects to arrays
The `slice()` method is often used with [`bind()`](../function/bind) and [`call()`](../function/call) to create a utility method that converts an array-like object into an array.
```
// slice() is called with `this` passed as the first argument
const slice = Function.prototype.call.bind(Array.prototype.slice);
function list() {
return slice(arguments);
}
const list1 = list(1, 2, 3); // [1, 2, 3]
```
### Using slice() on sparse arrays
The array returned from `slice()` may be sparse if the source is sparse.
```
console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.slice](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.slice) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `slice` | 1 | 12 | 1 | 4 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.splice()`](splice)
* [`Function.prototype.call()`](../function/call)
* [`Function.prototype.bind()`](../function/bind)
javascript Array.prototype.shift() Array.prototype.shift()
=======================
The `shift()` method removes the **first** element from an array and returns that removed element. This method changes the length of the array.
Try it
------
Syntax
------
```
shift()
```
### Return value
The removed element from the array; [`undefined`](../undefined) if the array is empty.
Description
-----------
The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the [`length`](length) property is 0, [`undefined`](../undefined) is returned.
The [`pop()`](pop) method has similar behavior to `shift()`, but applied to the last element in an array.
The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](slice) instead.
The `shift()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Removing an element from an array
The following code displays the `myFish` array before and after removing its first element. It also displays the removed element:
```
const myFish = ["angel", "clown", "mandarin", "surgeon"];
console.log("myFish before:", JSON.stringify(myFish));
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']
const shifted = myFish.shift();
console.log("myFish after:", myFish);
// myFish after: ['clown', 'mandarin', 'surgeon']
console.log("Removed this element:", shifted);
// Removed this element: angel
```
### Using shift() method in while loop
The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array, until it is empty:
```
const names = ["Andrew", "Tyrone", "Paul", "Maria", "Gayatri"];
while (typeof (i = names.shift()) !== "undefined") {
console.log(i);
}
// Andrew, Tyrone, Paul, Maria, Gayatri
```
### Calling shift() on non-array objects
The `shift()` method reads the `length` property of `this`. If the [normalized length](../array#normalization_of_the_length_property) is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `0` is returned, and the rest of the properties are shifted left by one. The `length` property is decremented by one.
```
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.shift.call(arrayLike));
// undefined, because it is an empty slot
console.log(arrayLike);
// { '1': 4, length: 2, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.shift.call(plainObj);
console.log(plainObj);
// { length: 0 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.shift](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.shift) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `shift` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.push()`](push)
* [`Array.prototype.pop()`](pop)
* [`Array.prototype.unshift()`](unshift)
* [`Array.prototype.concat()`](concat)
javascript Array.prototype.some() Array.prototype.some()
======================
The `some()` method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
Try it
------
Syntax
------
```
// Arrow function
some((element) => { /\* … \*/ })
some((element, index) => { /\* … \*/ })
some((element, index, array) => { /\* … \*/ })
// Callback function
some(callbackFn)
some(callbackFn, thisArg)
// Inline callback function
some(function (element) { /\* … \*/ })
some(function (element, index) { /\* … \*/ })
some(function (element, index, array) { /\* … \*/ })
some(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `some()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
`true` if the callback function returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for at least one element in the array. Otherwise, `false`.
Description
-----------
The `some()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value for all elements, `some()` returns `false`.
`some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
`some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
The `some()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Testing value of array elements
The following example tests whether any element in the array is bigger than 10.
```
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
```
### Testing array elements using arrow functions
[Arrow functions](../../functions/arrow_functions) provide a shorter syntax for the same test.
```
[2, 5, 8, 1, 4].some((x) => x > 10); // false
[12, 5, 8, 1, 4].some((x) => x > 10); // true
```
### Checking whether a value exists in an array
To mimic the function of the `includes()` method, this custom function returns `true` if the element exists in the array:
```
const fruits = ["apple", "banana", "mango", "guava"];
function checkAvailability(arr, val) {
return arr.some((arrVal) => val === arrVal);
}
checkAvailability(fruits, "kela"); // false
checkAvailability(fruits, "banana"); // true
```
### Converting any value to Boolean
```
const TRUTHY\_VALUES = [true, "true", 1];
function getBoolean(value) {
if (typeof value === "string") {
value = value.toLowerCase().trim();
}
return TRUTHY\_VALUES.some((t) => t === value);
}
getBoolean(false); // false
getBoolean("false"); // false
getBoolean(1); // true
getBoolean("true"); // true
```
### Using some() on sparse arrays
`some()` will not run its predicate on empty slots.
```
console.log([1, , 3].some((x) => x === undefined)); // false
console.log([1, , 1].some((x) => x !== 1)); // false
console.log([1, undefined, 1].some((x) => x !== 1)); // true
```
### Calling some() on non-array objects
The `some()` method reads the `length` property of `this` and then accesses each integer index until the end is reached or `callbackFn` returns `true`.
```
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
};
console.log(Array.prototype.some.call(arrayLike, (x) => typeof x === "number"));
// false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.some](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.some) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `some` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.some` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.every()`](every)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.find()`](find)
* [`TypedArray.prototype.some()`](../typedarray/some)
javascript Array() constructor Array() constructor
===================
The `Array()` constructor is used to create [`Array`](../array) objects.
Syntax
------
```
new Array(element0, element1, /\* … ,\*/ elementN)
new Array(arrayLength)
Array(element0, element1, /\* … ,\*/ elementN)
Array(arrayLength)
```
**Note:** `Array()` can be called with or without [`new`](../../operators/new). Both create a new `Array` instance.
### Parameters
`elementN` A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the bracket syntax.
`arrayLength` If the only argument passed to the `Array` constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values — see [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays)).
### Exceptions
[`RangeError`](../rangeerror) Thrown if there's only one argument (`arrayLength`) and its value is not between 0 and 232 - 1 (inclusive).
Examples
--------
### Array literal notation
Arrays can be created using the [literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) notation:
```
const fruits = ["Apple", "Banana"];
console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
```
### Array constructor with a single parameter
Arrays can be created using a constructor with a single number parameter. An array with its `length` property set to that number and the array elements are empty slots.
```
const fruits = new Array(2);
console.log(fruits.length); // 2
console.log(fruits[0]); // undefined
```
### Array constructor with multiple parameters
If more than one argument is passed to the constructor, a new [`Array`](../array) with the given elements is created.
```
const fruits = new Array("Apple", "Banana");
console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array-constructor](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Array` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array`](../array) class
| programming_docs |
javascript Array.prototype.includes() Array.prototype.includes()
==========================
The `includes()` method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate.
Try it
------
Syntax
------
```
includes(searchElement)
includes(searchElement, fromIndex)
```
### Parameters
`searchElement` The value to search for.
`fromIndex` Optional
Zero-based index at which to start searching, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. However, the array is still searched from front to back in this case.
* If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched.
* If `fromIndex >= array.length`, the array is not searched and `false` is returned.
### Return value
A boolean value which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified).
Description
-----------
The `includes()` method compares `searchElement` to elements of the array using the [SameValueZero](../../operators/strict_equality) algorithm. Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is equal to `0`), but `false` is *not* considered to be the same as `0`. [`NaN`](../nan) can be correctly searched for.
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `includes()` method iterates empty slots as if they have the value `undefined`.
The `includes()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using includes()
```
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
["1", "2", "3"].includes(3); // false
```
### fromIndex is greater than or equal to the array length
If `fromIndex` is greater than or equal to the length of the array, `false` is returned. The array will not be searched.
```
const arr = ["a", "b", "c"];
arr.includes("c", 3); // false
arr.includes("c", 100); // false
```
### Computed index is less than 0
If `fromIndex` is negative, the computed index is calculated to be used as a position in the array at which to begin searching for `searchElement`. If the computed index is less than or equal to `0`, the entire array will be searched.
```
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97
const arr = ["a", "b", "c"];
arr.includes("a", -100); // true
arr.includes("b", -100); // true
arr.includes("c", -100); // true
arr.includes("a", -2); // false
```
### Using includes() on sparse arrays
You can search for `undefined` in a sparse array and get `true`.
```
console.log([1, , 3].includes(undefined)); // true
```
### Calling includes() on non-array objects
The `includes()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.includes.call(arrayLike, 2));
// true
console.log(Array.prototype.includes.call(arrayLike, 1));
// false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.includes](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.includes) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `includes` | 47 | 14 | 43 | No | 34 | 9 | 47 | 47 | 43 | 34 | 9 | 5.0 | 1.0 | 6.0.0
5.0.0 |
See also
--------
* [Polyfill of `Array.prototype.includes` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`TypedArray.prototype.includes()`](../typedarray/includes)
* [`String.prototype.includes()`](../string/includes)
* [`Array.prototype.indexOf()`](indexof)
* [`Array.prototype.find()`](find)
* [`Array.prototype.findIndex()`](findindex)
javascript Array.prototype.splice() Array.prototype.splice()
========================
The `splice()` method changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To access part of an array without modifying it, see [`slice()`](slice).
Try it
------
Syntax
------
```
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)
```
### Parameters
`start` Zero-based index at which to start changing the array, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided.
`deleteCount` Optional
An integer indicating the number of elements in the array to remove from `start`.
If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](../number#integer_conversion) to `0`.
If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below).
`item1`, …, `itemN` Optional
The elements to add to the array, beginning from `start`.
If you do not specify any elements, `splice()` will only remove elements from the array.
### Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
Description
-----------
The `splice()` method is a [mutating method](../array#copying_methods_and_mutating_methods). It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](@@species) to create a new array instance to be returned.
If the deleted portion is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots.
The `splice()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Remove 0 (zero) elements before index 2, and insert "drum"
```
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum");
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed
```
### Remove 0 (zero) elements before index 2, and insert "drum" and "guitar"
```
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum", "guitar");
// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed is [], no elements removed
```
### Remove 1 element at index 3
```
const myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"];
const removed = myFish.splice(3, 1);
// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]
```
### Remove 1 element at index 2, and insert "trumpet"
```
const myFish = ["angel", "clown", "drum", "sturgeon"];
const removed = myFish.splice(2, 1, "trumpet");
// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]
```
### Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"
```
const myFish = ["angel", "clown", "trumpet", "sturgeon"];
const removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]
```
### Remove 2 elements, starting from index 2
```
const myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"];
const removed = myFish.splice(2, 2);
// myFish is ["parrot", "anemone", "sturgeon"]
// removed is ["blue", "trumpet"]
```
### Remove 1 element from index -2
```
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(-2, 1);
// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]
```
### Remove all elements, starting from index 2
```
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2);
// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]
```
### Using splice() on sparse arrays
The `splice()` method preserves the array's sparseness.
```
const arr = [1, , 3, 4, , 6];
console.log(arr.splice(1, 2)); // [empty, 3]
console.log(arr); // [1, 4, empty, 6]
```
### Calling splice() on non-array objects
The `splice()` method reads the `length` property of `this`. It then updates the integer-keyed properties and the `length` property as needed.
```
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
};
console.log(Array.prototype.splice.call(arrayLike, 0, 1, 2, 3));
// [ 5 ]
console.log(arrayLike);
// { '0': 2, '1': 3, '3': 4, length: 4, unrelated: 'foo' }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.splice](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.splice) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `splice` | 1 | 12 | 1 | 5.5
From Internet Explorer 5.5 through 8, all elements of the array will not be deleted if `deleteCount` is omitted. This behavior was fixed in Internet Explorer 9. | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`push()`](push) / [`pop()`](pop)— add/remove elements from the end of the array
* [`unshift()`](unshift) / [`shift()`](shift)— add/remove elements from the beginning of the array
* [`concat()`](concat)— returns a new array comprised of this array joined with other array(s) and/or value(s)
javascript Array.prototype.entries() Array.prototype.entries()
=========================
The `entries()` method returns a new **Array Iterator** object that contains the key/value pairs for each index in the array.
Try it
------
Syntax
------
```
entries()
```
### Return value
A new [`Array`](../array) iterator object.
Description
-----------
When used on [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `entries()` method iterates empty slots as if they have the value `undefined`.
The `entries()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Iterating with index and element
```
const a = ["a", "b", "c"];
for (const [index, element] of a.entries()) {
console.log(index, element);
}
// 0 'a'
// 1 'b'
// 2 'c'
```
### Using a for...of loop
```
const array = ["a", "b", "c"];
const arrayEntries = array.entries();
for (const element of arrayEntries) {
console.log(element);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']
```
### Iterating sparse arrays
`entries()` will visit empty slots as if they are `undefined`.
```
for (const element of [, "a"].entries()) {
console.log(element);
}
// [0, undefined]
// [1, 'a']
```
### Calling entries() on non-array objects
The `entries()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.entries](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.entries) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `entries` | 38 | 12 | 28 | No | 25 | 8 | 38 | 38 | 28 | 25 | 8 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Array.prototype.entries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.keys()`](keys)
* [`Array.prototype.values()`](values)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.every()`](every)
* [`Array.prototype.some()`](some)
* [for...of](../../statements/for...of)
* [Iteration protocols](../../iteration_protocols)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
javascript Array.prototype[@@unscopables] Array.prototype[@@unscopables]
==============================
The `@@unscopables` data property of `Array.prototype` is shared by all [`Array`](../array) instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](../../statements/with) statement-binding purposes.
Value
-----
A [`null`-prototype object](../object#null-prototype_objects) with property names given below and their values set to `true`.
| Property attributes of `Array.prototype[@@unscopables]` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | yes |
Description
-----------
The default `Array` properties that are ignored for `with` statement-binding purposes are:
* [`at()`](at)
* [`copyWithin()`](copywithin)
* [`entries()`](entries)
* [`fill()`](fill)
* [`find()`](find)
* [`findIndex()`](findindex)
* [`findLast()`](findlast)
* [`findLastIndex()`](findlastindex)
* [`flat()`](flat)
* [`flatMap()`](flatmap)
* [`includes()`](includes)
* [`keys()`](keys)
* [`values()`](values)
`Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](../object#null-prototype_objects), so `Object.prototype` properties like [`toString`](../object/tostring) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array.
See [`Symbol.unscopables`](../symbol/unscopables) for how to set unscopable properties for your own objects.
Examples
--------
Imagine the `keys.push('something')` call below is in code that was written prior to ECMAScript 2015.
```
var keys = [];
with (Array.prototype) {
keys.push("something");
}
```
When ECMAScript 2015 introduced the [`Array.prototype.keys()`](keys) method, if the `@@unscopables` data property had not also been introduced, that `keys.push('something')` call would break — because the JavaScript runtime would have interpreted `keys` as being the [`Array.prototype.keys()`](keys) method, rather than the `keys` array defined in the example code.
So the `@@unscopables` data property for `Array.prototype` causes the `Array` properties introduced in ECMAScript 2015 to be ignored for `with` statement-binding purposes — allowing code that was written prior to ECMAScript 2015 to continue working as expected, rather than breaking.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype-@@unscopables](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype-@@unscopables) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@unscopables` | 38 | 12 | 48 | No | 25 | 10 | 38 | 38 | 48 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`Symbol.unscopables`](../symbol/unscopables)
javascript get Array[@@species] get Array[@@species]
====================
The `Array[@@species]` accessor property returns the constructor used to construct return values from array methods.
**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
Syntax
------
```
Array[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from array methods that create new arrays.
Description
-----------
The `@@species` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```
// Hypothetical underlying implementation for illustration
class Array {
static get [Symbol.species]() {
return this;
}
}
```
Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.
```
class SubArray extends Array {}
SubArray[Symbol.species] === SubArray; // true
```
When calling array methods that do not mutate the existing array but return a new array instance (for example, [`filter()`](filter) and [`map()`](map)), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays.
```
class NotAnArray {
constructor(length) {
this.length = length;
}
}
const arr = [0, 1, 2];
arr.constructor = { [Symbol.species]: NotAnArray };
arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 }
arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 }
arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 }
```
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `Array` constructor for `Array`.
```
Array[Symbol.species]; // [Function: Array]
```
### Species in derived objects
In an instance of a custom `Array` subclass, such as `MyArray`, the `MyArray` species is the `MyArray` constructor. However, you might want to overwrite this, in order to return parent `Array` objects in your derived class methods:
```
class MyArray extends Array {
// Overwrite MyArray species to the parent Array constructor
static get [Symbol.species]() {
return Array;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-array-@@species](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-get-array-@@species) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@species` | 51 | 79 | 48 | No | 38 | 10 | 51 | 51 | 48 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [Polyfill of `Array[Symbol.species]` and support of `Symbol.species` in all affected `Array` methods in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array`](../array)
* [`Symbol.species`](../symbol/species)
| programming_docs |
javascript Array.prototype.indexOf() Array.prototype.indexOf()
=========================
The `indexOf()` method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Try it
------
Syntax
------
```
indexOf(searchElement)
indexOf(searchElement, fromIndex)
```
### Parameters
`searchElement` Element to locate in the array.
`fromIndex` Optional
Zero-based index at which to start searching, [converted to an integer](../number#integer_conversion).
* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case.
* If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched.
* If `fromIndex >= array.length`, the array is not searched and `-1` is returned.
### Return value
The first index of the element in the array; **-1** if not found.
Description
-----------
The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](../../operators/strict_equality) (the same algorithm used by the `===` operator).
The `indexOf()` method skips empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `indexOf()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Using indexOf()
The following example uses `indexOf()` to locate values in an array.
```
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
```
### Finding all the occurrences of an element
```
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
```
### Finding if an element exists in the array or not and updating the array
```
function updateVegetablesCollection(veggies, veggie) {
if (veggies.indexOf(veggie) === -1) {
veggies.push(veggie);
console.log(`New veggies collection is: ${veggies}`);
} else {
console.log(`${veggie} already exists in the veggies collection.`);
}
}
const veggies = ["potato", "tomato", "chillies", "green-pepper"];
updateVegetablesCollection(veggies, "spinach");
// New veggies collection is: potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach already exists in the veggies collection.
```
### Using indexOf() on sparse arrays
You cannot use `indexOf()` to search for empty slots in sparse arrays.
```
console.log([1, , 3].indexOf(undefined)); // -1
```
### Calling indexOf() on non-array objects
The `indexOf()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.indexOf.call(arrayLike, 2));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.indexof](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.indexof) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `indexOf` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.indexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.lastIndexOf()`](lastindexof)
* [`TypedArray.prototype.indexOf()`](../typedarray/indexof)
* [`String.prototype.indexOf()`](../string/indexof)
javascript Array.from() Array.from()
============
The `Array.from()` static method creates a new, shallow-copied `Array` instance from an iterable or array-like object.
Try it
------
Syntax
------
```
Array.from(arrayLike)
// Arrow function
Array.from(arrayLike, (element) => { /\* … \*/ })
Array.from(arrayLike, (element, index) => { /\* … \*/ })
// Mapping function
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)
// Inline mapping function
Array.from(arrayLike, function (element) { /\* … \*/ })
Array.from(arrayLike, function (element, index) { /\* … \*/ })
Array.from(arrayLike, function (element) { /\* … \*/ }, thisArg)
Array.from(arrayLike, function (element, index) { /\* … \*/ }, thisArg)
```
### Parameters
`arrayLike` An iterable or array-like object to convert to an array.
`mapFn` Optional
Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`thisArg` Optional
Value to use as `this` when executing `mapFn`.
### Return value
A new [`Array`](../array) instance.
Description
-----------
`Array.from()` lets you create `Array`s from:
* [iterable objects](../../iteration_protocols) (objects such as [`Map`](../map) and [`Set`](../set)); or, if the object is not iterable,
* array-like objects (objects with a `length` property and indexed elements).
`Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array.
`Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to [`map()`](map). More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction.
**Note:** This behavior is more important for [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), since the intermediate array would necessarily have values truncated to fit into the appropriate type. `Array.from()` is implemented to have the same signature as [`TypedArray.from()`](../typedarray/from).
The `Array.from()` method is a generic factory method. For example, if a subclass of `Array` inherits the `from()` method, the inherited `from()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array. When an iterable is passed as `arrayLike`, the constructor is called with no arguments; when an array-like object is passed, the constructor is called with the [normalized length](../array#normalization_of_the_length_property) of the array-like object. The final `length` will be set again when iteration finishes. If the `this` value is not a constructor function, the plain `Array` constructor is used instead.
Examples
--------
### Array from a String
```
Array.from("foo");
// [ "f", "o", "o" ]
```
### Array from a Set
```
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]
```
### Array from a Map
```
const map = new Map([
[1, 2],
[2, 4],
[4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([
["1", "a"],
["2", "b"],
]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
```
### Array from a NodeList
```
// Create an array based on a property of DOM Elements
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));
```
### Array from an Array-like object (arguments)
```
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
```
### Using arrow functions and Array.from()
```
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], (x) => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]
```
### Sequence generator (range)
```
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP, etc.)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1 }, (\_, i) => start + i \* step);
// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
// Generate the alphabet using Array.from making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0), 1).map((x) =>
String.fromCharCode(x),
);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
```
### Calling from() on non-array constructors
The `from()` method can be called on any constructor function that accepts a single argument representing the length of the new array.
```
function NotArray(len) {
console.log("NotArray called with length", len);
}
// Iterable
console.log(Array.from.call(NotArray, new Set(["foo", "bar", "baz"])));
// NotArray called with length undefined
// NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 }
// Array-like
console.log(Array.from.call(NotArray, { length: 1, 0: "foo" }));
// NotArray called with length 1
// NotArray { '0': 'foo', length: 1 }
```
When the `this` value is not a constructor, a plain `Array` object is returned.
```
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.from](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `from` | 45 | 12 | 32 | No | 32 | 9 | 45 | 45 | 32 | 32 | 9 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `Array.from` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array`](../array)
* [`Array.of()`](of)
* [`Array.prototype.map()`](map)
* [`TypedArray.from()`](../typedarray/from)
javascript Array.of() Array.of()
==========
The `Array.of()` static method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments.
Syntax
------
```
Array.of(element0)
Array.of(element0, element1)
Array.of(element0, element1, /\* … ,\*/ elementN)
```
### Parameters
`elementN` Elements used to create the array.
### Return value
A new [`Array`](../array) instance.
Description
-----------
The difference between `Array.of()` and the [`Array()`](array) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual [`undefined`](../undefined) values.)
```
Array.of(7); // [7]
Array(7); // array of 7 empty slots
Array.of(1, 2, 3); // [1, 2, 3]
Array(1, 2, 3); // [1, 2, 3]
```
The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead.
Examples
--------
### Using Array.of()
```
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]
```
### Calling of() on non-array constructors
The `of()` method can be called on any constructor function that accepts a single argument representing the length of the new array.
```
function NotArray(len) {
console.log("NotArray called with length", len);
}
console.log(Array.of.call(NotArray, 1, 2, 3));
// NotArray called with length 3
// NotArray { '0': 1, '1': 2, '2': 3, length: 3 }
console.log(Array.of.call(Object)); // [Number: 0] { length: 0 }
```
When the `this` value is not a constructor, a plain `Array` object is returned.
```
console.log(Array.of.call({}, 1)); // [ 1 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.of](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.of) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `of` | 45 | 12 | 25 | No | 26 | 9 | 39 | 39 | 25 | 26 | 9 | 4.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `Array.of` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js)
* [`Array()`](array)
* [`Array.from()`](from)
* [`TypedArray.of()`](../typedarray/of)
* [`Array.of()` & `Array.from()` proposal](https://gist.github.com/rwaldron/1074126)
* [`Array.of()` polyfill](https://gist.github.com/rwaldron/3186576)
javascript Array.prototype.toString() Array.prototype.toString()
==========================
The `toString()` method returns a string representing the specified array and its elements.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the elements of the array.
Description
-----------
The [`Array`](../array) object overrides the `toString` method of [`Object`](../object). The `toString` method of arrays calls [`join()`](join) internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, [`Object.prototype.toString`](../object/tostring) is used instead, returning `[object Array]`.
```
const arr = [];
arr.join = 1; // re-assign `join` with a non-function
console.log(arr.toString()); // [object Array]
console.log(Array.prototype.toString.call({ join: () => 1 })); // 1
```
JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
Examples
--------
### Using toString()
```
const array1 = [1, 2, "a", "1a"];
console.log(array1.toString()); // "1,2,a,1a"
```
### Using toString() on sparse arrays
Following the behavior of `join()`, `toString()` treats empty slots the same as `undefined` and produces an extra separator:
```
console.log([1, , 3].toString()); // '1,,3'
```
### Calling toString() on non-array objects
Same as `join()`, `toString()` is [generic](../array#generic_array_methods) and only reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 1,
1: 2,
2: 3,
};
console.log(Array.prototype.toString.call(arrayLike));
// 1,2,3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.tostring](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.tostring) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toString` | 1 | 12 | 1 | 4 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.join()`](join)
javascript Array.prototype.unshift() Array.prototype.unshift()
=========================
The `unshift()` method adds one or more elements to the beginning of an array and returns the new length of the array.
Try it
------
Syntax
------
```
unshift(element0)
unshift(element0, element1)
unshift(element0, element1, /\* … ,\*/ elementN)
```
### Parameters
`elementN` The elements to add to the front of the `arr`.
### Return value
The new [`length`](length) property of the object upon which the method was called.
Description
-----------
The `unshift()` method inserts the given values to the beginning of an array-like object.
[`Array.prototype.push()`](push) has similar behavior to `unshift()`, but applied to the end of an array.
Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results.
See example:
```
let arr = [4, 5, 6];
arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]
arr = [4, 5, 6]; // resetting the array
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr);
// [3, 2, 1, 4, 5, 6]
```
The `unshift()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
--------
### Using unshift()
```
const arr = [1, 2];
arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]
arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]
arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]
arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
```
### Calling unshift() on non-array objects
The `unshift()` method reads the `length` property of `this`. It then shifts all properties in the range `0` to `length - 1` right by the number of arguments and sets each index starting at `0` with the arguments passed to `unshift()`. Finally, it sets the `length` to the previous length plus the number of prepended elements.
```
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
Array.prototype.unshift.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.unshift.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.unshift](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.unshift) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `unshift` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.unshift` in `core-js` with fixes of this method](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.push()`](push)
* [`Array.prototype.pop()`](pop)
* [`Array.prototype.shift()`](shift)
* [`Array.prototype.concat()`](concat)
| programming_docs |
javascript Array.prototype.every() Array.prototype.every()
=======================
The `every()` method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Try it
------
Syntax
------
```
// Arrow function
every((element) => { /\* … \*/ })
every((element, index) => { /\* … \*/ })
every((element, index, array) => { /\* … \*/ })
// Callback function
every(callbackFn)
every(callbackFn, thisArg)
// Inline callback function
every(function (element) { /\* … \*/ })
every(function (element, index) { /\* … \*/ })
every(function (element, index, array) { /\* … \*/ })
every(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) to indicate the element passes the test, and a falsy value otherwise.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `every()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
`true` if `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for every array element. Otherwise, `false`.
Description
-----------
The `every()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for all elements, `every()` returns `true`.
`every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.)
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
`every()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `every()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `every()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Testing size of all array elements
The following example tests whether all elements in the array are bigger than 10.
```
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
```
### Check if one array is a subset of another array
The following example tests if all the elements of an array are present in another array.
```
const isSubset = (array1, array2) =>
array2.every((element) => array1.includes(element));
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false
```
### Using every() on sparse arrays
`every()` will not run its predicate on empty slots.
```
console.log([1, , 3].every((x) => x !== undefined)); // true
console.log([2, , 2].every((x) => x === 2)); // true
```
### Affecting Initial Array (modifying, appending, and deleting)
The following examples tests the behavior of the `every` method when the array is modified.
```
// ---------------
// Modifying items
// ---------------
let arr = [1, 2, 3, 4];
arr.every((elem, index, arr) => {
arr[index + 1]--;
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 2;
});
// Loop runs for 3 iterations, but would
// have run 2 iterations without any modification
//
// 1st iteration: [1,1,3,4][0] -> 1
// 2nd iteration: [1,1,2,4][1] -> 1
// 3rd iteration: [1,1,2,3][2] -> 2
// ---------------
// Appending items
// ---------------
arr = [1, 2, 3];
arr.every((elem, index, arr) => {
arr.push("new");
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 4;
});
// Loop runs for 3 iterations, even after appending new items
//
// 1st iteration: [1, 2, 3, new][0] -> 1
// 2nd iteration: [1, 2, 3, new, new][1] -> 2
// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3
// ---------------
// Deleting items
// ---------------
arr = [1, 2, 3, 4];
arr.every((elem, index, arr) => {
arr.pop();
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 4;
});
// Loop runs for 2 iterations only, as the remaining
// items are `pop()`ed off
//
// 1st iteration: [1,2,3][0] -> 1
// 2nd iteration: [1,2][1] -> 2
```
### Calling every() on non-array objects
The `every()` method reads the `length` property of `this` and then accesses each integer index until the end is reached or `callbackFn` returns `false`.
```
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
};
console.log(
Array.prototype.every.call(arrayLike, (x) => typeof x === "string"),
); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.every](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.every) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `every` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.every` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.some()`](some)
* [`Array.prototype.find()`](find)
* [`TypedArray.prototype.every()`](../typedarray/every)
javascript Array.prototype.concat() Array.prototype.concat()
========================
The `concat()` method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Try it
------
Syntax
------
```
concat()
concat(value0)
concat(value0, value1)
concat(value0, value1, /\* … ,\*/ valueN)
```
### Parameters
`valueN` Optional
Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details.
### Return value
A new [`Array`](../array) instance.
Description
-----------
The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](../symbol/isconcatspreadable) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments.
The `concat()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays.
The `concat()` method preserves empty slots if any of the source arrays is [sparse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `concat()` method is [generic](../array#generic_array_methods). The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `@@isConcatSpreadable` will be spread into the resulting array.
Examples
--------
### Concatenating two arrays
The following code concatenates two arrays:
```
const letters = ["a", "b", "c"];
const numbers = [1, 2, 3];
const alphaNumeric = letters.concat(numbers);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
```
### Concatenating three arrays
The following code concatenates three arrays:
```
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
### Concatenating values to an array
The following code concatenates three values to an array:
```
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
```
### Concatenating nested arrays
The following code concatenates nested arrays and demonstrates retention of references:
```
const num1 = [[1]];
const num2 = [2, [3]];
const numbers = num1.concat(num2);
console.log(numbers);
// results in [[1], 2, [3]]
// modify the first element of num1
num1[0].push(4);
console.log(numbers);
// results in [[1, 4], 2, [3]]
```
### Concatenating array-like objects with Symbol.isConcatSpreadable
`concat` does not treat all array-like objects as arrays by default — only if `Symbol.isConcatSpreadable` is set to a truthy value (e.g. `true`).
```
const obj1 = { 0: 1, 1: 2, 2: 3, length: 3 };
const obj2 = { 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true };
console.log([0].concat(obj1, obj2));
// [ 0, { '0': 1, '1': 2, '2': 3, length: 3 }, 1, 2, 3 ]
```
### Using concat() on sparse arrays
If any of the source arrays is sparse, the resulting array will also be sparse:
```
console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5]
console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]
```
### Calling concat() on non-array objects
If the `this` value is not an array, it is converted to an object and then treated in the same way as the arguments for `concat()`. In this case the return value is always a plain new array.
```
console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3]
console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ]
const arrayLike = { [Symbol.isConcatSpreadable]: true, length: 2, 0: 1, 1: 2 };
console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.concat](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.concat) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `concat` | 1 | 12 | 1 | 5.5 | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.concat` in `core-js` with fixes and implementation of modern behavior like `Symbol.isConcatSpreadable` support](https://github.com/zloirock/core-js#ecmascript-array)
* [`push()`](push) / [`pop()`](pop) — add/remove elements from the end of the array
* [`unshift()`](unshift) / [`shift()`](shift) — add/remove elements from the beginning of the array
* [`splice()`](splice) — add/remove elements from the specified location of the array
* [`String.prototype.concat()`](../string/concat)
* [`Symbol.isConcatSpreadable`](../symbol/isconcatspreadable) — control flattening.
javascript Array.prototype.findLast() Array.prototype.findLast()
==========================
The `findLast()` method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, [`undefined`](../undefined) is returned.
Try it
------
If you need to find:
* the *first* element that matches, use [`find()`](find).
* the *index* of the last matching element in the array, use [`findLastIndex()`](findlastindex).
* the *index of a value*, use [`indexOf()`](indexof). (It's similar to [`findIndex()`](findindex), but checks each element for equality with the value instead of using a testing function.)
* whether a value *exists* in an array, use [`includes()`](includes). Again, it checks each element for equality with the value instead of using a testing function.
* if any element satisfies the provided testing function, use [`some()`](some).
Syntax
------
```
// Arrow function
findLast((element) => { /\* … \*/ })
findLast((element, index) => { /\* … \*/ })
findLast((element, index, array) => { /\* … \*/ })
// Callback function
findLast(callbackFn)
findLast(callbackFn, thisArg)
// Inline callback function
findLast(function (element) { /\* … \*/ })
findLast(function (element, index) { /\* … \*/ })
findLast(function (element, index, array) { /\* … \*/ })
findLast(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `findLast()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
The value of the element in the array with the highest index value that satisfies the provided testing function; [`undefined`](../undefined) if no matching element is found.
Description
-----------
The `findLast()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `findLast()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLast()` returns [`undefined`](../undefined).
`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`.
`findLast()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `findLast()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are visited as if they were `undefined`.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `findLast()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Find last object in an array matching on element properties
This example shows how you might create a test based on the properties of array elements.
```
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
// return true inventory stock is low
function isNotEnough(item) {
return item.quantity < 2;
}
console.log(inventory.findLast(isNotEnough));
// { name: "fish", quantity: 1 }
```
#### Using arrow function and destructuring
The previous example might be written using an arrow function and [object destructuring](../../operators/destructuring_assignment#object_destructuring):
```
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "fish", quantity: 1 },
{ name: "cherries", quantity: 5 },
];
const result = inventory.findLast(({ quantity }) => quantity < 2);
console.log(result);
// { name: "fish", quantity: 1 }
```
### Find last prime number in an array
The following example finds the last element in the array that is a prime number (or returns [`undefined`](../undefined) if there is no prime number):
```
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
```
### Using findLast() on sparse arrays
Empty slots in sparse arrays *are* visited, and are treated the same as `undefined`.
```
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];
// Shows all indexes, not just those with assigned values
array.findLast((value, index) => {
console.log(`Visited index ${index} with value ${value}`);
});
// Visited index 6 with value 6
// Visited index 5 with value 5
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
// Shows all indexes, including deleted
array.findLast((value, index) => {
// Delete element 5 on first iteration
if (index === 6) {
console.log(`Deleting array[5] with value ${array[5]}`);
delete array[5];
}
// Element 5 is still visited even though deleted
console.log(`Visited index ${index} with value ${value}`);
});
// Deleting array[5] with value 5
// Visited index 6 with value 6
// Visited index 5 with value undefined
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
```
### Calling findLast() on non-array objects
The `findLast()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
};
console.log(
Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)),
); // 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.findlast](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.findlast) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findLast` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | 18.0.0 |
See also
--------
* [Polyfill of `Array.prototype.findLast` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.findLastIndex()`](findlastindex) – find last element and return its index
* [`Array.prototype.includes()`](includes) – test whether a value exists in the array
* [`Array.prototype.filter()`](filter) – remove all non-matching elements
* [`Array.prototype.every()`](every) – test all elements
* [`Array.prototype.some()`](some) – test until one element matches
| programming_docs |
javascript Array.prototype.filter() Array.prototype.filter()
========================
The `filter()` method creates a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Try it
------
Syntax
------
```
// Arrow function
filter((element) => { /\* … \*/ })
filter((element, index) => { /\* … \*/ })
filter((element, index, array) => { /\* … \*/ })
// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
// Inline callback function
filter(function (element) { /\* … \*/ })
filter(function (element, index) { /\* … \*/ })
filter(function (element, index, array) { /\* … \*/ })
filter(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. It should return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) to keep the element in the resulting array, and a falsy value otherwise.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `filter()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
A [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.
Description
-----------
The `filter()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
The `filter()` method is a [copying method](../array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array (with some filtered out). However, the function provided as `callbackFn` can mutate the array. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `filter()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `filter()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
Examples
--------
### Filtering out all small values
The following example uses `filter()` to create a filtered array that has all elements with values less than `10` removed.
```
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
```
### Find all prime numbers in an array
The following example returns all prime numbers in the array:
```
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
```
### Filtering invalid entries from JSON
The following example uses `filter()` to create a filtered JSON of all elements with non-zero, numeric `id`.
```
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" },
];
let invalidEntries = 0;
function filterByID(item) {
if (Number.isFinite(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
const arrByID = arr.filter(filterByID);
console.log("Filtered Array\n", arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
console.log("Number of Invalid Entries = ", invalidEntries);
// Number of Invalid Entries = 5
```
### Searching in array
Following example uses `filter()` to filter array content based on search criteria.
```
const fruits = ["apple", "banana", "grapes", "mango", "orange"];
/\*\*
\* Filter array items based on search criteria (query)
\*/
function filterItems(arr, query) {
return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}
console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
```
### Using filter() on sparse arrays
`filter()` will skip empty slots.
```
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]
```
### Calling filter() on non-array objects
The `filter()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
};
console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));
// [ 'a', 'b' ]
```
### Affecting Initial Array (modifying, appending and deleting)
The following example tests the behavior of the `filter` method when the array is modified.
```
// Modifying each word
let words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const modifiedWords = words.filter((word, index, arr) => {
arr[index + 1] += " extra";
return word.length < 6;
});
console.log(modifiedWords);
// Notice there are three words below length 6, but since they've been modified one is returned
// ["spray"]
// Appending new words
words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const appendedWords = words.filter((word, index, arr) => {
arr.push("new");
return word.length < 6;
});
console.log(appendedWords);
// Only three fits the condition even though the `words` itself now has a lot more words with character length less than 6
// ["spray" ,"limit" ,"elite"]
// Deleting words
words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const deleteWords = words.filter((word, index, arr) => {
arr.pop();
return word.length < 6;
});
console.log(deleteWords);
// Notice 'elite' is not even obtained as it's been popped off 'words' before filter can even get there
// ["spray" ,"limit"]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.filter](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.filter) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `filter` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.filter` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.forEach()`](foreach)
* [`Array.prototype.every()`](every)
* [`Array.prototype.some()`](some)
* [`Array.prototype.reduce()`](reduce)
* [`Array.prototype.find()`](find)
javascript Array.prototype.forEach() Array.prototype.forEach()
=========================
The `forEach()` method executes a provided function once for each array element.
Try it
------
Syntax
------
```
// Arrow function
forEach((element) => { /\* … \*/ })
forEach((element, index) => { /\* … \*/ })
forEach((element, index, array) => { /\* … \*/ })
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function (element) { /\* … \*/ })
forEach(function (element, index) { /\* … \*/ })
forEach(function (element, index, array) { /\* … \*/ })
forEach(function (element, index, array) { /\* … \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to execute for each element in the array. Its return value is discarded.
The function is called with the following arguments:
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array `forEach()` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`. See [iterative methods](../array#iterative_methods).
### Return value
`undefined`.
Description
-----------
The `forEach()` method is an [iterative method](../array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike [`map()`](map), `forEach()` always returns [`undefined`](../undefined) and is not chainable. The typical use case is to execute side effects at the end of a chain.
`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays).
`forEach()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved *before* the first invocation of `callbackFn`. Therefore:
* `callbackFn` will not visit any elements added beyond the array's initial length when the call to `forEach()` began.
* Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again.
* If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](../../operators/delete) elements are not visited.
**Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
The `forEach()` method is [generic](../array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties.
There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool.
Early termination may be accomplished with looping statements like [`for`](../../statements/for), [`for...of`](../../statements/for...of), and [`for...in`](../../statements/for...in). Array methods like [`every()`](every), [`some()`](some), [`find()`](find), and [`findIndex()`](findindex) also stops iteration immediately when further iteration is not necessary.
`forEach()` expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as `forEach` callbacks.
```
const ratings = [5, 4, 5];
let sum = 0;
const sumFunction = async (a, b) => a + b;
ratings.forEach(async (rating) => {
sum = await sumFunction(sum, rating);
});
console.log(sum);
// Naively expected output: 14
// Actual output: 0
```
To run a series of asynchronous operations sequentially or concurrently, see [promise composition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#composition).
Examples
--------
### Using forEach() on sparse arrays
```
const arraySparse = [1, 3, /\* empty \*/, 7];
let numCallbackRuns = 0;
arraySparse.forEach((element) => {
console.log({ element });
numCallbackRuns++;
});
console.log({ numCallbackRuns });
// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
```
The callback function is not invoked for the missing value at index 2.
### Converting a for loop to forEach
```
const items = ["item1", "item2", "item3"];
const copyItems = [];
// before
for (let i = 0; i < items.length; i++) {
copyItems.push(items[i]);
}
// after
items.forEach((item) => {
copyItems.push(item);
});
```
### Printing the contents of an array
**Note:** In order to display the content of an array in the console, you can use [`console.table()`](https://developer.mozilla.org/en-US/docs/Web/API/console/table), which prints a formatted version of the array.
The following example illustrates an alternative approach, using `forEach()`.
The following code logs a line for each element in an array:
```
const logArrayElements = (element, index /\*, array \*/) => {
console.log(`a[${index}] = ${element}`);
};
// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// Logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
```
### Using thisArg
The following (contrived) example updates an object's properties from each entry in the array:
```
class Counter {
constructor() {
this.sum = 0;
this.count = 0;
}
add(array) {
// Only function expressions will have its own this binding
array.forEach(function countEntry(entry) {
this.sum += entry;
++this.count;
}, this);
}
}
const obj = new Counter();
obj.add([2, 5, 9]);
console.log(obj.count); // 3
console.log(obj.sum); // 16
```
Since the `thisArg` parameter (`this`) is provided to `forEach()`, it is passed to `callback` each time it's invoked. The callback uses it as its `this` value.
**Note:** If passing the callback function used an [arrow function expression](../../functions/arrow_functions), the `thisArg` parameter could be omitted, since all arrow functions lexically bind the [`this`](../../operators/this) value.
### An object copy function
The following code creates a copy of a given object.
There are different ways to create a copy of an object. The following is just one way and is presented to explain how `Array.prototype.forEach()` works by using `Object.*` utility functions.
```
const copy = (obj) => {
const copy = Object.create(Object.getPrototypeOf(obj));
const propNames = Object.getOwnPropertyNames(obj);
propNames.forEach((name) => {
const desc = Object.getOwnPropertyDescriptor(obj, name);
Object.defineProperty(copy, name, desc);
});
return copy;
};
const obj1 = { a: 1, b: 2 };
const obj2 = copy(obj1); // obj2 looks like obj1 now
```
### Modifying the array during iteration
The following example logs `one`, `two`, `four`.
When the entry containing the value `two` is reached, the first entry of the whole array is shifted off—resulting in all remaining entries moving up one position. Because element `four` is now at an earlier position in the array, `three` will be skipped.
`forEach()` does not make a copy of the array before iterating.
```
const words = ["one", "two", "three", "four"];
words.forEach((word) => {
console.log(word);
if (word === "two") {
words.shift(); //'one' will delete from array
}
}); // one // two // four
console.log(words); // ['two', 'three', 'four']
```
### Flatten an array
The following example is only here for learning purpose. If you want to flatten an array using built-in methods you can use [`Array.prototype.flat()`](flat).
```
const flatten = (arr) => {
const result = [];
arr.forEach((item) => {
if (Array.isArray(item)) {
result.push(...flatten(item));
} else {
result.push(item);
}
});
return result;
};
// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];
console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
### Calling forEach() on non-array objects
The `forEach()` method reads the `length` property of `this` and then accesses each integer index.
```
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
Array.prototype.forEach.call(arrayLike, (x) => console.log(x));
// 2
// 3
// 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-array.prototype.foreach](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.foreach) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `forEach` | 1 | 12 | 1.5 | 9 | 9.5 | 3 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `Array.prototype.forEach` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array)
* [`Array.prototype.find()`](find)
* [`Array.prototype.findIndex()`](findindex)
* [`Array.prototype.map()`](map)
* [`Array.prototype.filter()`](filter)
* [`Array.prototype.every()`](every)
* [`Array.prototype.some()`](some)
* [`Map.prototype.forEach()`](../map/foreach)
* [`Set.prototype.forEach()`](../set/foreach)
javascript AsyncGenerator.prototype.throw() AsyncGenerator.prototype.throw()
================================
The `throw()` method of an async generator acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.
Syntax
------
```
asyncGeneratorObject.throw(exception)
```
### Parameters
`exception` The exception to throw. For debugging purposes, it is useful to make it an `instanceof` [`Error`](../error).
### Return value
If the thrown error is not caught, it will return a [`Promise`](../promise) which rejects with the exception passed in.
If the exception is caught by a [`try...catch`](../../statements/try...catch) and the generator resumes to yield more values, it will return a [`Promise`](../promise) which resolves with an [`Object`](../object) with two properties:
`done` A boolean value:
* `true` if the generator function's control flow has reached the end.
* `false` if the generator function is able to produce more values.
`value` The value yielded from the next `yield` expression.
Examples
--------
### Using throw()
The following example shows a simple generator and an error that is thrown using the `throw` method. An error can be caught by a [`try...catch`](../../statements/try...catch) block as usual.
```
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}
async function\* createAsyncGenerator() {
while (true) {
try {
await sleep(500);
yield 42;
} catch (e) {
console.error(e);
}
}
}
const asyncGen = createAsyncGenerator();
asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }
asyncGen.throw(new Error('Something went wrong')) // Error: Something went wrong
.then((res) => console.log(res)); // { value: 42, done: false }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgenerator-prototype-throw](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgenerator-prototype-throw) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `throw` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*`](../../statements/async_function*)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
| programming_docs |
javascript AsyncGenerator.prototype.next() AsyncGenerator.prototype.next()
===============================
The `next()` method returns the next value in the sequence.
Syntax
------
```
asyncGeneratorObject.next()
asyncGeneratorObject.next(value)
```
### Parameters
`value` Optional
An optional value used to modify the internal state of the generator. A value passed to the `next()` method will be received by `yield`
### Return value
A [`Promise`](../promise) which when resolved returns an [`Object`](../object) with two properties:
`done` A boolean value:
* `true` if the generator is past the end of its control flow. In this case `value` specifies the *return value* of the generator (which may be undefined).
* `false` if the generator is able to produce more values.
`value` Any JavaScript value yielded or returned by the generator.
Examples
--------
### Using next()
The following example shows a simple generator and the object that the `next` method returns:
```
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(value), time);
});
}
async function\* createAsyncGenerator() {
yield delayedValue(500, 1);
yield delayedValue(500, 2);
yield delayedValue(500, 3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }
```
### Sending values to the generator
In this example, `next` is called with a value.
**Note:** The first call does not log anything, because the generator was not yielding anything initially.
```
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}
async function\* createAsyncGenerator() {
while (true) {
await sleep(500);
const value = yield;
console.log(value);
}
}
async function main() {
const asyncGen = createAsyncGenerator();
// No log at this step: the first value sent through `next` is lost
console.log(await asyncGen.next(1)); // { value: undefined, done: false }
// Logs 2: the value sent through `next`
console.log(await asyncGen.next(2)); // { value: undefined, done: false }
}
main();
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgenerator-prototype-next](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgenerator-prototype-next) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `next` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*`](../../statements/async_function*)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
javascript AsyncGenerator.prototype.return() AsyncGenerator.prototype.return()
=================================
The `return()` method of an async generator acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](../../statements/try...catch#the_finally-block) block.
Syntax
------
```
asyncGeneratorObject.return(value)
```
### Parameters
`value` The value to return.
### Return value
A [`Promise`](../promise) which resolves with an [`Object`](../object) with two properties:
`done` A boolean value:
* `true` if the generator function's control flow has reached the end.
* `false` if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the `return` is captured in a [`try...finally`](../../statements/try...catch#the_finally-block) and there are more `yield` expressions in the `finally` block.
`value` The value that is given as an argument, or, if the `yield` expression is wrapped in a [`try...finally`](../../statements/try...catch#the_finally-block), the value yielded/returned from the `finally` block.
Description
-----------
The `return()` method, when called, can be seen as if a `return value;` statement is inserted in the generator's body at the current suspended position, where `value` is the value passed to the `return()` method. Therefore, in a typical flow, calling `return(value)` will return `{ done: true, value: value }`. However, if the `yield` expression is wrapped in a `try...finally` block, the control flow doesn't exit the function body, but proceeds to the `finally` block instead. In this case, the value returned may be different, and `done` may even be `false`, if there are more `yield` expressions within the `finally` block.
Examples
--------
### Using return()
The following example shows a simple async generator and the `return` method.
```
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(value), time);
});
}
async function\* createAsyncGenerator() {
yield delayedValue(500, 1);
yield delayedValue(500, 2);
yield delayedValue(500, 3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.return('foo').then((res) => console.log(res)); // { value: "foo", done: true }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }
```
### Using return() once a generator is complete
If no `value` argument is passed into the `return()` method, the promise will resolve as if the [next()](next) method has been called. In this example the generator has completed, so the value returned is `undefined`.
`return()` can still be called after the generator is in a "completed" state, however the generator will stay in this state.
```
async function\* createAsyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
// value is returned undefined, as no value is passed and generator is 'done'
asyncGen.return().then((res) => console.log(res)); // { value: undefined, done: true }
// we can still return a value once the generator is complete
asyncGen.return(1).then((res) => console.log(res)); // { value: 1, done: true }
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-asyncgenerator-prototype-return](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-asyncgenerator-prototype-return) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `return` | 63 | 79 | 55 | No | 50 | 12 | 63 | 63 | 55 | 46 | 12 | 8.0 | 1.0 | 10.0.0
8.10.0 |
See also
--------
* [`async function*`](../../statements/async_function*)
* [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)
javascript Uint16Array() constructor Uint16Array() constructor
=========================
The `Uint16Array()` typed array constructor creates an array of 16-bit unsigned integers in the platform byte order.
Syntax
------
```
new Uint16Array()
new Uint16Array(length)
new Uint16Array(typedArray)
new Uint16Array(object)
new Uint16Array(buffer)
new Uint16Array(buffer, byteOffset)
new Uint16Array(buffer, byteOffset, length)
```
**Note:** `Uint16Array()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
See [`TypedArray`](../typedarray#parameters).
### Exceptions
See [`TypedArray`](../typedarray#exceptions).
Examples
--------
### Different ways to create a Uint16Array
```
// From a length
const uint16 = new Uint16Array(2);
uint16[0] = 42;
console.log(uint16[0]); // 42
console.log(uint16.length); // 2
console.log(uint16.BYTES\_PER\_ELEMENT); // 2
// From an array
const x = new Uint16Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint16Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Uint16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2
// From an iterable
const iterable = (function\* () {
yield\* [1, 2, 3];
})();
const uint16FromIterable = new Uint16Array(iterable);
console.log(uint16FromIterable);
// Uint16Array [1, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray-constructors](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray-constructors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `Uint16Array` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
| `constructor_without_parameters` | 7 | 12 | 55 | 10 | 11.6 | 5.1 | ≤37 | 18 | 55 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
| `iterable_allowed` | 39 | 14 | 52 | No | 26 | 10 | 39 | 39 | 52 | 26 | 10 | 4.0 | 1.0 | 4.0.0 |
| `new_required` | 7 | 14 | 44 | No | 15 | 5.1 | ≤37 | 18 | 44 | 14 | 5 | 1.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `Uint16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`ArrayBuffer`](../arraybuffer)
* [`DataView`](../dataview)
javascript WeakSet.prototype.has() WeakSet.prototype.has()
=======================
The `has()` method returns a boolean indicating whether an object exists in a `WeakSet` or not.
Try it
------
Syntax
------
```
has(value)
```
### Parameters
`value` Required. The object to test for presence in the `WeakSet`.
### Return value
Boolean Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`.
Examples
--------
### Using the `has()` method
```
const ws = new WeakSet();
const obj = {};
ws.add(window);
ws.has(window); // returns true
ws.has(obj); // returns false
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakset.prototype.has](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset.prototype.has) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `has` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`WeakSet`](../weakset)
* [`WeakSet.prototype.add()`](add)
* [`WeakSet.prototype.delete()`](delete)
javascript WeakSet.prototype.add() WeakSet.prototype.add()
=======================
The `add()` method appends a new object to the end of a `WeakSet` object.
Try it
------
Syntax
------
```
add(value)
```
### Parameters
value Required. The object to add to the `WeakSet` collection.
### Return value
The `WeakSet` object.
Examples
--------
### Using add
```
const ws = new WeakSet();
ws.add(window); // add the window object to the WeakSet
ws.has(window); // true
// WeakSet only takes objects as arguments
ws.add(1);
// results in "TypeError: Invalid value used in weak set" in Chrome
// and "TypeError: 1 is not a non-null object" in Firefox
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakset.prototype.add](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset.prototype.add) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `add` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`WeakSet`](../weakset)
* [`WeakSet.prototype.delete()`](delete)
* [`WeakSet.prototype.has()`](has)
javascript WeakSet() constructor WeakSet() constructor
=====================
The `WeakSet` constructor lets you create `WeakSet` objects that store weakly held *objects* in a collection.
Syntax
------
```
new WeakSet()
new WeakSet(iterable)
```
**Note:** `WeakSet()` can only be constructed with [`new`](../../operators/new). Attempting to call it without `new` throws a [`TypeError`](../typeerror).
### Parameters
`iterable` Optional
If an [iterable object](../../statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. null is treated as undefined.
Examples
--------
### Using the WeakSet object
```
const ws = new WeakSet();
const foo = {};
const bar = {};
ws.add(foo);
ws.add(bar);
ws.has(foo); // true
ws.has(bar); // true
ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained
```
Note that `foo !== bar`. While they are similar objects, *they are not **the same object***. And so they are both added to the set.
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakset-constructor](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset-constructor) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `WeakSet` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
| `iterable_allowed` | 38 | 12 | 34 | No | 25 | 9 | 38 | 38 | 34 | 25 | 9 | 3.0 | 1.0 | 0.12.0 |
| `null_allowed` | 36 | 12 | 37 | No | 23 | 9 | 37 | 36 | 37 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `WeakSet` in `core-js`](https://github.com/zloirock/core-js#weakset)
* [`WeakSet`](../weakset)
javascript WeakSet.prototype.delete() WeakSet.prototype.delete()
==========================
The `delete()` method removes the specified element from a `WeakSet` object.
Try it
------
Syntax
------
```
delete(value)
```
### Parameters
`value` Required. The object remove from the `WeakSet` object.
### Return value
`true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet` or if the `value` is not an object.
Examples
--------
### Using the delete() method
```
const ws = new WeakSet();
const obj = {};
ws.add(window);
ws.delete(obj); // Returns false. No obj found to be deleted.
ws.delete(window); // Returns true. Successfully removed.
ws.has(window); // Returns false. The window is no longer present in the WeakSet.
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-weakset.prototype.delete](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset.prototype.delete) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `delete` | 36 | 12 | 34 | No | 23 | 9 | 37 | 36 | 34 | 24 | 9 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [`WeakSet`](../weakset)
* [`WeakSet.prototype.add()`](add)
* [`WeakSet.prototype.has()`](has)
javascript TypedArray.prototype.sort() TypedArray.prototype.sort()
===========================
The `sort()` method sorts the elements of a typed array numerically *in place* and returns the typed array. This method has the same algorithm as [`Array.prototype.sort()`](../array/sort), except that sorts the values numerically instead of as strings. *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Functionless
sort()
// Arrow function
sort((a, b) => { /\* ... \*/ } )
// Compare function
sort(compareFn)
// Inline compare function
sort(function compareFn(a, b) { /\* ... \*/ })
```
### Parameters
`compareFunction` Optional
Specifies a function that defines the sort order.
### Return value
The sorted typed array.
Examples
--------
### Using sort
For more examples, see also the [`Array.prototype.sort()`](../array/sort) method.
```
let numbers = new Uint8Array([40, 1, 5, 200]);
numbers.sort();
// Uint8Array [ 1, 5, 40, 200 ]
// Unlike plain Arrays, a compare function is not required
// to sort the numbers numerically.
// Regular Arrays require a compare function to sort numerically:
numbers = [40, 1, 5, 200];
numbers.sort();
// [1, 200, 40, 5]
numbers.sort((a, b) => a - b); // compare numbers
// [ 1, 5, 40, 200 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.sort](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `sort` | 45 | 12 | 46 | No | 32 | 10 | 45 | 45 | 46 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.sort` with modern behavior like stable sort in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`Array.prototype.sort()`](../array/sort)
javascript TypedArray.prototype.join() TypedArray.prototype.join()
===========================
The `join()` method joins all elements of an array into a string. This method has the same algorithm as [`Array.prototype.join()`](../array/join). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
join()
join(separator)
```
### Parameters
`separator` Optional
Specifies a string to separate each element. The `separator` is converted to a string if necessary. If omitted, the typed array elements are separated with a comma (",").
### Return value
A string with all array elements joined.
Examples
--------
### Using join()
```
const uint8 = new Uint8Array([1, 2, 3]);
uint8.join(); // '1,2,3'
uint8.join(" / "); // '1 / 2 / 3'
uint8.join(""); // '123'
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.join](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `join` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.join` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray`](../typedarray)
* [`Array.prototype.join()`](../array/join)
| programming_docs |
javascript TypedArray.prototype.byteLength TypedArray.prototype.byteLength
===============================
The `byteLength` accessor property represents the length (in bytes) of the typed array.
Try it
------
Description
-----------
The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when a *TypedArray* is constructed and cannot be changed. If the *TypedArray* is not specifying a `byteOffset` or a `length`, the `length` of the referenced `ArrayBuffer` will be returned. *TypedArray* is one of the [TypedArray objects](../typedarray#typedarray_objects).
Examples
--------
### Using the byteLength property
```
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
uint8.byteLength; // 8 (matches the byteLength of the buffer)
const uint8newLength = new Uint8Array(buffer, 1, 5);
uint8newLength.byteLength; // 5 (as specified when constructing the Uint8Array)
const uint8offSet = new Uint8Array(buffer, 2);
uint8offSet.byteLength; // 6 (due to the offset of the constructed Uint8Array)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-%typedarray%.prototype.bytelength](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `byteLength` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
javascript TypedArray.prototype.fill() TypedArray.prototype.fill()
===========================
The `fill()` method fills all the elements of a typed array from a start index to an end index with a static value. This method has the same algorithm as [`Array.prototype.fill()`](../array/fill). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
fill(value)
fill(value, start)
fill(value, start, end)
```
### Parameters
`value` Value to fill the typed array with.
`start` Optional
Start index. Defaults to 0.
`end` Optional
End index (not included). Defaults to `this.length`.
### Return value
The modified array.
Description
-----------
The elements interval to fill is [`start`, `end`).
The `fill()` method takes up to three arguments `value`, `start` and `end`. The `start` and `end` arguments are optional with default values of `0` and the `length` of the `this` object.
If `start` is negative, it is treated as `length+start` where `length` is the length of the array. If `end` is negative, it is treated as `length+end`.
Examples
--------
### Using fill()
```
new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4]
new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4]
new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3]
new Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3]
new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.fill](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `fill` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.fill` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`Array.prototype.fill()`](../array/fill)
javascript TypedArray.prototype.map() TypedArray.prototype.map()
==========================
The `map()` method creates a new typed array with the results of calling a provided function on every element in this typed array. This method has the same algorithm as [`Array.prototype.map()`](../array/map). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Arrow function
map((currentValue) => { /\* ... \*/ } )
map((currentValue, index) => { /\* ... \*/ } )
map((currentValue, index, array) => { /\* ... \*/ } )
// Callback function
map(callbackFn)
map(callbackFn, thisArg)
// Inline callback function
map(function(currentValue) { /\* ... \*/ })
map(function(currentValue, index) { /\* ... \*/ })
map(function(currentValue, index, array){ /\* ... \*/ })
map(function(currentValue, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` A callback function that produces an element of the new typed array.
The function is called with the following arguments:
`currentValue` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `map()` was called upon.
`thisArg` Optional
Value to use as `this` when executing `callbackFn`.
### Return value
A new typed array.
Description
-----------
The `map()` method calls a provided callback function (`callbackFn`) once for each element in a typed array, in order, and constructs a new typed array from the results.
`callbackFn` is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes that are `undefined`, those which have been deleted, or which have never been assigned values.
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `map()`, it will be passed to `callbackFn` when invoked, for use as its `this` value. Otherwise, the value [`undefined`](../undefined) will be passed for use as its `this` value. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
`map()` does not mutate the typed array on which it is called (although `callbackFn`, if invoked, may do so).
The range of elements processed by `map()` is set before the first invocation of `callbackFn`. Elements which are appended to the array after the call to `map()` begins will not be visited by `callbackFn`. If existing elements of the typed array are changed, or deleted, their value as passed to `callbackFn` will be the value at the time `map()` visits them; elements that are deleted are not visited.
Examples
--------
### Mapping a typed array to a typed array of square roots
The following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.
```
const numbers = new Uint8Array([1, 4, 9]);
const roots = numbers.map(Math.sqrt);
// roots is now: Uint8Array [1, 2, 3],
// numbers is still Uint8Array [1, 4, 9]
```
### Mapping a typed array of numbers using a function containing an argument
The following code shows how `map()` works when a function requiring one argument is used with it. The argument will automatically be assigned to each element of the typed array as `map()` loops through the original typed array.
```
const numbers = new Uint8Array([1, 4, 9]);
const doubles = numbers.map((num) => num \* 2);
// doubles is now Uint8Array [2, 8, 18]
// numbers is still Uint8Array [1, 4, 9]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.map](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `map` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.map` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.filter()`](filter)
* [`Array.prototype.map()`](../array/map)
javascript TypedArray.prototype.toLocaleString() TypedArray.prototype.toLocaleString()
=====================================
The `toLocaleString()` method returns a string representing the elements of the typed array. The elements are converted to strings and are separated by a locale-specific string (such as a comma ","). This method has the same algorithm as [`Array.prototype.toLocaleString()`](../array/tolocalestring) and, as the typed array elements are numbers, the same algorithm as [`Number.prototype.toLocaleString()`](../number/tolocalestring) applies for each element. *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Syntax
------
```
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```
### Parameters
The `locales` and `options` arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the `locales` and `options` arguments, the locale used and the form of the string returned are entirely implementation dependent.
See the [`Intl.NumberFormat()`](../intl/numberformat/numberformat) constructor for details on these parameters and how to use them.
### Return value
A string representing the elements of the typed array.
Examples
--------
### Using toLocaleString
```
const uint = new Uint32Array([2000, 500, 8123, 12, 4212]);
uint.toLocaleString();
// if run in a de-DE locale
// "2.000,500,8.123,12,4.212"
uint.toLocaleString("en-US");
// "2,000,500,8,123,12,4,212"
uint.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });
// "¥2,000,¥500,¥8,123,¥12,¥4,212"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.tolocalestring](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toLocaleString` | 7 | 12 | 51 | 10 | 11.6 | 5.1 | ≤37 | 18 | 51 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`Array.prototype.toLocaleString()`](../array/tolocalestring)
* [`Number.prototype.toLocaleString()`](../number/tolocalestring)
javascript TypedArray.prototype.values() TypedArray.prototype.values()
=============================
The `values()` method returns a new *array iterator* object that contains the values for each index in the array.
Try it
------
Syntax
------
```
values()
```
### Return value
A new *array iterator* object.
Examples
--------
### Iteration using for...of loop
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
const values = arr.values();
for (const n of values) {
console.log(n);
}
```
### Alternative iteration
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
const values = arr.values();
console.log(values.next().value); // 10
console.log(values.next().value); // 20
console.log(values.next().value); // 30
console.log(values.next().value); // 40
console.log(values.next().value); // 50
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.values](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `values` | 38 | 12 | 37 | No | 25 | 10 | 38 | 38 | 37 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.values` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`TypedArray.prototype.entries()`](entries)
* [`TypedArray.prototype.keys()`](keys)
* [`TypedArray.prototype[@@iterator]()`](@@iterator)
javascript TypedArray.prototype.lastIndexOf() TypedArray.prototype.lastIndexOf()
==================================
The `lastIndexOf()` method returns the last index at which a given element can be found in the typed array, or -1 if it is not present. The typed array is searched backwards, starting at `fromIndex`. This method has the same algorithm as [`Array.prototype.lastIndexOf()`](../array/lastindexof). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
```
### Parameters
`searchElement` Element to locate in the typed array.
`fromIndex` Optional. The index at which to start searching backwards. Defaults to the typed array's length, i.e. the whole typed array will be searched. If the index is greater than or equal to the length of the typed array, the whole typed array will be searched. If negative, it is taken as the offset from the end of the typed array. Note that even when the index is negative, the typed array is still searched from back to front. If the calculated index is less than 0, -1 is returned, i.e. the typed array will not be searched.
### Return value
The last index of the element in the array; `-1` if not found.
Description
-----------
`lastIndexOf` compares `searchElement` to elements of the typed array using [strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using) (the same method used by the `===` operator).
Examples
--------
### Using lastIndexOf
```
const uint8 = new Uint8Array([2, 5, 9, 2]);
uint8.lastIndexOf(2); // 3
uint8.lastIndexOf(7); // -1
uint8.lastIndexOf(2, 3); // 3
uint8.lastIndexOf(2, 2); // 0
uint8.lastIndexOf(2, -2); // 0
uint8.lastIndexOf(2, -1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.lastindexof](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `lastIndexOf` | 45 | 12 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).lastIndexOf(0, -0)` will now always return `+0`. | No | 32 | 10 | 45 | 45 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).lastIndexOf(0, -0)` will now always return `+0`. | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.lastIndexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.indexOf()`](indexof)
* [`Array.prototype.lastIndexOf()`](../array/lastindexof)
javascript TypedArray.prototype.findIndex() TypedArray.prototype.findIndex()
================================
The `findIndex()` method returns an **index** in the typed array, if an element in the typed array satisfies the provided testing function. Otherwise -1 is returned.
See also the [`find()`](find) method, which returns the **value** of a found element in the typed array instead of its index.
Try it
------
Syntax
------
```
// Arrow function
findIndex((element) => { /\* ... \*/ } )
findIndex((element, index) => { /\* ... \*/ } )
findIndex((element, index, array) => { /\* ... \*/ } )
// Callback function
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
// Inline callback function
findIndex(function(element) { /\* ... \*/ })
findIndex(function(element, index) { /\* ... \*/ })
findIndex(function(element, index, array){ /\* ... \*/ })
findIndex(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` Function to execute on each value in the typed array.
The function is called with the following arguments:
`element` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `findIndex()` was called upon.
`thisArg` Optional
Object to use as `this` when executing `callbackFn`.
### Return value
An index in the array if an element passes the test; otherwise, `-1`.
Description
-----------
The `findIndex()` method executes the `callbackFn` function once for each element present in the typed array until it finds one where `callbackFn` returns a true value. If such an element is found, `findIndex()` immediately returns the index of that element. Otherwise, `findIndex()` returns -1. `callbackFn` is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `findIndex()`, it will be used as the `this` for each invocation of the `callback`. If it is not provided, then [`undefined`](../undefined) is used.
`findIndex()` does not mutate the typed array on which it is called.
The range of elements processed by `findIndex()` is set before the first invocation of `callbackFn`. Elements that are appended to the typed array after the call to `findIndex()` begins will not be visited by `callbackFn`. If an existing, unvisited element of the typed array is changed by `callbackFn`, its value passed to the visiting `callbackFn` will be the value at the time that `findIndex()` visits that element's index; elements that are deleted are not visited.
Examples
--------
### Find the index of a prime number in a typed array
The following example finds the index of an element in the typed array that is a prime number (or returns `-1` if there is no prime number).
```
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
const uint8 = new Uint8Array([4, 6, 8, 12]);
const uint16 = new Uint16Array([4, 6, 7, 12]);
console.log(uint8.findIndex(isPrime)); // -1, not found
console.log(uint16.findIndex(isPrime)); // 2
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.findindex](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findIndex` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.findIndex` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.find()`](find)
* [`TypedArray.prototype.indexOf()`](indexof)
javascript TypedArray.prototype.byteOffset TypedArray.prototype.byteOffset
===============================
The `byteOffset` accessor property represents the offset (in bytes) of a typed array from the start of its [`ArrayBuffer`](../arraybuffer).
Description
-----------
The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when a *TypedArray* is constructed and cannot be changed. *TypedArray* is one of the [TypedArray objects](../typedarray#typedarray_objects).
Examples
--------
### Using the byteOffset property
```
const buffer = new ArrayBuffer(8);
const uint8array1 = new Uint8Array(buffer);
uint8array1.byteOffset; // 0 (no offset specified)
const uint8array2 = new Uint8Array(buffer, 3);
uint8array2.byteOffset; // 3 (as specified when constructing Uint8Array)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-%typedarray%.prototype.byteoffset](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `byteOffset` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
| programming_docs |
javascript TypedArray.prototype.subarray() TypedArray.prototype.subarray()
===============================
The `subarray()` method returns a new *TypedArray* on the same [`ArrayBuffer`](../arraybuffer) store and with the same element types as for this *TypedArray* object. The begin offset is **inclusive** and the end offset is **exclusive**. *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects).
Try it
------
Syntax
------
```
subarray()
subarray(begin)
subarray(begin, end)
```
### Parameters
`begin` Optional
Element to begin at. The offset is inclusive. The whole array will be included in the new view if this value is not specified.
`end` Optional
Element to end at. The offset is exclusive. If not specified, all elements from the one specified by `begin` to the end of the array are included in the new view.
### Return value
A new [`TypedArray`](../typedarray) object.
Description
-----------
The range specified by `begin` and `end` is clamped to the valid index range for the current array; if the computed length of the new array would be negative, it's clamped to zero. If either `begin` or `end` is negative, it refers to an index from the end of the array instead of from the beginning.
Also note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa.
Examples
--------
### Using the subarray() method
```
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
uint8.set([1, 2, 3]);
console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]
const sub = uint8.subarray(0, 4);
console.log(sub); // Uint8Array [ 1, 2, 3, 0 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.subarray](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `subarray` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.subarray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`ArrayBuffer`](../arraybuffer)
javascript TypedArray.prototype.copyWithin() TypedArray.prototype.copyWithin()
=================================
The `copyWithin()` method copies the sequence of array elements within the array to the position starting at `target`. The copy is taken from the index positions of the second and third arguments `start` and `end`. The `end` argument is optional and defaults to the length of the array. This method has the same algorithm as [`Array.prototype.copyWithin`](../array/copywithin). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
copyWithin(target, start)
copyWithin(target, start, end)
```
### Parameters
`target` Target start index position where to copy the elements to.
`start` Source start index position where to start copying elements from.
`end` Optional
Optional. Source end index position where to end copying elements from.
### Return value
The modified array.
Description
-----------
See [`Array.prototype.copyWithin`](../array/copywithin) for more details.
Examples
--------
### Using copyWithin
```
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
uint8.set([1, 2, 3]);
console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]
uint8.copyWithin(3, 0, 3);
console.log(uint8); // Uint8Array [ 1, 2, 3, 1, 2, 3, 0, 0 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.copywithin](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `copyWithin` | 45 | 12 | 34 | No | 32 | 9.1 | 45 | 45 | 34 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.copyWithin` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray`](../typedarray)
javascript TypedArray.prototype.at() TypedArray.prototype.at()
=========================
The `at()` method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
This is not to suggest there is anything wrong with using the square bracket notation. For example `array[0]` would return the first item. However instead of using [`array.length`](length) for latter items; e.g. `array[array.length-1]` for the last item, you can call `array.at(-1)`. [(See the examples below)](#examples)
Try it
------
Syntax
------
```
at(index)
```
### Parameters
`index` The index (position) of the array element to be returned. Supports relative indexing from the end of the array when passed a negative index; that is, if a negative number is used, the element returned will be found by counting back from the end of the array.
### Return value
The element in the array matching the given index. Returns [`undefined`](../undefined) if the given index can not be found.
Examples
--------
### Return the last value of a typed array
The following example provides a function which returns the last element found in a specified array.
```
const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);
// A function which returns the last item of a given array
function returnLast(arr) {
return arr.at(-1);
}
const lastItem = returnLast(uint8);
console.log(lastItem); // 18
```
### Comparing methods
Here we compare different ways to select the penultimate (last but one) item of a [`TypedArray`](../typedarray). Whilst all below methods are valid, it highlights the succinctness and readability of the `at()` method.
```
// Our typed array with values
const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);
// Using length property
const lengthWay = uint8[uint8.length - 2];
console.log(lengthWay); // 11
// Using slice() method. Note an array is returned
const sliceWay = uint8.slice(-2, -1);
console.log(sliceWay[0]); // 11
// Using at() method
const atWay = uint8.at(-2);
console.log(atWay); // 11
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.at](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `at` | 92 | 92 | 90 | No | 78 | 15.4 | 92 | 92 | 90 | 65 | 15.4 | 16.0 | No | 16.6.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.at` in `core-js`](https://github.com/zloirock/core-js#relative-indexing-method)
* [A polyfill for the at() method](https://github.com/tc39/proposal-relative-indexing-method#polyfill).
* [`TypedArray.prototype.find()`](find) – return a value based on a given test.
* [`TypedArray.prototype.includes()`](includes) – test whether a value exists in the array.
* [`TypedArray.prototype.indexOf()`](indexof) – return the index of a given element.
javascript TypedArray.prototype.reduceRight() TypedArray.prototype.reduceRight()
==================================
The `reduceRight()` method applies a function against an accumulator and each value of the typed array (from right-to-left) has to reduce it to a single value. This method has the same algorithm as [`Array.prototype.reduceRight()`](../array/reduceright). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Syntax
------
```
// Arrow function
reduceRight((accumulator, currentValue) => { /\* ... \*/ } )
reduceRight((accumulator, currentValue, index) => { /\* ... \*/ } )
reduceRight((accumulator, currentValue, index, array) => { /\* ... \*/ } )
reduceRight((accumulator, currentValue, index, array) => { /\* ... \*/ }, initialValue)
// Callback function
reduceRight(callbackFn)
reduceRight(callbackFn, initialValue)
// Inline callback function
reduceRight(function(accumulator, currentValue) { /\* ... \*/ })
reduceRight(function(accumulator, currentValue, index) { /\* ... \*/ })
reduceRight(function(accumulator, currentValue, index, array){ /\* ... \*/ })
reduceRight(function(accumulator, currentValue, index, array) { /\* ... \*/ }, initialValue)
```
### Parameters
`callbackFn` Function to execute on each value in the typed array.
The function is called with the following arguments:
`accumulator` The value previously returned in the last invocation of the callback, or `initialValue`, if supplied (see below).
`currentValue` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `reduceRight()` was called upon.
`initialValue` Optional. Object to use as the first argument to the first call of the `callbackFn`.
### Return value
The value that results from the reduction.
Description
-----------
The `reduceRight` method executes the `callbackFn` function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous `callbackFn` call), the value of the current element, the current index, and the typed array over which iteration is occurring.
The call to the `reduceRight` callback would look something like this:
```
typedarray.reduceRight((accumulator, currentValue, index, typedarray) => {
// ...
});
```
The first time the function is called, the `accumulator` and `currentValue` can be one of two values. If an `initialValue` was provided in the call to `reduceRight`, then `accumulator` will be equal to `initialValue` and `currentValue` will be equal to the last value in the typed array. If no `initialValue` was provided, then `accumulator` will be equal to the last value in the typed array and `currentValue` will be equal to the second-to-last value.
If the typed array is empty and no `initialValue` was provided, [`TypeError`](../typeerror) would be thrown. If the typed array has only one element (regardless of position) and no `initialValue` was provided, or if `initialValue` is provided but the typed array is empty, the solo value would be returned without calling `callbackFn`.
Examples
--------
### Sum up all values within an array
```
const total = new Uint8Array([0, 1, 2, 3]).reduceRight((a, b) => a + b);
// total === 6
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.reduceright](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reduceRight` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.reduceRight` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.reduce()`](reduce)
* [`Array.prototype.reduceRight()`](../array/reduceright)
javascript TypedArray.prototype.reverse() TypedArray.prototype.reverse()
==============================
The `reverse()` method reverses a typed array in place. The first typed array element becomes the last and the last becomes the first. This method has the same algorithm as [`Array.prototype.reverse()`](../array/reverse). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
reverse()
```
### Return value
The reversed array.
Examples
--------
### Using reverse
```
const uint8 = new Uint8Array([1, 2, 3]);
uint8.reverse();
console.log(uint8); // Uint8Array [3, 2, 1]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.reverse](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reverse` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.reverse` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`Array.prototype.reverse()`](../array/reverse)
javascript TypedArray.prototype.findLastIndex() TypedArray.prototype.findLastIndex()
====================================
The `findLastIndex()` method iterates a [typed array](../typedarray#typedarray_objects) in reverse order and returns the index of the first element that satisfies the provided testing function. If no values satisfy the testing function, -1 is returned.
See also the [`findLast()`](findlast) method, which returns the value of the found element rather than its index.
Try it
------
Syntax
------
```
// Arrow function
findLastIndex((element) => { /\* ... \*/ } )
findLastIndex((element, index) => { /\* ... \*/ } )
findLastIndex((element, index, array) => { /\* ... \*/ } )
// Callback function
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
// Inline callback function
findLastIndex(function(element) { /\* ... \*/ })
findLastIndex(function(element, index) { /\* ... \*/ })
findLastIndex(function(element, index, array){ /\* ... \*/ })
findLastIndex(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` A function used to test elements in the typed array.
The function is called with the following arguments:
`element` The current element in the typed array.
`index` The index (position) of the current element in the typed array.
`array` The typed array that `findLastIndex()` was called on.
The callback must return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate an appropriate element has been found. The index of this element is returned by `findLastIndex()`.
`thisArg` Optional
Object to use as [`this`](../../operators/this) when executing `callbackFn`.
### Return value
The index of the last (highest-index) element in the array that passes the test. Otherwise -1 if no matching element is found.
Description
-----------
The `findLastIndex()` method executes the `callbackFn` function once for each index of the typed array in descending-index order until the `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `findLastIndex()` then returns the index of that element and stops iterating through the typed array. If `callbackFn` never returns a truthy value, `findLastIndex()` returns [`undefined`](../undefined).
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `findLastIndex()`, it will be used as the `this` for each invocation of the `callbackFn`. If it is not provided, then [`undefined`](../undefined) is used.
The `findLastIndex()` method does not mutate the typed array on which it is called, but the function provided to `callbackFn` can.
The range of elements processed by `findLastIndex()` is set before the first invocation of `callbackFn`. Elements that are appended to the typed array after the call to `findLastIndex()` begins will not be visited by `callbackFn`. If an existing, unvisited element of the typed array is changed by `callbackFn`, its value passed to the visiting `callbackFn` will be the value at the time that `findLastIndex()` visits that element's index.
**Warning:** Concurrent modification of the kind described in the previous paragraph frequently leads to hard-to-understand code and is generally to be avoided (except in special cases).
Examples
--------
### Find the index of a prime number in a typed array
The following example finds the index of the last element in the typed array that is a prime number (or returns `-1` if there is no prime number).
```
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
let uint8 = new Uint8Array([4, 6, 8, 12]);
console.log(uint8.findLastIndex(isPrime));
// -1 (no primes in array)
uint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]);
console.log(uint8.findLastIndex(isPrime));
// 11
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.findlastindex](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findLastIndex` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | No |
See also
--------
* [Polyfill of `TypedArray.prototype.findLastIndex` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.findLast()`](findlast)
* [`TypedArray.prototype.findIndex()`](findindex)
* [`TypedArray.prototype.indexOf()`](indexof)
javascript TypedArray.prototype.length TypedArray.prototype.length
===========================
The `length` accessor property represents the length (in elements) of a typed array.
Try it
------
Description
-----------
The `length` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when a *TypedArray* is constructed and cannot be changed. If the *TypedArray* is not specifying a `byteOffset` or a `length`, the length of the referenced [`ArrayBuffer`](../arraybuffer) will be returned. *TypedArray* is one of the [TypedArray objects](../typedarray#typedarray_objects).
Examples
--------
### Using the `length` property
```
const buffer = new ArrayBuffer(8);
let uint8 = new Uint8Array(buffer);
uint8.length; // 8 (matches the length of the buffer)
uint8 = new Uint8Array(buffer, 1, 5);
uint8.length; // 5 (as specified when constructing the Uint8Array)
uint8 = new Uint8Array(buffer, 2);
uint8.length; // 6 (due to the offset of the constructed Uint8Array)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-%typedarray%.prototype.length](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `length` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
| programming_docs |
javascript TypedArray.prototype.keys() TypedArray.prototype.keys()
===========================
The `keys()` method returns a new *array iterator* object that contains the keys for each index in the array.
Try it
------
Syntax
------
```
keys()
```
### Return value
A new *array iterator* object.
Examples
--------
### Iteration using for...of loop
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
const arrKeys = arr.keys();
for (const n of arrKeys) {
console.log(n);
}
```
### Alternative iteration
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
const arrKeys = arr.keys();
console.log(arrKeys.next().value); // 0
console.log(arrKeys.next().value); // 1
console.log(arrKeys.next().value); // 2
console.log(arrKeys.next().value); // 3
console.log(arrKeys.next().value); // 4
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.keys](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `keys` | 38 | 12 | 37 | No | 25 | 10 | 38 | 38 | 37 | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.keys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`TypedArray.prototype.entries()`](entries)
* [`TypedArray.prototype.values()`](values)
* [`TypedArray.prototype[@@iterator]()`](@@iterator)
* [for...of](../../statements/for...of)
* [Iteration protocols](../../iteration_protocols)
javascript TypedArray.prototype.find() TypedArray.prototype.find()
===========================
The `find()` method returns a value of an element in the typed array, if it satisfies the provided testing function. Otherwise [`undefined`](../undefined) is returned. *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
See also the [`findIndex()`](findindex) method, which returns the **index** of a found element in the typed array instead of its value.
Try it
------
Syntax
------
```
// Arrow function
find((element) => { /\* ... \*/ } )
find((element, index) => { /\* ... \*/ } )
find((element, index, array) => { /\* ... \*/ } )
// Callback function
find(callbackFn)
find(callbackFn, thisArg)
// Inline callback function
find(function(element) { /\* ... \*/ })
find(function(element, index) { /\* ... \*/ })
find(function(element, index, array){ /\* ... \*/ })
find(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` Function to execute on each value in the typed array.
The function is called with the following arguments:
`element` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The array `find()` was called upon.
`thisArg` Optional
Object to use as `this` when executing `callbackFn`.
### Return value
A value in the array if an element passes the test; otherwise, [`undefined`](../undefined).
Description
-----------
The `find()` method executes the `callbackFn` function once for each element present in the typed array until it finds one where `callbackFn` returns a true value. If such an element is found, `find()` immediately returns the value of that element. Otherwise, `find()` returns [`undefined`](../undefined). `callbackFn` is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `find()`, it will be used as the `this` for each invocation of the `callbackFn`. If it is not provided, then [`undefined`](../undefined) is used.
`find()` does not mutate the typed array on which it is called.
The range of elements processed by `find()` is set before the first invocation of `callbackFn`. Elements that are appended to the typed array after the call to `find()` begins will not be visited by `callbackFn`. If an existing, unvisited element of the typed array is changed by `callbackFn`, its value passed to the visiting `callbackFn` will be the value at the time that `find()` visits that element's index; elements that are deleted are not visited.
Examples
--------
### Find a prime number in a typed array
The following example finds an element in the typed array that is a prime number (or returns [`undefined`](../undefined) if there is no prime number).
```
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
const uint8 = new Uint8Array([4, 5, 8, 12]);
console.log(uint8.find(isPrime)); // 5
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.find](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `find` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.find` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.findIndex()`](findindex)
* [`TypedArray.prototype.every()`](every)
javascript TypedArray.prototype.reduce() TypedArray.prototype.reduce()
=============================
The `reduce()` method applies a function against an accumulator and each value of the typed array (from left-to-right) has to reduce it to a single value. This method has the same algorithm as [`Array.prototype.reduce()`](../array/reduce). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Arrow function
reduce((accumulator, currentValue) => { /\* ... \*/ } )
reduce((accumulator, currentValue, index) => { /\* ... \*/ } )
reduce((accumulator, currentValue, index, array) => { /\* ... \*/ } )
reduce((accumulator, currentValue, index, array) => { /\* ... \*/ }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function(accumulator, currentValue) { /\* ... \*/ })
reduce(function(accumulator, currentValue, index) { /\* ... \*/ })
reduce(function(accumulator, currentValue, index, array){ /\* ... \*/ })
reduce(function(accumulator, currentValue, index, array) { /\* ... \*/ }, initialValue)
```
### Parameters
`callbackFn` Function to execute on each value in the typed array.
The function is called with the following arguments:
`accumulator` The value previously returned in the last invocation of the callback, or `initialValue`, if supplied (see below).
`currentValue` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `reduce()` was called upon.
`initialValue` Optional. Object to use as the first argument to the first call of the `callbackFn`.
### Return value
The value that results from the reduction.
Description
-----------
The `reduce` method executes the `callbackFn` function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous `callbackFn` call), the value of the current element, the current index, and the typed array over which iteration is occurring.
The first time the callback is called, `accumulator` and `currentValue` can be one of two values. If `initialValue` is provided in the call to `reduce`, then `accumulator` will be equal to `initialValue` and `currentValue` will be equal to the first value in the typed array. If no `initialValue` was provided, then `accumulator` will be equal to the first value in the typed array and `currentValue` will be equal to the second.
If the typed array is empty and no `initialValue` was provided, [`TypeError`](../typeerror) would be thrown. If the typed array has only one element (regardless of position) and no `initialValue` was provided, or if `initialValue` is provided but the typed array is empty, the solo value would be returned without calling `callbackFn`.
Examples
--------
### Sum up all values within an array
```
const total = new Uint8Array([0, 1, 2, 3]).reduce((a, b) => a + b);
// total === 6
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.reduce](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `reduce` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.reduce` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.reduceRight()`](reduceright)
* [`Array.prototype.reduce()`](../array/reduce)
javascript TypedArray.prototype[@@iterator]() TypedArray.prototype[@@iterator]()
==================================
The `@@iterator` method of a `TypedArray` object implements the [iterable protocol](../../iteration_protocols) and allows typed arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](../../operators/spread_syntax) and [`for...of`](../../statements/for...of) loops. It returns an iterator that yields the value of each index in the typed array.
The initial value of this property is the same function object as the initial value of the [`TypedArray.prototype.values`](values) property.
Syntax
------
```
typedArray[Symbol.iterator]()
```
### Return value
The same return value as [`TypedArray.prototype.values()`](values): a new iterable iterator object that yields the value of each index in the typed array.
Examples
--------
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes typed arrays [iterable](../../iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically calls this method to obtain the iterator to loop over.
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
for (const n of arr) {
console.log(n);
}
```
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```
const arr = new Uint8Array([10, 20, 30, 40, 50]);
const arrIter = arr[Symbol.iterator]();
console.log(arrIter.next().value); // 10
console.log(arrIter.next().value); // 20
console.log(arrIter.next().value); // 30
console.log(arrIter.next().value); // 40
console.log(arrIter.next().value); // 50
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype-@@iterator](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@iterator` | 38 | 12 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | No | 25 | 10 | 38 | 38 | 36
27-36
A placeholder property named `@@iterator` is used.
17-27
A placeholder property named `iterator` is used. | 25 | 10 | 3.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `TypedArray.prototype[@@iterator]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`TypedArray.prototype.entries()`](entries)
* [`TypedArray.prototype.keys()`](keys)
* [`TypedArray.prototype.values()`](values)
javascript TypedArray.prototype.slice() TypedArray.prototype.slice()
============================
The `slice()` method returns a new typed array (with a new underlying buffer), that contains a copy of a portion of the original typed array. This method has the same algorithm as [`Array.prototype.slice()`](../array/slice). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
slice()
slice(start)
slice(start, end)
```
### Parameters
`start` Optional
Zero-based index at which to begin extraction.
A negative index can be used, indicating an offset from the end of the sequence. `slice(-2)` extracts the last two elements in the sequence.
If `start` is undefined, `slice` begins from index `0`.
`end` Optional
Zero-based index *before* which to end extraction. `slice` extracts up to but not including `end`.
For example, `slice(1,4)` extracts the second element through the fourth element (elements indexed 1, 2, and 3).
A negative index can be used, indicating an offset from the end of the sequence. `slice(2,-1)` extracts the third element through the second-to-last element in the sequence.
If `end` is omitted, `slice` extracts through the end of the sequence (`typedarray.length`).
### Return value
A new typed array containing the extracted elements.
Description
-----------
The `slice` method does not alter the original typed array, but instead returns a copy of a portion of the original typed array. As typed arrays only store primitive values, the copy the `slice` method returns is always a [deep copy](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy).
If an element is changed in either typed array, the other typed array is not affected.
Examples
--------
### Return a portion of an existing typed array
```
const uint8 = new Uint8Array([1, 2, 3]);
uint8.slice(1); // Uint8Array [ 2, 3 ]
uint8.slice(2); // Uint8Array [ 3 ]
uint8.slice(-2); // Uint8Array [ 2, 3 ]
uint8.slice(0, 1); // Uint8Array [ 1 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.slice](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `slice` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.slice` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`Array.prototype.slice()`](../array/slice)
javascript TypedArray.BYTES_PER_ELEMENT TypedArray.BYTES\_PER\_ELEMENT
==============================
The `TypedArray.BYTES_PER_ELEMENT` property represents the size in bytes of each element in a typed array.
Try it
------
Value
-----
A number whose value depends on the type of `TypedArray`.
| Property attributes of `TypedArray.BYTES_PER_ELEMENT` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`TypedArray` objects differ from each other in the number of bytes per element and in the way the bytes are interpreted. The `BYTES_PER_ELEMENT` constant contains the number of bytes each element in the given `TypedArray` has.
The `BYTES_PER_ELEMENT` property is both an *instance property* and a *static property*. It's available on both `TypedArray` subclass constructors and on instances of those constructors.
As an instance property, `BYTES_PER_ELEMENT` is defined on the constructor's `prototype`.
```
console.log(Object.hasOwn(Int8Array.prototype, "BYTES\_PER\_ELEMENT")); // true
```
Examples
--------
### Using BYTES\_PER\_ELEMENT
As a static property:
```
Int8Array.BYTES\_PER\_ELEMENT; // 1
Uint8Array.BYTES\_PER\_ELEMENT; // 1
Uint8ClampedArray.BYTES\_PER\_ELEMENT; // 1
Int16Array.BYTES\_PER\_ELEMENT; // 2
Uint16Array.BYTES\_PER\_ELEMENT; // 2
Int32Array.BYTES\_PER\_ELEMENT; // 4
Uint32Array.BYTES\_PER\_ELEMENT; // 4
Float32Array.BYTES\_PER\_ELEMENT; // 4
Float64Array.BYTES\_PER\_ELEMENT; // 8
BigInt64Array.BYTES\_PER\_ELEMENT; // 8
BigUint64Array.BYTES\_PER\_ELEMENT; // 8
```
As an instance property:
```
new Int8Array([]).BYTES\_PER\_ELEMENT; // 1
new Uint8Array([]).BYTES\_PER\_ELEMENT; // 1
new Uint8ClampedArray([]).BYTES\_PER\_ELEMENT; // 1
new Int16Array([]).BYTES\_PER\_ELEMENT; // 2
new Uint16Array([]).BYTES\_PER\_ELEMENT; // 2
new Int32Array([]).BYTES\_PER\_ELEMENT; // 4
new Uint32Array([]).BYTES\_PER\_ELEMENT; // 4
new Float32Array([]).BYTES\_PER\_ELEMENT; // 4
new Float64Array([]).BYTES\_PER\_ELEMENT; // 8
new BigInt64Array([]).BYTES\_PER\_ELEMENT; // 8
new BigUint64Array([]).BYTES\_PER\_ELEMENT; // 8
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-typedarray.bytes\_per\_element](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-typedarray.bytes_per_element) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `BYTES_PER_ELEMENT` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
javascript TypedArray.prototype.some() TypedArray.prototype.some()
===========================
The `some()` method tests whether some element in the typed array passes the test implemented by the provided function. This method has the same algorithm as [`Array.prototype.some()`](../array/some). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Arrow function
some((element) => { /\* ... \*/ } )
some((element, index) => { /\* ... \*/ } )
some((element, index, array) => { /\* ... \*/ } )
// Callback function
some(callbackFn)
some(callbackFn, thisArg)
// Inline callback function
some(function(element) { /\* ... \*/ })
some(function(element, index) { /\* ... \*/ })
some(function(element, index, array){ /\* ... \*/ })
some(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` Function to test for each element.
The function is called with the following arguments:
`element` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `some` was called upon.
`thisArg` Optional. Value to use as `this` when executing `callback`.
### Return value
`true` if the callback function returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for any array element; otherwise, `false`.
Description
-----------
The `some` method executes the `callbackFn` function once for each element present in the typed array until it finds one where `callbackFn` returns a true value. If such an element is found, `some` immediately returns `true`. Otherwise, `some` returns `false`.
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed.
If a `thisArg` parameter is provided to `some`, it will be passed to `callbackFn` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
`some` does not mutate the typed array on which it is called.
Examples
--------
### Testing size of all typed array elements
The following example tests whether any element in the typed array is bigger than 10.
```
function isBiggerThan10(element, index, array) {
return element > 10;
}
new Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false
new Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true
```
### Testing typed array elements using arrow functions
[Arrow functions](../../functions/arrow_functions) provide a shorter syntax for the same test.
```
new Uint8Array([2, 5, 8, 1, 4]).some((elem) => elem > 10); // false
new Uint8Array([12, 5, 8, 1, 4]).some((elem) => elem > 10); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.some](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `some` | 45 | 12 | 37 | No | 32 | 10 | 45 | 45 | 37 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.some` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.every()`](every)
* [`Array.prototype.some()`](../array/some)
| programming_docs |
javascript TypedArray.prototype.includes() TypedArray.prototype.includes()
===============================
The `includes()` method determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. This method has the same algorithm as [`Array.prototype.includes()`](../array/includes). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
includes(searchElement)
includes(searchElement, fromIndex)
```
### Parameters
`searchElement` The element to search for.
`fromIndex` Optional
The position in this array at which to begin searching for `searchElement`; defaults to 0.
### Return value
A [`Boolean`](../boolean).
Examples
--------
### Using includes
```
const uint8 = new Uint8Array([1, 2, 3]);
uint8.includes(2); // true
uint8.includes(4); // false
uint8.includes(3, 3); // false
// NaN handling (only true for Float32 and Float64)
new Uint8Array([NaN]).includes(NaN); // false, since the NaN passed to the constructor gets converted to 0
new Float32Array([NaN]).includes(NaN); // true;
new Float64Array([NaN]).includes(NaN); // true;
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.includes](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `includes` | 47 | 14 | 43 | No | 34 | 10 | 47 | 47 | 43 | 34 | 10 | 5.0 | 1.0 | 6.0.0
5.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.includes` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`Array.prototype.includes()`](../array/includes)
* [`String.prototype.includes()`](../string/includes)
* [`TypedArray.prototype.indexOf()`](indexof)
javascript TypedArray.name TypedArray.name
===============
The `TypedArray.name` property represents a string value of the typed array constructor name.
Try it
------
Value
-----
A string whose value depends on the type of `TypedArray`.
| Property attributes of `TypedArray.name` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
-----------
`TypedArray` objects differ from each other in the number of bytes per element and in the way the bytes are interpreted. The `name` property describes what data type the array consists of. It has three parts:
* The first part can be `Int` for *integer*, `Uint` for *unsigned integer*, or `Float` for *floating point*.
* The second part is a number describing the bit size of each element. Since 64-bit integers are too large to be represented without loss of precision with JavaScript numbers, the elements are stored as [`BigInt`](../bigint) values instead, and the first part is prefixed with "Big", becoming either `BigInt` or `BigUint`.
* Finally, the name terminates with `Array` or `ClampedArray`. [`Uint8ClampedArray`](../uint8clampedarray) has details about *clamped arrays*.
Examples
--------
### Using name
```
Int8Array.name; // "Int8Array"
Uint8Array.name; // "Uint8Array"
Uint8ClampedArray.name; // "Uint8ClampedArray"
Int16Array.name; // "Int16Array"
Uint16Array.name; // "Uint16Array"
Int32Array.name; // "Int32Array"
Uint32Array.name; // "Uint32Array"
Float32Array.name; // "Float32Array"
Float64Array.name; // "Float64Array"
BigInt64Array.name; // "BigInt64Array"
BigUint64Array.name; // "BigUint64Array"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-properties-of-the-typedarray-constructors](https://tc39.es/ecma262/multipage/indexed-collections.html#sec-properties-of-the-typedarray-constructors) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `name` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
javascript TypedArray.prototype.entries() TypedArray.prototype.entries()
==============================
The `entries()` method returns a new [`Array`](../array) iterator object that contains the key/value pairs for each index in the array.
Try it
------
Syntax
------
```
entries()
```
### Return value
A new *array iterator* object.
Examples
--------
### Iteration using for...of loop
```
const array = new Uint8Array([10, 20, 30, 40, 50]);
const arrayEntries = arr.entries();
for (const element of arrayEntries) {
console.log(element);
}
```
### Alternative iteration
```
const array = new Uint8Array([10, 20, 30, 40, 50]);
const arrayEntries = arr.entries();
console.log(arrayEntries.next().value); // [0, 10]
console.log(arrayEntries.next().value); // [1, 20]
console.log(arrayEntries.next().value); // [2, 30]
console.log(arrayEntries.next().value); // [3, 40]
console.log(arrayEntries.next().value); // [4, 50]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.entries](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `entries` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 0.12.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.entries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`TypedArray.prototype.keys()`](keys)
* [`TypedArray.prototype.values()`](values)
* [`TypedArray.prototype[@@iterator]()`](@@iterator)
javascript get TypedArray[@@species] get TypedArray[@@species]
=========================
The `TypedArray[@@species]` accessor property returns the constructor used to construct return values from typed array methods.
**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible.
Syntax
------
```
TypedArray[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from typed array methods that create new typed arrays.
Description
-----------
The `@@species` accessor property returns the default constructor for [typed array](../typedarray#typedarray_objects) objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
```
// Hypothetical underlying implementation for illustration
class TypedArray {
static get [Symbol.species]() {
return this;
}
}
```
Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.
```
class SubTypedArray extends Int8Array {}
SubTypedArray[Symbol.species] === SubTypedArray; // true
```
When calling typed array methods that do not mutate the existing array but return a new array instance (for example, [`filter()`](filter) and [`map()`](map)), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the typed array method.
However, unlike [`Array[@@species]`](../array/@@species), when using `@@species` to create new typed arrays, the language will make sure that the newly created array is a proper typed array and has the same content type as the original array — for example, you can't create a [`BigInt64Array`](../bigint64array) from a [`Float64Array`](../float64array), or create a non-BigInt array from a BigInt array. Doing so throws a [`TypeError`](../typeerror).
```
class BadArray extends Int8Array {
static get [Symbol.species]() {
return Array;
}
}
new BadArray(1).map(() => 0); // TypeError: Method %TypedArray%.prototype.map called on incompatible receiver [object Array]
class BadArray2 extends Int8Array {
static get [Symbol.species]() {
return BigInt64Array;
}
}
new BadArray2(1).map(() => 0n); // TypeError: TypedArray.prototype.map constructed typed array of different content type from |this|
```
**Note:** Due to a bug in both [SpiderMonkey](https://bugzilla.mozilla.org/show_bug.cgi?id=1640194) and V8, the content type match is not checked. Only Safari will throw a [`TypeError`](../typeerror) in the second example.
Examples
--------
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is one of the typed array constructors itself for any given [typed array](../typedarray#typedarray_objects) constructor.
```
Int8Array[Symbol.species]; // function Int8Array()
Uint8Array[Symbol.species]; // function Uint8Array()
Float32Array[Symbol.species]; // function Float32Array()
```
### Species in derived objects
In an instance of a custom `TypedArray` subclass, such as `MyTypedArray`, the `MyTypedArray` species is the `MyTypedArray` constructor. However, you might want to overwrite this, in order to return a parent [typed array](../typedarray#typedarray_objects) object in your derived class methods:
```
class MyTypedArray extends Uint8Array {
// Overwrite MyTypedArray species to the parent Uint8Array constructor
static get [Symbol.species]() {
return Uint8Array;
}
}
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-%typedarray%-@@species](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `@@species` | 51 | 13 | 48 | No | 38 | 10 | 51 | 51 | 48 | 41 | 10 | 5.0 | 1.0 | 6.5.0
6.0.0 |
See also
--------
* [`TypedArray`](../typedarray)
* [`Symbol.species`](../symbol/species)
javascript TypedArray.prototype.indexOf() TypedArray.prototype.indexOf()
==============================
The `indexOf()` method returns the first index at which a given element can be found in the typed array, or -1 if it is not present. This method has the same algorithm as [`Array.prototype.indexOf()`](../array/indexof). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
indexOf(searchElement)
indexOf(searchElement, fromIndex)
```
### Parameters
`searchElement` Element to locate in the typed array.
`fromIndex` Optional
The index to start the search at. If the index is greater than or equal to the typed array's length, -1 is returned, which means the typed array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the typed array. Note: if the provided index is negative, the typed array is still searched from front to back. If the calculated index is less than 0, then the whole typed array will be searched. Default: 0 (entire typed array is searched).
### Return value
The first index of the element in the array; `-1` if not found.
Description
-----------
`indexOf` compares `searchElement` to elements of the typed array using [strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using) (the same method used by the `===` operator).
Examples
--------
### Using indexOf
```
const uint8 = new Uint8Array([2, 5, 9]);
uint8.indexOf(2); // 0
uint8.indexOf(7); // -1
uint8.indexOf(9, 2); // 2
uint8.indexOf(2, -1); // -1
uint8.indexOf(2, -3); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.indexof](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `indexOf` | 45 | 12 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).indexOf(0, -0)` will now always return `+0`. | No | 32 | 9.1 | 45 | 45 | 37
Starting with Firefox 47, this method will no longer return `-0`. For example, `new Uint8Array([0]).indexOf(0, -0)` will now always return `+0`. | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.indexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.lastIndexOf()`](lastindexof)
* [`Array.prototype.indexOf()`](../array/indexof)
javascript TypedArray.from() TypedArray.from()
=================
The `TypedArray.from()` static method creates a new [typed array](../typedarray#typedarray_objects) from an array-like or iterable object. This method is nearly the same as [`Array.from()`](../array/from).
Try it
------
Syntax
------
```
// Arrow function
TypedArray.from(arrayLike, (element) => { /\* ... \*/ } )
TypedArray.from(arrayLike, (element, index) => { /\* ... \*/ } )
// Mapping function
TypedArray.from(arrayLike, mapFn)
TypedArray.from(arrayLike, mapFn, thisArg)
// Inline mapping function
TypedArray.from(arrayLike, function mapFn(element) { /\* ... \*/ })
TypedArray.from(arrayLike, function mapFn(element, index) { /\* ... \*/ })
TypedArray.from(arrayLike, function mapFn(element) { /\* ... \*/ }, thisArg)
TypedArray.from(arrayLike, function mapFn(element, index) { /\* ... \*/ }, thisArg)
```
Where `TypedArray` is one of:
* [`Int8Array`](../int8array)
* [`Uint8Array`](../uint8array)
* [`Uint8ClampedArray`](../uint8clampedarray)
* [`Int16Array`](../int16array)
* [`Uint16Array`](../uint16array)
* [`Int32Array`](../int32array)
* [`Uint32Array`](../uint32array)
* [`Float32Array`](../float32array)
* [`Float64Array`](../float64array)
* [`BigInt64Array`](../bigint64array)
* [`BigUint64Array`](../biguint64array)
### Parameters
`arrayLike` An array-like or iterable object to convert to a typed array.
`mapFn` Optional
Map function to call on every element of the typed array.
`thisArg` Optional
Value to use as `this` when executing `mapFn`.
### Return value
A new [`TypedArray`](../typedarray) instance.
Description
-----------
`TypedArray.from()` lets you create typed arrays from:
* array-like objects (objects with a `length` property and indexed elements); or
* [iterable objects](../../iteration_protocols) (objects where you can get its elements, such as [`Map`](../map) and [`Set`](../set)).
`TypedArray.from()` has the optional parameter `mapFn`, which allows you to execute a [`map()`](../array/map) function on each element of the typed array (or subclass object) that is being created. This means that the following are equivalent:
* `TypedArray.from(obj, mapFn, thisArg)`
* `TypedArray.from(Array.prototype.map.call(obj, mapFn, thisArg))`.
The `length` property of the `from()` method is `1`.
### Differences from Array.from()
Some subtle distinctions between [`Array.from()`](../array/from) and `TypedArray.from()`:
* If the `thisArg` value passed to `TypedArray.from()` is not a constructor, `TypedArray.from()` will throw a [`TypeError`](../typeerror), where `Array.from()` defaults to creating a new [`Array`](../array).
* `TypedArray.from()` uses `[[Set]]` where `Array.from()` uses `[[DefineOwnProperty]]`. Hence, when working with [`Proxy`](../proxy) objects, it calls [`handler.set()`](../proxy/proxy/set) to create new elements rather than [`handler.defineProperty()`](../proxy/proxy/defineproperty).
* When the `source` parameter is an iterator, the `TypedArray.from()` first collects all the values from the iterator, then creates an instance of `thisArg` using the count, then sets the values on the instance. `Array.from()` sets each value as it receives them from the iterator, then sets its `length` at the end.
* When `Array.from()` gets an array-like which isn't an iterator, it respects holes. `TypedArray.from()` will ensure the result is dense.
Examples
--------
### From an iterable object (Set)
```
const s = new Set([1, 2, 3]);
Uint8Array.from(s);
// Uint8Array [ 1, 2, 3 ]
```
### From a string
```
Int16Array.from("123");
// Int16Array [ 1, 2, 3 ]
```
### Use with arrow function and map
Using an arrow function as the map function to manipulate the elements
```
Float32Array.from([1, 2, 3], (x) => x + x);
// Float32Array [ 2, 4, 6 ]
```
### Generate a sequence of numbers
```
Uint8Array.from({ length: 5 }, (v, k) => k);
// Uint8Array [ 0, 1, 2, 3, 4 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.from](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `from` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.from` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.of()`](of)
* [`Array.from()`](../array/from)
* [`Array.prototype.map()`](../array/map)
* [A polyfill](https://github.com/behnammodi/polyfill/blob/v0.0.1/int-8-array.polyfill.js)
javascript TypedArray.of() TypedArray.of()
===============
The `TypedArray.of()` static method creates a new [typed array](../typedarray#typedarray_objects) from a variable number of arguments. This method is nearly the same as [`Array.of()`](../array/of).
Try it
------
Syntax
------
```
TypedArray.of(element0)
TypedArray.of(element0, element1)
TypedArray.of(element0, element1, /\* ... ,\*/ elementN)
```
Where `TypedArray` is one of:
* [`Int8Array`](../int8array)
* [`Uint8Array`](../uint8array)
* [`Uint8ClampedArray`](../uint8clampedarray)
* [`Int16Array`](../int16array)
* [`Uint16Array`](../uint16array)
* [`Int32Array`](../int32array)
* [`Uint32Array`](../uint32array)
* [`Float32Array`](../float32array)
* [`Float64Array`](../float64array)
* [`BigInt64Array`](../bigint64array)
* [`BigUint64Array`](../biguint64array)
### Parameters
`elementN` Elements of which to create the typed array.
### Return value
A new [`TypedArray`](../typedarray) instance.
Description
-----------
Some subtle distinctions between [`Array.of()`](../array/of) and `TypedArray.of()`:
* If the `this` value passed to `TypedArray.of()` is not a constructor, `TypedArray.of()` will throw a [`TypeError`](../typeerror), where `Array.of()` defaults to creating a new [`Array`](../array).
* `TypedArray.of()` uses `[[Set]]` where `Array.of()` uses `[[DefineOwnProperty]]`. Hence, when working with [`Proxy`](../proxy) objects, it calls [`handler.set()`](../proxy/proxy/set) to create new elements rather than [`handler.defineProperty()`](../proxy/proxy/defineproperty).
Examples
--------
### Using of()
```
Uint8Array.of(1); // Uint8Array [ 1 ]
Int8Array.of("1", "2", "3"); // Int8Array [ 1, 2, 3 ]
Float32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ]
Int16Array.of(undefined); // Int16Array [ 0 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.of](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `of` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.of` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.from()`](from)
* [`Array.of()`](../array/of)
| programming_docs |
javascript TypedArray.prototype.buffer TypedArray.prototype.buffer
===========================
The `buffer` accessor property represents the [`ArrayBuffer`](../arraybuffer) referenced by a *TypedArray* at construction time.
Try it
------
Description
-----------
The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the *TypedArray* is constructed and cannot be changed. *TypedArray* is one of the [TypedArray objects](../typedarray#typedarray_objects).
Because a typed array is a *view* of a buffer, the underlying buffer may be longer than the typed array itself.
Examples
--------
### Using the buffer property
```
const buffer = new ArrayBuffer(8);
const uint16 = new Uint16Array(buffer);
uint16.buffer; // ArrayBuffer { byteLength: 8 }
```
### Accessing the underlying buffer from a sliced array view
```
const buffer = new ArrayBuffer(1024);
const arr = new Uint8Array(buffer, 64, 128);
console.log(arr.byteLength); // 128
console.log(arr.buffer.byteLength); // 1024
console.log(arr.buffer === buffer); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-%typedarray%.prototype.buffer](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `buffer` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
javascript TypedArray.prototype.toString() TypedArray.prototype.toString()
===============================
The `toString()` method returns a string representing the specified array and its elements. This method has the same algorithm as [`Array.prototype.toString()`](../array/tostring). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
toString()
```
### Return value
A string representing the elements of the typed array.
Examples
--------
The [`TypedArray`](../typedarray) objects override the `toString` method of [`Object`](../object). For `TypedArray` objects, the `toString` method joins the array and returns one string containing each typed array element separated by commas. For example, the following code creates a typed array and uses `toString` to convert the array to a string.
```
const numbers = new Uint8Array([2, 5, 8, 1, 4]);
numbers.toString(); // "2,5,8,1,4"
```
JavaScript calls the `toString` method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation.
### Compatibility
If a browser doesn't support the `TypedArray.prototype.toString()` method yet, JavaScript will call the `toString` method of [`Object`](../object):
```
const numbers = new Uint8Array([2, 5, 8, 1, 4]);
numbers.toString(); // "[object Uint8Array]"
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.tostring](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `toString` | 7 | 12 | 51 | 10 | 11.6 | 5.1 | ≤37 | 18 | 51 | 12 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`TypedArray.prototype.join()`](join)
javascript TypedArray.prototype.every() TypedArray.prototype.every()
============================
The `every()` method tests whether all elements in the typed array pass the test implemented by the provided function. This method has the same algorithm as [`Array.prototype.every()`](../array/every). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Arrow function
every((element) => { /\* ... \*/ } )
every((element, index) => { /\* ... \*/ } )
every((element, index, array) => { /\* ... \*/ } )
// Callback function
every(callbackFn)
every(callbackFn, thisArg)
// Inline callback function
every(function(element) { /\* ... \*/ })
every(function(element, index) { /\* ... \*/ })
every(function(element, index, array){ /\* ... \*/ })
every(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` A function to test for each element.
The function is called with the following arguments:
`element` The current element being processed in the typed array.
`index` The index of the current element being processed in the typed array.
`array` The typed array `every` was called upon.
`thisArg` Optional
A value to use as `this` when executing `callbackFn`.
### Return value
`true` if the callback function returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for every array element; otherwise, `false`.
Description
-----------
The `every` method executes the provided `callbackFn` function once for each element present in the typed array until it finds the one where `callbackFn` returns a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value. If such an element is found, the `every` method immediately returns `false`. Otherwise, if `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value for all elements, `every` returns `true`.
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `every`, it will be used as callback's `this` value. Otherwise, the value `undefined` will be used as its `this` value. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
`every` does not mutate the typed array on which it is called.
Examples
--------
### Testing size of all typed array elements
The following example tests whether all elements in the typed array are bigger than 9.
```
function isBigEnough(element, index, array) {
return element >= 10;
}
new Uint8Array([12, 5, 8, 130, 44]).every(isBigEnough); // false
new Uint8Array([12, 54, 18, 130, 44]).every(isBigEnough); // true
```
### Testing typed array elements using arrow functions
[Arrow functions](../../functions/arrow_functions) provide a shorter syntax for the same test.
```
new Uint8Array([12, 5, 8, 130, 44]).every((elem) => elem >= 10); // false
new Uint8Array([12, 54, 18, 130, 44]).every((elem) => elem >= 10); // true
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.every](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `every` | 45 | 12 | 37 | No | 32 | 9.1 | 45 | 45 | 37 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.every` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.some()`](some)
* [`Array.prototype.every()`](../array/every)
javascript TypedArray.prototype.set() TypedArray.prototype.set()
==========================
The `set()` method stores multiple values in the typed array, reading input values from a specified array.
Try it
------
Syntax
------
```
set(array)
set(array, targetOffset)
set(typedarray)
set(typedarray, targetOffset)
```
### Parameters
`array` The array from which to copy values. All values from the source array are copied into the target array, unless the length of the source array plus the target offset exceeds the length of the target array, in which case an exception is thrown.
`typedarray` If the source array is a typed array, the two arrays may share the same underlying [`ArrayBuffer`](../arraybuffer); the JavaScript engine will intelligently **copy** the source range of the buffer to the destination range.
`targetOffset` Optional
The offset into the target array at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0).
### Return value
[`undefined`](../undefined).
### Exceptions
[`RangeError`](../rangeerror) Thrown if one of the two conditions is met:
* An element will be stored beyond the end of the typed array, either because `targetOffset` is too large or because `array` or `typedarray` is too large.
* `targetOffset` is negative.
Examples
--------
### Using set()
```
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
uint8.set([1, 2, 3], 3);
console.log(uint8); // Uint8Array [ 0, 0, 0, 1, 2, 3, 0, 0 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.set](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `set` | 7 | 12 | 4 | 10 | 11.6 | 5.1 | 4 | 18 | 4 | 12 | 4.2 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.set` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
* [`TypedArray`](../typedarray)
* [`ArrayBuffer`](../arraybuffer)
javascript TypedArray.prototype.findLast() TypedArray.prototype.findLast()
===============================
The `findLast()` method iterates a [typed array](../typedarray#typedarray_objects) in reverse order and returns the value of the first element that satisfies the provided testing function. If no values satisfy the testing function, [`undefined`](../undefined) is returned.
See also the [`findLastIndex()`](findlastindex) method, which returns the index of the found element instead of its value.
Try it
------
Syntax
------
```
// Arrow function
findLast((element) => { /\* ... \*/ } )
findLast((element, index) => { /\* ... \*/ } )
findLast((element, index, array) => { /\* ... \*/ } )
// Callback function
findLast(callbackFn)
findLast(callbackFn, thisArg)
// Inline callback function
findLast(function(element) { /\* ... \*/ })
findLast(function(element, index) { /\* ... \*/ })
findLast(function(element, index, array){ /\* ... \*/ })
findLast(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` A function used to test elements in the typed array.
The function is called with the following arguments:
`element` The current element in the typed array.
`index` The index (position) of the current element in the typed array.
`array` The typed array that `findLast()` was called on.
The callback must return a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value to indicate an appropriate element has been found. The value of this element is returned by `findLast()`.
`thisArg` Optional
Object to use as [`this`](../../operators/this) when executing `callbackFn`.
### Return value
The element in the typed array with the highest index value that satisfies the provided testing function; [`undefined`](../undefined) if no matching value is found.
Description
-----------
The `findLast()` method executes the `callbackFn` function once for each index of the typed array in descending-index order until the `callbackFn` returns a [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value. `findLast()` then returns the value of that element and stops iterating through the typed array. If `callbackFn` never returns a truthy value, `findLast()` returns [`undefined`](../undefined).
`callbackFn` is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed.
If a `thisArg` parameter is provided to `findLast()`, it will be used as the `this` for each invocation of the `callbackFn`. If it is not provided, then [`undefined`](../undefined) is used.
The `findLast()` method does not mutate the typed array on which it is called, but the function provided to `callbackFn` can.
The range of elements processed by `findLast()` is set before the first invocation of `callbackFn`. Elements that are appended to the typed array after the call to `findLast()` begins will not be visited by `callbackFn`. If an existing, unvisited element of the typed array is changed by `callbackFn`, its value passed to the visiting `callbackFn` will be the value at the time that `findLast()` visits that element's index.
**Warning:** Concurrent modification of the kind described in the previous paragraph frequently leads to hard-to-understand code and is generally to be avoided (except in special cases).
Examples
--------
### Find a prime number in a typed array
The following example finds the value of the last element in the typed array that is a prime number (or returns [`undefined`](../undefined) if there is no prime number).
```
function isPrime(element) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
let uint8 = new Uint8Array([4, 6, 8, 12]);
console.log(uint8.findLast(isPrime)); // undefined (no primes in array)
uint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]);
console.log(uint8.findLast(isPrime)); // 11
```
### All elements are visited and may be modified by the callback
The following examples show that all elements *are* visited, and that the value passed to the callback is their value when visited:
```
// Declare array with no elements at indexes 2, 3, and 4
// The missing elements will be initialized to zero.
const uint8 = new Uint8Array([0, 1, , , , 5, 6]);
// Iterate through the elements in reverse order.
// Note that all elements are visited.
uint8.findLast((value, index) => {
console.log(`Visited index ${index} with value ${value}`);
});
// Shows all indexes, including deleted
uint8.findLast((value, index) => {
// Modify element 3 on first iteration
if (index === 6) {
console.log("Set uint8[3] to 44");
uint8[3] = 44;
}
// Element 3 is still visited but will have a new value.
console.log(`Visited index ${index} with value ${value}`);
});
// Visited index 6 with value 6
// Visited index 5 with value 5
// Visited index 4 with value 0
// Visited index 3 with value 0
// Visited index 2 with value 0
// Visited index 1 with value 1
// Visited index 0 with value 0
// Deleting uint8[5] with value 5
// Visited index 6 with value 6
// Visited index 5 with value 5
// Visited index 4 with value 0
// Visited index 3 with value 44
// Visited index 2 with value 0
// Visited index 1 with value 1
// Visited index 0 with value 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.findlast](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `findLast` | 97 | 97 | 104 | No | 83 | 15.4 | 97 | 97 | 104 | 68 | 15.4 | 18.0 | 1.16 | No |
See also
--------
* [Polyfill of `TypedArray.prototype.findLast()` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.findLastIndex()`](findlastindex)
* [`TypedArray.prototype.find()`](find)
* [`TypedArray.prototype.every()`](every)
javascript TypedArray.prototype.filter() TypedArray.prototype.filter()
=============================
The `filter()` method creates a new typed array with all elements that pass the test implemented by the provided function. This method has the same algorithm as [`Array.prototype.filter()`](../array/filter). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Try it
------
Syntax
------
```
// Arrow function
filter((element) => { /\* ... \*/ } )
filter((element, index) => { /\* ... \*/ } )
filter((element, index, array) => { /\* ... \*/ } )
// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
// Inline callback function
filter(function(element) { /\* ... \*/ })
filter(function(element, index) { /\* ... \*/ })
filter(function(element, index, array){ /\* ... \*/ })
filter(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` Function to test each element of the typed array.
The function is called with the following arguments: `(element, index, array)`. Return `true` to keep the element, `false` otherwise.
`thisArg` Optional
Value to use as `this` when executing `callbackFn`.
### Return value
A new typed array with the elements that pass the test.
Description
-----------
The `filter()` method calls a provided `callbackFn` function once for each element in a typed array, and constructs a new typed array of all the values for which `callbackFn` returns [a value that coerces to `true`](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). `callbackFn` is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Typed array elements which do not pass the `callbackFn` test are skipped, and are not included in the new typed array.
`callbackFn` is invoked with three arguments:
1. the value of the element
2. the index of the element
3. the typed array object being traversed
If a `thisArg` parameter is provided to `filter()`, it will be passed to `callbackFn` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
`filter()` does not mutate the typed array on which it is called.
The range of elements processed by `filter()` is set before the first invocation of `callbackFn`. Elements which are appended to the typed array after the call to `filter()` begins will not be visited by `callbackFn`. If existing elements of the typed array are changed, or deleted, their value as passed to `callbackFn` will be the value at the time `filter()` visits them; elements that are deleted are not visited.
Examples
--------
### Filtering out all small values
The following example uses `filter()` to create a filtered typed array that has all elements with values less than 10 removed.
```
function isBigEnough(element, index, array) {
return element >= 10;
}
new Uint8Array([12, 5, 8, 130, 44]).filter(isBigEnough);
// Uint8Array [ 12, 130, 44 ]
```
### Filtering typed array elements using arrow functions
[Arrow functions](../../functions/arrow_functions) provide a shorter syntax for the same test.
```
new Uint8Array([12, 5, 8, 130, 44]).filter((elem) => elem >= 10);
// Uint8Array [ 12, 130, 44 ]
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.filter](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `filter` | 45 | 12 | 38 | No | 32 | 9.1 | 45 | 45 | 38 | 32 | 9.3 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.filter` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.every()`](every)
* [`TypedArray.prototype.some()`](some)
* [`Array.prototype.filter()`](../array/filter)
| programming_docs |
javascript TypedArray.prototype.forEach() TypedArray.prototype.forEach()
==============================
The `forEach()` method executes a provided function once per array element. This method has the same algorithm as [`Array.prototype.forEach()`](../array/foreach). *TypedArray* is one of the [typed array types](../typedarray#typedarray_objects) here.
Syntax
------
```
// Arrow function
forEach((element) => { /\* ... \*/ } )
forEach((element, index) => { /\* ... \*/ } )
forEach((element, index, array) => { /\* ... \*/ } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function(element) { /\* ... \*/ })
forEach(function(element, index) { /\* ... \*/ })
forEach(function(element, index, array){ /\* ... \*/ })
forEach(function(element, index, array) { /\* ... \*/ }, thisArg)
```
### Parameters
`callbackFn` Function that produces an element of the new typed array.
The function is called with the following arguments:
`element` The current element being processed in the typed array.
`index` The index of the current element being processed in the array.
`array` The array `forEach()` was called upon.
`thisArg` Optional
Value to use as `this` when executing `callbackFn`.
### Return value
[`undefined`](../undefined).
Description
-----------
The `forEach()` method executes the provided `callbackFn` once for each element present in the typed array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value [`undefined`](../undefined).
`callbackFn` is invoked with **three arguments**:
* the **element value**
* the **element index**
* the **typed array being traversed**
If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callbackFn` when invoked, for use as its `this` value. Otherwise, the value [`undefined`](../undefined) will be passed for use as its `this` value. The `this` value ultimately observable by `callbackFn` is determined according to [the usual rules for determining the `this` seen by a function](../../operators/this).
The range of elements processed by `forEach()` is set before the first invocation of `callbackFn`. Elements that are appended to the typed array after the call to `forEach()` begins will not be visited by `callbackFn`. If the values of existing elements of the typed array are changed, the value passed to `callbackFn` will be the value at the time `forEach()` visits them; elements that are deleted before being visited are not visited.
`forEach()` executes the `callbackFn` function once for each typed array element; unlike [`every()`](every) and [`some()`](some) it, always returns the value [`undefined`](../undefined).
Examples
--------
### Logging the contents of a typed array
The following code logs a line for each element in a typed array:
```
function logArrayElements(element, index, array) {
console.log(`a[${index}] = ${element}`);
}
new Uint8Array([0, 1, 2, 3]).forEach(logArrayElements);
// Logs:
// a[0] = 0
// a[1] = 1
// a[2] = 2
// a[3] = 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-%typedarray%.prototype.foreach](#) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `forEach` | 45 | 12 | 38 | No | 32 | 10 | 45 | 45 | 38 | 32 | 10 | 5.0 | 1.0 | 4.0.0 |
See also
--------
* [Polyfill of `TypedArray.prototype.forEach` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
* [`TypedArray.prototype.map()`](map)
* [`TypedArray.prototype.every()`](every)
* [`TypedArray.prototype.some()`](some)
* [`Array.prototype.forEach()`](../array/foreach)
javascript DataView.prototype.setUint32() DataView.prototype.setUint32()
==============================
The `setUint32()` method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setUint32(byteOffset, value)
setUint32(byteOffset, value, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
`littleEndian` Optional Indicates whether the 32-bit int is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
[`undefined`](../undefined).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would store beyond the end of the view.
Examples
--------
### Using the setUint32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setUint32(1, 3);
dataview.getUint32(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setuint32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setuint32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setUint32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.byteLength DataView.prototype.byteLength
=============================
The `byteLength` accessor property represents the length (in bytes) of the dataview.
Try it
------
Description
-----------
The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned.
Examples
--------
### Using the byteLength property
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteLength; // 8 (matches the byteLength of the buffer)
const dataview2 = new DataView(buffer, 1, 5);
dataview2.byteLength; // 5 (as specified when constructing the DataView)
const dataview3 = new DataView(buffer, 2);
dataview3.byteLength; // 6 (due to the offset of the constructed DataView)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-dataview.prototype.bytelength](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-dataview.prototype.bytelength) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `byteLength` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`SharedArrayBuffer`](../sharedarraybuffer)
javascript DataView.prototype.setFloat64() DataView.prototype.setFloat64()
===============================
The `setFloat64()` method stores a signed 64-bit float (double) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setFloat64(byteOffset, value)
setFloat64(byteOffset, value, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
`littleEndian` Optional Indicates whether the 64-bit float is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
[`undefined`](../undefined).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would store beyond the end of the view.
Examples
--------
### Using the setFloat64 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setFloat64(0, 3);
dataview.getFloat64(0); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setfloat64](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setfloat64) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setFloat64` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.setInt16() DataView.prototype.setInt16()
=============================
The `setInt16()` method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setInt16(byteOffset, value)
setInt16(byteOffset, value, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
`littleEndian` Optional Indicates whether the 16-bit int is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
[`undefined`](../undefined).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would store beyond the end of the view.
Examples
--------
### Using the setInt16 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setInt16(1, 3);
dataview.getInt16(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setint16](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setint16) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setInt16` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.byteOffset DataView.prototype.byteOffset
=============================
The `byteOffset` accessor property represents the offset (in bytes) of this view from the start of its [`ArrayBuffer`](../arraybuffer) or [`SharedArrayBuffer`](../sharedarraybuffer).
Try it
------
Description
-----------
The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed.
Examples
--------
### Using the byteOffset property
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteOffset; // 0 (no offset specified)
const dataview2 = new DataView(buffer, 3);
dataview2.byteOffset; // 3 (as specified when constructing the DataView)
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-get-dataview.prototype.byteoffset](https://tc39.es/ecma262/multipage/structured-data.html#sec-get-dataview.prototype.byteoffset) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `byteOffset` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
* [`SharedArrayBuffer`](../sharedarraybuffer)
javascript DataView.prototype.setFloat32() DataView.prototype.setFloat32()
===============================
The `setFloat32()` method stores a signed 32-bit float (float) value at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
setFloat32(byteOffset, value)
setFloat32(byteOffset, value, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to store the data.
`value` The value to set.
`littleEndian` Optional Indicates whether the 32-bit float is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is written.
### Return value
[`undefined`](../undefined).
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would store beyond the end of the view.
Examples
--------
### Using the setFloat32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.setFloat32(1, 3);
dataview.getFloat32(1); // 3
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.setfloat32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.setfloat32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `setFloat32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.getInt32() DataView.prototype.getInt32()
=============================
The `getInt32()` method gets a signed 32-bit integer (long) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getInt32(byteOffset)
getInt32(byteOffset, littleEndian)
```
### Parameters
`byteOffset` The offset, in bytes, from the start of the view where to read the data.
`littleEndian` Optional Indicates whether the 32-bit int is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
A signed 32-bit integer number.
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would read beyond the end of the view.
Description
-----------
There is no alignment constraint; multi-byte values may be fetched from any offset.
Examples
--------
### Using the getInt32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getInt32(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getint32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getint32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getInt32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.getUint32() DataView.prototype.getUint32()
==============================
The `getUint32()` method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getUint32(byteOffset)
getUint32(byteOffset, littleEndian)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
`littleEndian` Optional Indicates whether the 32-bit int is stored in [little- or big-endian](https://developer.mozilla.org/en-US/docs/Glossary/Endianness) format. If `false` or `undefined`, a big-endian value is read.
### Return value
An unsigned 32-bit integer number.
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would read beyond the end of the view.
Description
-----------
There is no alignment constraint; multi-byte values may be fetched from any offset.
Examples
--------
### Using the getUint32 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getUint32(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getuint32](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getuint32) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUint32` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
javascript DataView.prototype.getUint8() DataView.prototype.getUint8()
=============================
The `getUint8()` method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the [`DataView`](../dataview).
Try it
------
Syntax
------
```
getUint8(byteOffset)
```
### Parameters
`byteOffset` The offset, in byte, from the start of the view where to read the data.
### Return value
An unsigned 8-bit integer number.
### Errors thrown
[`RangeError`](../rangeerror) Thrown if the `byteOffset` is set such as it would read beyond the end of the view.
Description
-----------
There is no alignment constraint; multi-byte values may be fetched from any offset.
Examples
--------
### Using the getUint8 method
```
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.getUint8(1); // 0
```
Specifications
--------------
| Specification |
| --- |
| [ECMAScript Language Specification # sec-dataview.prototype.getuint8](https://tc39.es/ecma262/multipage/structured-data.html#sec-dataview.prototype.getuint8) |
Browser compatibility
---------------------
| | Desktop | Mobile | Server |
| --- | --- | --- | --- |
| | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js |
| `getUint8` | 9 | 12 | 15 | 10 | 12.1 | 5.1 | 4 | 18 | 15 | 12.1 | 5 | 1.0 | 1.0 | 0.10.0 |
See also
--------
* [`DataView`](../dataview)
* [`ArrayBuffer`](../arraybuffer)
| programming_docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.